CSCI111: Chapter 2

CSCI111: Notes Chapter 2
Basic Java Structural Components


Any language has a Syntax or Grammar. Computer languages are no different. SUN provides a Learning the Java Language Tutorial ... and the notes and text book are good to read as well to help in learning the language.

Java is an object-oriented language so it needs ways to write objects (in the form of classes), and then to say what these classes look like (remember - variables (properties/state) and methods (behavior)).
slides 65-70 from Ch. 1

Classes that are related are organized into packages. We have seen how java organizes classes into packages in the API and will look deeper into the API in lab 3.

Java Packages and Classes are defined by you (or by Sun in the API library) through Source files.

In this chapter we will talk about how to represent properties as variables and then how to use variables to make statements and write methods.

Comments:
When we write code we sometimes like to tell people what we are doing but we do not want Java to parse the words. In this case we use comments slide 48 from Ch. 1

/* continues until the next */
// until the end of the line
/** used to generate documentation automatically */          We will see how to do this (javadoc) in Lab 3.

Valid Identifiers (or variable names): (Types, Values and Variables) slide 49, 50 from Ch. 1

Some examples that are OK: Some examples that follow convention (Usually, do not use underscore, instead style is to use capitals for beginning of the second word): Examples in Java: Reserved Words/Keywords:
Words that Java uses for its own language constructs cannot be used by programmers for variables. These are called keywords and are reserved meaning you cannot use them for your variable names. Since there are a good number, here is a
link to them.

slides 51 and code for slide 52 of Ch. 1. NOTE: no space within variable names (discuss)

Primitive Data Types and Literals: (or variable values)

Every piece of data in a Java program is classified and stored in memory according to its data type. Some properties of objects are not other objects (with properties and methods), but rather simply numbers. In most object-oriented languages, numbers are represented differently because of this fact that they do not have "methods" of their own. Numbers are interpreted as things that we do things with, they do not have actions of their own. We call them "primitive data types".

Thus, there are two basic categories of data types in Java:

Primitive data types have a variable name and a (one) value - no methods. Primitive data types are "primitive" in that they are basic building blocks which do not have the complete object structure - the Java language defines how the values can be manipuated rather than the methods of a class.

Primitive data types are not Classes, they are simply a place in computer memory with a value. Every variable must be declared as a certain type and named (as defined above).

By convention:
Class names are started with capitals (Applet, Graphics, MyApplet).
Primitive data types, methods, and instance and class variable names are started with lower case (paint, myVariable)

Java uses five basic (primitive) element types: integer, floating point, boolean, character, and String*.
(Theoretically: four integer types, two floating-point types, char and boolean)

Integer: if you type 4, you get an int with value 4

Putting 0's in front means something completely different (base 8 and Hexadecimal (Base 16)
decimal octal hexadecimal
2.21 077 0xDC00

Integer:
Length Name
8 bits byte
16 bits short
32 bits int
64 bits long

Here is the range of values for each

Data Type Range
byte [-128 , 127]
short [-32768 , 32767]
int -2,147,483,648 to 2,147,483,647
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

The most common integer type is int.

Integer: if you type 4, you get an int with value 4. Usually programmers use int by default.
If you want it to be a long, you need to add an L (or lowercase l) at the end of the number.
long myNumber = 12345678900L;

Floating Point (Decimal)

Float:
Length Name
32 bits float
64 bits double

Here are some examples of numbers with decimal values:

3.14
3.1E12 means 3.1 X 1012
2e12 means 2 X 1012 (E or e makes no difference)
12.34f means 12.34 floating point
-32.0f means -32.0 floating point

You can use e or E (for powers of 10), f or F (for float), d or D (for double) but the d or D is not required since it is the default and hence usually omitted.
The f or F must be given for float types.

The ranges for these types are something like these given but I suggest you go to the Java Language Specification if you want a detailed explanation (for all intents and purposes - they allow big numbers):

Data Type Range
float +-1.4 * 10-45 to +-3.4 * 1038
double +-4.9 * 10-324 to +-1.8 * 10308
If you omit the f Java assumes double. So, what would be wrong with
float myValue = 12.3;
What would happen?

A variable must be declared before it can be used. Whatever type it is.


Even Duke has to sort out the right type!

Primitive Data Type - Boolean (boolean)

Booleans are used for logical reasoning and have two possible values:
true or false

They are not F, T, TRUE, or FALSE ... only true or false.

In Java (and in logic), the ! means not (or the opposite of) .
So if testMe is true, then !testMe is false.
If testMe is false, then !testMe is true.

Primitive Data Type - Character (char):

Characters are basically single characters. An easy way to think of them is what are the keys on a keyboard. Each "key" is a character. In Java we show something is a char by putting it in single quotes:
if you type 'a', you get a char with value a
char myCharacter = 'a';

Examples of some other "keystrokes" (special escape sequences) represented in Java:

\t (tab)
\b (backspace)
\n (linefeed)
\r (carriage return)
\f (form feed)
\" (double quote)
\' (single quote)
\\ (backslash)

These are often used within Strings (see below)

char myOtherCharacter = 'm';
Why the single quotes?

Summary of Primitive Data Types:

Review: Ch 2 slides 18-23

Strings

Strings are not primitive data types - they are a java class in the package java.lang. String: E.g. "Hello World"

Note that the API specification says that Strings are immutable. What does that mean?

Strings are often used for output

We have seen output on applets as
g.drawString("Hello", 100, 100);

What were the variables there for? And what about:
g.drawString("Hello" + " there", 100, 100);

When seen in Strings the + was concatenation. The same happens in the following line, but the area number is first converted by Java into a String...then it is concatenated g.drawString("Area is " + area, 100, 100);

More on Strings below, but here are the slides from the text on Strings and primitive data types

Review: Ch 2 slides 4-10 (Code examples: Countdown.java , Facts.java , Addition.java , Roses.java ) Notice that these all print to the console System.out.println.

Variables

How variable names and values and memory work

What happens in the computer when you do
int length= 20;

Variable declaration:
int length;
You can also declare a bunch of variables at once:
int length, width, area;
but it is good programming style to put variables that are related together and ones that are different on separate lines

Assignment statement:
variable = expression;
length = 40;
The place where it is stored (variable name for memory location) is on the left-hand side. On the right-hand side are expressions; expressions calculate to the values in those memory locations. Variables (left) are memory locations where the values of expressions (right) are stored once calculated.

Memory: variable names and values

We need to look carefully at Assignment statements. Consider

Type variableName = expression;

There are three important aspects in this description of a line of code:

(1) The left-hand side of the = sign is the place where the value of the variable is stored (variableName is a memory location).
Type variableName;
is declaring the Type of the variable that will be placed into the location of variableName.
Java needs to know the Type so it knows how much space it needs in memory at that location.

(2) The = sign is not like it is in algebra. In programming languages, the left side is a location or an address in memory.
An analogy would be like the old time card catalogs in libraries. You look up a title of a book to get a number for where the book is located. You do not go to the card catalog for the book, but for the book's location. The left-hand side of an equal sign (=) in programming languages is always just the location telling where the value for the variable can be found.
Since the variableName tells Java the location, then just like card catalog locations, you do not do any manipulation (arithmetic) to these numbers. The only thing on the left side of an equal sign in Java is a variableName which is a address.
and possibly the type of variable that will be placed into that location

(3) On the right-hand side are expressions; expressions calculate to the values that will be put into those memory locations.
variableNames (left-side) are memory locations where the values of expressions (right-side) are stored once calculated.

When the computer sees a variableName on the right-hand side of an = sign, it goes and gets the value at that location.
When it sees a variableName on the left-hand side of an = sign, it puts the result of the right side into the address of the left side variableName.

Literals

A literal is the source code representation of a fixed value. Literals are represented directly in your code without requiring computation. The examples below show how it is possible to assign a literal to a variable of a primitive type:
boolean result = true;
char capitalD = 'D';
byte b = 42;
short s = 5280;
int i = 100000;

We have set values like this in previous examples, but now if you hear the word literal, you know it is just a fixed value (like a number) to which you can set primitive data type variables.

slide 12-14
code

Calculations and Operators

What happens in the computer when you do
area = length * width;

Variables and a Program to dissect

Discuss: // calculate area of rectangle - version 1 import java.awt.*; import java.applet.Applet; public class Calculation extends Applet { public void paint(Graphics g) { int length; //declarations int width; int area; length= 20; // assignments width = 10; area = length * width; g.drawString("Area is " + area, 100, 100); // display the answer } }

Additional Potentials

Defaults
Sometimes you know what a variables value is going to be before anyone even uses a Class. Specifically, that variable value is always the same. This is often called the default. One can specify in the declaration the value as well if it is known for sure. I.e.,
float pi = 3.14f;

Constants

Actually though public final static double PI is in java.lang.Math    Here it is a constant    slide 15,16

For class variables, Java provides defaults of

Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false

Variables in methods (called local variables are different.

The compiler never assigns a default value to an uninitialized local variable.

If you cannot initialize your method variable when it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Increment and Assignment Shortcuts
Examples:

int n = 10; n = n + 1; n++; // an increment expression - if the + is post (after) then it adds after it uses n += 1; // essentially the same as n = n + 1; An increment expression has the side effect of incrementing the value by 1. If the operator ++ is a suffix (post), the value of the increment expression is the value of the variable before it is incremented. If the operator ++ is a prefix, the value of the increment expression is the value of the variable after it is incremented. (I.E., if the ++ is first it adds first.) Use sparingly to reduce confusion (often used only to increment loop variables). For example: int i = 0; int j = i++; // j is 0; i is 1 j = ++i; // if the + is pre (before) then it adds before it uses // j and i are both 2

Review and More!: Ch 2 slides 32-37 (see slides for x *= 3;, etc.)

Operators and Precedence

Precedence of operators is important here. On computers, the order is
  1. ()
  2. *, /, %
  3. +, -
meaning first
(1) anything in parentheses is done, then any operator in
(2) is done left to right and then any operator in
(3) is done left to right.
(Actually, there is
more, but this is good for our needs for now)

Multiplication in Java must have a *

You cannot use x to mean times and you cannot use no operator as in 6y for 6 times y. Nor can you use parentheses, as in y(y+1) Only * between each operand.
(Using y * (y+1) would be fine.)

The % stands for remainder. I.e., what is left after you divide. See text.

Review: slide 25-31

Careful with division on ints (Integers). Division on integers always yields an integer. So 1/2 is 0 (the answer (0.5) is truncated to 0.)

public class Division { public static void main (String args[]) { int b = 1; int c = 2; float d = b/c; System.out.println(b/c); System.out.println(d); } } Yields
boris:/user/faculty/amk/java/test> java Division      
0
0.0
Here is the file for you to use for testing future problems. Download it, compile it and run it. Then try your own expressions, recompile, run, etc

What does the following yield?
int half = 20000*(1/2)

type conversion

I have mentioned that Java can convert integers into a String (more below) The programmer can do cast conversion as well if desired.
Legal Conversions and casting
slide 39-43

System.out.println(((float)(10+11)/2));
Yields 10.5

Repeat: Very important

When an operator manipulates a mixture of int and float (or double) values, any integers are temporarily converted to float for the purpose of the calculation. E.g.,
7 / 2.0 => 7.0 / 2.0 => 3.5

The idea here is that no information is "added" - i.e., if I have 2 then it does not hurt to make it a 2.0 for computation in the method.

Ch 2 slides 39-43

The Role of Expressions
Anywhere you could put an integer, you can put an integer expression.
What does that mean?

Output
Above, I had a java application so I used System.out.println(b/c);

For an applet output could look like:
g.drawString("Area is " + area, 100, 100);

Be careful with concatenation! Consider the differences between:

g.drawString("Answer is " +1+2, 100, 100); and g.drawString("Answer is " +(1+2), 100, 100);

Declaring and Creating Objects slide 37-43

and more on Strings later

Java in a Nutshell also has some nice notes on syntax. Here is a summary page which shows example of various kinds of the Java Statements, Expressions, etc. from their online book.

Slides and code. Don't forget to look at chapter summaries and self-review questions.