25 March 2002
This lecture covers the reading in Day 3: ABC's of Java |
A statement is a command that you write in your program.
A statement must end with a semicolon (;) so that the parser in the Java
compiler (javac) knows you end this point to be the end of your statement.
System.out.println("Hello Luke"); // pass a string argument to a method
double bodyTemperature = 98.6; // assign a value to a primitive variable
HumanBeing.inalienableRight = pursuitOfHappiness; // assign a value to a property of an object
Comments are for human code readers. The compiler ignores comments.
Insert comments in your code that you, and others who will use your code, know
what the code is about.
It is more common for code to have too few comments than too many comments.
In the preceding statements, a comment follows each statement.
Two slash characters (//) define the comment through the end of the current
line.
/* A slash followed by an asterisk defined the beginning of a multi-line comment, which ends with the reverse, an asterisk, followed by a slash */
An expression is a statement that returns a value.
In both examples below, the Java virtual machine will:
sum = priceOfItem1 + priceOfItem2; // the return value is stored in the variable sum
selfEvidentTruth = HumanBeing.IsCreatedEqual(); // boolean return value must be true or false
A declaration is a statement that lets the compiler know that we are going to use a variable to refer to a value of a certain type.
An assignment gives (assigns) a value to a variable. Typically, in Java, we assign a value to a variable when we declare that variable.
For example,
int temperature = 70; //
Fahrenheit
float drunk = .01; // in percent
final int BOILING_POINT = 212; // a constant
// We will learn about arrays in detail later.
// What follows is an array of characters
// for the 7 days of the week.
// (Single quotes are for chars.)
// Each element has a unique index.
// The first 's' (Sunday) has the index of zero.
// The second 's' (Saturday) has the index of 6.
char[] daysOfTheWeek = {'s', 'm', 't', 'w', 't', 'f', 's'};
// Use double quotes for strings.
String[] myDays = {"Sunday", "Monday", "Tuesday"};
A literal is different from a variable. Whereas a variable is name for a storage area for a value that can change, a literal is the direct representation of a value.
double sum = 382.36; String firstName = "Luke"; // string literal inside quotation marks boolean isExpensive = false;
Here are character literals you might use:
// character literal inside single quote marks '\n' new line '\t' tab
A variable in a program is something with a name, the value of which can vary.
The syntax to declare a variable is to specify the type, then specify the name of the variable.
You can also assign a value to the variable when you declare it.
<type> <name> [= <value>];
// brackets mean optional
The syntax to assign a value to a variable is to put the name of the variable, followed by an equal sign (=) and the new value. The equal sign is the assignment operator.
<name> = <value>;
A constant (also called a constant variable) is a variable which is assigned a value once and
cannot be changed afterward (during execution of the program).
The compiler
optimizes a constant for memory storage and performance.
The keyword final signals the declaration of a constant:
Examples of constants
varName; // not capitalized initially, but each subsequent word in the name is capitalized
methodName(); // not capitalized initially, but each subsequent word in the name is capitalized
CONST_NAME // all capital letters with underscore to separate words in the name
ClassName // initial capital letter and capital letter for each word in the name
The concept of scope (Day 5, p. 114) is fundamental.
Scope is the block of code in which a variable exists and is available for use.
The scope (or visibility) of a variable depends upon WHERE you declare it.
You might declare a variable within a block of code that is a:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/scope.html
Sun's tutorial exposes a common error involving the concept of scope:
The final line won't compile because the local variableif (...) { int i = 17; ... } System.out.println("The value of i = " + i); // error
i
is out of
scope. The scope of i
is the block of code between the {
and }
. The i
variable does not exist anymore after the
closing }
.
QUESTION: Can you use have an instance variable with exactly the same name as a local variable?
A variable is a name for a piece of memory that stores a value. Each variable must have a name.
Unlike JavaScript and Visual Basic, Java is a strongly typed programming language, which means that you must declare the data type of a variable.
A variable can be any of the following types:
Numbers are represented in memory using bits, a bit is the smallest unit that
a computer can work with.
A bit has two possible values, 0 or 1.
Everything in a computer is represented using different numbers of bits.
A number is represented by a series of bits which represent different powers of
2.
An 8 bit number (byte):
Value of the number | Bits |
0 | 00000000 = (0*2^0) |
1 | 00000001 = (1*2^0) |
4 = 4 + 0 + 0 | 00000100 = (1*2^2) + (0*2^1) + 0^0 |
8 = 8 + 0 + 0 + 0 | 00001000 = (1*2^3) + (0*2^2) + (0*0^1) + 0^0 |
13 = 8 + 4 + 1 | 00001101 = (1*2^3) + (1*2^2) + (1*0^1) + 2^0 |
255 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 | 11111111 = ... |
A given variable is either a primitive (basic type) or an object.
Each primitive data type has a range of values, which determines its size in memory
Type | Size | Range | Example |
Integer types | |||
byte | 8 bits | -128 to 127
-28 to (28-1) |
Colors (RGB) ASCII characters |
short | 16 bits | -32,768 to 32,767
-216 to (216-1) |
Unicode (world languages) |
int | 32 bits | -232 to (232-1) | counters in loops |
long | 64 bits | -264 to (264-1) | big numbers |
Floating point types | |||
float | 32 bits | 3.40282e+38 | floating point (currency, temperature, length) |
double | 64 bits | 1.79769e+308 | floating point (large numbers or high precision, such as for astronomy or subatomic physics) |
Special types | |||
boolean | Java reserves 8 bits but only uses 1 | true false Note: These values are keywords. |
logic test with if |
char | 16 bits (2 bytes) | unicode characters (whereas other languages use 1-byte ASCII text characters) http://www.unicode.org/unicode/standard/WhatIsUnicode.html |
alphabets and numerals |
Sun's Java Tutorial contains a program that outputs the largest value of the
primitive types.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html
Java stores each primitive type in a fixed amount of memory and Java directly
manipulates the values for primitives.
However, objects and arrays do not have a standard size, and they can become
quite large. Therefore, Java manipulates these reference types by reference.
Whereas the reference types do not have a standard size, the references to
reference types do have a standard size.
Reference types differ from primitives in the way values are copied and compared.
David will explain arrays. For now, just be aware that an array stores multiple variables of
Examples of possible arrays
In the geeky language of programming (and mathematics), we say that operators
operate on operands.
In the case of sum = cost1 + cost2
for example, the operators are the addition operator (+)
and the assignment operator (=). The operands
are that on which the operators operate, namely, the variables cost1,
cost2, and sum.
If you write a Java statement such as:
int totalDaysInYear = 365;
The assignment operator (=) assigns the integer value of 365 to the
variable named totalDaysInYear.
Point location = new Point(4,3);
The assignment operator (=) assigns x- and y-coordinate values.
The new operator creates a new instance of a
class and returns a reference to that instance.
(More on this next week.)
The arithmetic operators return a number.
numeric return value = <operand1> <operator> <operand2>;
example: myLongString = myShortString + myOtherString;
Note: These are binary operators because they operate on two things. How many binary operators are there in the following application?
class Weather { public static void main(String[] arguments) { float fah = 86; System.out.println(fah); // To convert Fahrenheit into Celsius // Begin by subtracting 32 fah = fah - 32; // Divide the answer by 9 fah = fah / 9; // Multiply that answer by 5 fah = fah * 5; System.out.println(fah); float cel = 33; System.out.println(cel); // To convert Celsius into Fahrenheit // Begin by multiplying it by 9 cel = cel * 9; // Divide the answer by 5 cel = cel / 5; // Add 32 to the answer cel = cel + 32; System.out.println(cel); } }
The unary minus operator ( - ) converts a positive value into a negative value.
How about this case? What will be the value of y?
Here's some handy shortcuts:
x += y; // x = x + y
x -= y // x = x - y
x *= y; // x = x * y
x /= y; // x = x / y
Here's some more complete reference tables:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.html#assignment
Operator | Use | Equivalent to |
---|---|---|
+= |
op1 += op2 |
op1 = op1 + op2 |
-= |
op1 -= op2 |
op1 = op1 - op2 |
*= |
op1 *= op2 |
op1 = op1 * op2 |
/= |
op1 /= op2 |
op1 = op1 / op2 |
%= |
op1 %= op2 |
op1 = op1 % op2 |
&= |
op1 &= op2 |
op1 = op1 & op2 |
|= |
op1 |= op2 |
op1 = op1 | op2 |
^= |
op1 ^= op2 |
op1 = op1 ^ op2 |
<<= |
op1 <<= op2 |
op1 = op1 << op2 |
>>= |
op1 >>= op2 |
op1 = op1 >> op2 |
>>>= |
op1 >>>= op2 |
op1 = op1 >>> op2 |
Operator | Use | Description |
---|---|---|
?: |
op1 ? op2 : op3 |
If op1 is true, returns op2 . Otherwise,
returns op3 . |
[]
| type []
| Declares an array of unknown length, which contains type elements. |
[]
| type[ op1 ]
| Creates and array with op1 elements. Must be used with
the new operator. |
[]
| op1[ op2 ]
| Accesses the element at op2 index within the array op1 .
Indices begin at 0 and extend through the length of the array minus one. |
.
| op1.op2
| Is a reference to the op2 member of op1 . |
()
| op1(params)
| Declares or calls the method named op1 with the specified
parameters. The list of parameters can be an empty list. The list is
comma-separated. |
(type)
| (type) op1
| Casts (converts) op1 to type . An exception will be thrown
if the type of op1 is incompatible with type . |
new
| new op1
| Creates a new object or array. op1 is either a call to a
constructor, or an array specification. |
instanceof
| op1 instanceof op2
| Returns true if op1 is an instance of op2 |
These short cut unary operators increment or decrement a number by one.
Operator | Use | Description |
---|---|---|
++ |
op++ |
Increments op by 1; evaluates to the value of op before
it was incremented |
++ |
++op |
Increments op by 1; evaluates to the value of op after it
was incremented |
-- |
op-- |
Decrements op by 1; evaluates to the value of op before
it was decremented |
-- |
--op |
Decrements op by 1; evaluates to the value of op after it
was decremented |
Note the difference between prefix versus post-fix.
Logical operators test a condition by comparing values and return a boolean value (true or false).
Here's two comparison operators in a sequence:
isBigSum = sum > 100;
The variable isBigSum gets the value true only if the sum is
greater than 100.
Note: Do not confuse the two forward slashes of comments (//) with the two "pipes" of one of the logical operators (||).
Truth table
Operand1 | Operand2 | == | != | && | || |
true | true | true | false | true | true |
true | false | false | true | false | true |
false | true | false | true | false | true |
false | false | true | false | false | false |
Multiplication occurs before addition
total = 2 + 3 * 4; // evaluates to (3 * 4) + 2,
which is 14
total = (2 + 3) * 4; // evaluates to 5 * 4, which is 20
Fortunately, whatever you put in parenthesis has precedence over what is not in parenthesis.
Table 3.6 on p. 79 gives a complete list of operator precedence.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html
The Java programming language allows you to construct compound expressions
and statements from various smaller expressions as long as the data types
required by one part of the expression matches the data types of the other.
Here's an example of a compound expression:
In this particular example, the order in which the expression is evaluated is unimportant because the results of multiplication is independent of order--the outcome is always the same no matter what order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results depending on whether you perform the addition or the division operation first:x * y * z
You can specify exactly how you want an expression to be evaluated by using balanced parenthesesx + y / 100 //ambiguous
(
and )
. For example to make the
previous expression unambiguous, you could write:
If you don't explicitly indicate the order in which you want the operations in a compound expression to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent:(x + y)/ 100 //unambiguous, recommended
When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first. This will make your code easier to read and to maintain.x + y / 100 x + (y / 100) //unambiguous, recommended
The following table shows the precedence assigned to the operators. The operators in this table are listed in precedence order: the higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same line have equal precedence.
postfix operators | [] . (params) expr++ expr-- |
unary operators | ++expr --expr +expr -expr ~
! |
creation or cast | new (type)expr |
multiplicative | * / % |
additive | + - |
shift | << >> >>> |
relational | < > <= >= instanceof |
equality | == != |
bitwise AND | & |
bitwise exclusive OR | ^ |
bitwise inclusive OR | | |
logical AND | && |
logical OR | || |
conditional | ? : |
assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated in left-to-right order. Assignment operators are evaluated right to left.
David will explain string arithmetic. Here, I just show what it looks like
because it is part of the Day 3 chapter (p. 80).
System.out.println(fah + " degrees Fahrenheit is
...");
System.out.println(fah + " degrees Celsius\n");
System.out.println(cel + " degrees Celsius is ...");
System.out.println(cel + " degrees Fahrenheit");
_________________________
course
homepage course
calendar