1
Java Programming
Java Syntax from the Ground Up
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 3
Lexical Structure - Unicode Character Set
Most languages use a 7/8 bit ASCII code table for encoding (128/256 different characters)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 4
Lexical Structure - Unicode
Unicode is 16 bit (32,768 different characters)Special unicode editor might be requiredor, encode characters as \uxxxx
xxxx is in hexExamples:
\ux0020 is space \u03c0 is π
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 5
Lexical Structure -Case-Sensitivity and Whitespace
Java is cAse-SEnsitIve ;-)While, WHILE, and while are different
thingsWhile and WHILE are identifiers.while is a reserved word.
If you have declared a variable i you cannot refer to it as I.
Whitespace is ignored (spaces, tabs and newlines)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 6
Comments
Comments are ignored by the compiler; there are three different types of comments:Single line comment ( //… )int i = 0; // initialize the loop variable
Multi-line comments (type 1, /* … */)/* * First, establish a connection to the server. * If the connection attempt fails, quit right away
*/
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 7
Comments
Multi-line comments (type 2, /** … */, doc-comment) used for generating automatic Javadoc documentation/** * Upload a file to a web server * * @param file The file to upload * @return <tt>true</tt> on success. * <tt>false</tt> on failures. * @author David Flanagan */
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 9
Reserved Words
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 10
Reserved Words (Modifiers)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 11
Reserved Words (Types)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 12
Reserved Words (Exceptions)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 13
Reserved Words (Control Flow)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 14
Reserved Words (Literals)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 15
Reserved Words (Modularity)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 16
Reserved Words (OO stuff)
abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private syncrhonized while
class false instanceof protected this
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 18
Literals
Integer and floating point numbers, characters, strings, as well as true, false and null
1, 1.0, 1f, 1L, ‘1’, “one”, true, null
(int, double, float, long, char, string, boolean, class type)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 19
Punctuation
Separators( ) { } [ ] < > : ; , . @
Operators+ - * / % & | ^ << >> >>>+= -= *= /= %= &= |= ^= <<= >>= >>>== == != < <= > >=! ~ && || ++ ? :
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 20
Primitive Data Types
Java supports 8 primitive typesType Contains Default Size Rangeboolean true or false false 1 bit N/A
char Unicode character \u0000 16 bits \u0000 to \uffff
byte Signed integer 0 8 bits -128 to 127
short Signed integer 0 16 bit -32,768 to 32767
int Signed integer 0 32 bit -2,147,483,648 to 2,147,483,647
long Signed integer 0 64 bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float IEEE 754 floating point
0.0 32 bit +/-1.4E-45 to +/-3.4028235E+38
double IEEE 754 floating point
0.00 64 bit +/-4.9E-324 to +/-1.7976931348623157E+308
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 21
The boolean Type
Represents a truth value.Only two possible values: true or false
Not like C where 0 is false and anything else is true.
Cannot be compared to integers.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 22
The char Type
Represents unicode characterschar c = ’A’;char tab = ’\t’;char apostrophe = ’\’’;char nul = ’\000’;char aleph = ’\u05D0’;
Note the difference here:char \u05D0 = ’\u05D0’;
\u05D0 is a variable name is unicode‘\u05D0’ is a character literal in unicode.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 23
The char Type
Escape sequence Character value
\b Backspace
\t Horizontal tab
\n Newline
\f Form feed
\r Carriage return
\” Double quote
\’ Single quote
\\ Backslash
\xxx/ Latin-1 character xxx octal value (0 to 377)
\uxxxx Unicode character xxxx hexadecimal value
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 24
Strings
String is not a primitive type, but a class.
Java does allow string Literals”Hello, World””This is a string!”
Or some code:String greeting = “Hello stranger!”;String \u03c0 = "\"\'\u03c0\'\"";
delcares a string ”’π’” in a unicode variable called \u03c0
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 25
Integer Types
byte, short, integer, and long are all signed integer types (no unsigned integer types exist in java)255 (decimal) = 0xff (hex) = 0377 (octal)1234 is a int value, 1234L is a long value
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 26
Overflow
Neither the compiler nor the runtime system catches overflow
byte b1 = 127, b2 = 1;byte sum = (byte)(b1 +
b2);
What is the value of sum?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 27
Wrapper Classes
Classes for each integer type exist: Byte, Short, Integer, Long(Note the capital letter)
Byte.MAX_VALUEByte.MIN_VALUE
gives the max/min byte values
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 28
Floating-Point Types
Real numbers in Java are represented by the float and double data types.
123.450.0.011.2345E02 // 1.2345*102, or 123.451e-6 // 1*106, or 0.000001
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 29
Floating-Point Types
Just like integer values are int types by default, floating point values are double by default.
double d = 6.02E23;float f = 6.02E23f;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 30
Floating-Point Types
int i = 1/0 causes an exception, division by 0 is illegal in integer arithmetic.
double inf = 1.0/0.0 does not cause an exception.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 31
Floating-Point Types
4 Special ‘values’ for floating points:
double inf = 1.0/0.0; // prints Infinitydouble neginf = -1.0/0.0; // prints -Infinitydouble negzero = -1.0/inf; // prints -0double NaN = 0.0/0.0; // prints NaN
Infinity + anything = Infinity-0 == 0NaN is not equal to anything (incl. itself)Double.isNaN() checks for NaN
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 32
Primitive Type Conversions
Conversion is legal between integer and floating points (incl. chars, but not boolean)Widening: A value is converted to a type
with a larger range of legal values:
double d = 10;
double is a ‘wider’ type than int.Widening is always allowed
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 33
Primitive Type Conversions
Narrowing: Converting a value to a type that has a smaller range of legal values.
Ok sometimes: int value 13 can be converted to a byte, but 1300 cannot (byte range is -128 to 127)
Narrowing conversions can be forced by a cast.
int i = 13;
byte b = (byte)i; // force int to be converted to a byte
i = (int)13.456; // force this double literal to the int 13
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 34
Primitive Type Conversions
To
From boolean byte short char int long float double
boolean --- N N N N N N N
byte N --- Y C Y Y Y Y
short N C --- C Y Y Y Y
char N C C --- Y Y Y Y
int N C C C --- Y Y* Y
long N C C C C --- Y* Y*
float N C C C C C --- Y
double N C C C C C C ---
Y = yes, the conversion is a widening.N = not, the conversion cannot occur.C = yes, the conversion must be a narrowing cast.Y* = yes, by automatic widening that can cause loss of precision. This can happen when converting int and long to float and double.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 35
Expressions and Operators
The Java interpreter evaluates expressions to compute its value.
The simplest expressions are called primary expressions, and consists of literals and variables: 1.7 // a floating point literal
true // a boolean literalsum // a variable
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 36
Expressions and Operators
The value of a literal is the value itself:The value of 1.7 is 1.7!
The value of a variable is the value stored in the location in memory represented by that variable
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 37
Expressions and Operators
We use operators together with primary expressions to form more interesting expressions:
sum = 1.7sum = 1 + 2 +3*1.2 + (4+8)/3.0sum/Math.sqrt(3.0 * 1.234)(int)(sum + 33)
Note, all valid expressions; assignments are not statements but expressions, they have a value.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 38
Operator Summary
P A Operator Operand(s) types Operation Performed
15 L .
[ ]
( args )
++/--
Object, member
Array, int
Method, arglist
Variable
Object member access
Array element access
Method invocation
Post increment/decrement
14 R ++/--
+/-
~
!
Variable
Number
Integer
Boolean
Pre increment/decrement
Unary plus/minus
Bitwise complement
Boolean NOT
13 R new
( type )
Class, any
Type, any
Object creation
Cast (type conversion)
12 L *,/,% Number, number Multiplication, division, remainder
11 L +,-
+
Number, number
String, any
Addition, subtraction
String concatenation
10 L <<
>>
>>>
Integer, integer
Integer, integer
Integer, integer
Left shift ( * 2)
Right shift w/sign extension ( / 2)
Right shift w/zero extension
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 39
Operator Summary
P A Operator Operand(s) types Operation Performed
9 L <, <=
>, >=
Instanceof
Number, number
Number, number
Reference, type
Less than, less than or equal
Greater than, greater than or equal
Type comparison
8 L ==
!=
==
!=
Primitive, primitive
Primitive, primitive
Reference, reference
Reference, reference
Equal (have identical values)
Not equal (have different values)
Equal (refer to the same object)
Not equal (refer to different objects)
7 L &
&
Integer, integer
Boolean, boolean
Bitwise AND
Boolean AND
6 L ^
^
Integer, integer
Boolean, boolean
Bitwise XOR
Boolean XOR
5 L |
|
Integer, integer
Boolean, boolean
Bitwise OR
Boolean OR
4 L && Boolean, boolean Conditional AND
3 L || Boolean, boolean Conditional OR
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 40
Operator Summary
P A Operator Operand(s) types Operation Performed
2 R ? : Boolean, any Conditional (ternary) operator
1 R =
*=, /=, %=,
+=, -=, <<=,
>>=, >>>=,
&=, ^=, |=
Variable, any
Variable, any
Assignment
Assignment with operation
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 41
Precedence
Precedence specifies the order in which operations are performed. Eg.:
1 + 2 * 3 // == 7
* has higher precedence than +, and is performed first. Precedence can be overruled using ( ):
(1 + 2) * 3 // == 9
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 42
Associativity
Associativity governs the order of operation when we use operators of the same precedence.a = b += c = -~d is: a = (b += (c = -(~d)))Precedence can be overridden using ( )
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 43
Operand Number and Type
Operators take different number of operands:Unary operators take one operand
-8 (unary minus)~i (bitwise complement)
Binary operators take two operandsa + 8 (binary plus)a << 8 (binary left shift)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 44
Operand Number and Type
Operators take different number of operands:Ternary operators take three operands
x > y ? x : y (called a ternary expression)Like an ‘if’-statement, but as an expressionmin = (x > y) ? x : y
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 45
Operand Number and Type
Not all operators work on all types.-”Hello”
(you cannot negate a string)a + false
(+ does not work with booleans)x > y ? “x is greater” : y
(Why is this one wrong? ;-) )
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 46
Return Type
Just as an operator only works on specific types, it also returns a value of a specific type (sometimes dependent on the type of the operands)1 + 1 = 2 (int + int = int)1.0 + 2.0 = 3.0
(double + double = double)1 + 2.0 = ???
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 47
Return Type
Not all operators return values of the same type as their operands:a < 0 is of boolean typex < y ? “x is smaller” : “y is smaller”always returns values of string type, but x and y can be any type compatible with <.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 48
Side Effects
int a=2;a = ++a + ++a * a++;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 49
Order of Evaluation
The order in which operands are evaluated is always left to rightTaking into account
Associativity of operatorPrecedense of operatorParentehsis ( )
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 50
Order of Evaluation
Some operators do not evaluate all their operands:x ? y : z (Ternary), only x and the
chosen branch are evaluatedx && y. If x is false there is no need to
evaluate y.x || y. if x is true there is no need to
evaluate y.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 51
Order of Evaluation
int a = 2;
int v = ++a + ++a * ++a;
What is the value of v after theassignment?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 52
Arithmetic Operators
Addition (+)Normally + adds numbers:
2 + 2 = 4 (integer + integer = integer)2 + 2.0 = 4.0 (integer + double = double)
Can be used on strings:“Hello “ + “world” = “Hello world”
Be careful when mixing strings and numbers“Total: “ + 3 + 4 = “Total: 34”3 + 4 + “ is the total” = “7 is the total”
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 53
Arithmetic Operators
Other arithmetic operators:Subtraction (-), both binary and unaryMultiplication(*)Division (/ )
7/3 = 27/3.0f = 2.33333337/3.0 = 2.33333333333333357/0 causes a runtime error (An exception)7/0.0 evaluates to (positive infinity)0.0/0.0 evaluates to NaN (Not a Number)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 54
String Concatenation Operator
Reminder: + and += can be used withstrings.
Objects are converted to strings with the toString() method (more about that later)
“Once a string, always a string”: remember to use ( ) around arithmetic when mixed with strings.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 55
Increment/Decrement Operators
++ or -- increment/decrement its single operand by 1.i = 1;
j= i++;
Is equivalent to
i = 1;
j = i + 1;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 56
Increment/Decrement Operators
a++ is not the same as ++a.a++ uses the value of a then incrementint a = 1;System.out.println(a++); // prints 2
++a increments the value of a then uses itint a = 1;System.out.println(++a); // prints 1
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 57
Increment/Decrement Operators
Be REAL careful about the ++ and -- operators.
Most of time x++ is equivalent to x = x + 1
But not always:
a[i++]++;a[i++] = a[i++] + 1;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 58
Comparison Operators
Used to test equality and size (order)== equal (values!)
Eg. a == b tests is the value stored in a is the same as the value stored in b
!= not equala != b is the same as !(a == b)
Careful: = is not a test for equality, it is assignment
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 59
Comparison Operators
<, >, <=, >=For comparing values that are ordered
!=, == works on ‘anything’<, >, <=, >= works on numbers only
The result of all of these operators is a boolean value: either true or false
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 60
Comparison Operators
Example:boolean b;int a, c;a = 10;c = 4;
b = !(a > c);
What is the value of b?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 61
Boolean Operators
A number of operators work on boolean values. They are either binary (two operands) or unary (one operand), but all produce a boolean result: && Conditional AND
true && true == true true && false == false false && false == false false && true == false
Example: (x < 10 && y > 3)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 62
Boolean Operators
|| Conditional ORtrue || true == truetrue || false == truefalse || false == falsefalse || true == true
! Boolean NOT!true == false!false == true
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 63
Short Circuit Boolean Evaluation
Remember: Evaluation from LEFT to RIGHT, and with SCBE.
To avoid SCBE and force evaluation of all operand expressions use & and | instead.
& and | used with integer operands computes a bit-wise operation. and | used with integer operands computes a bit-wise operation.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 64
Boolean Operators
^ is exclusive or (XOR)true ^ true == falsetrue ^ false == truefalse ^ true = truefalse ^ false = false
Can be used on integers as wellWith boolean operands: ^ is the same as !=
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 65
Bitwise Operators
Used to manipulate the individual bits of integral values/variables:~ bitwise complement& bitwise AND (we already saw this with
booleans)| bitwise OR^ bitwise XOR
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 66
Shift Operators
Shift operators moves bits left or right:<< Left Shift:
10 << 1 // 00001010 << 1 == 00010100 = 20 = 10*2
>> Signed Right Shift:27 >> 3 // 00011011 >> 3 == 00000011 = 3 / 27/(2*2*2)
-50 >> 2 // 11001110 >> 2 == 11110011 = -13 = -50/(2*2)
>>> Unsigned Right Shift:-50 >>> 2 // 0xFFFFFFCE >>> 2 = 0x3FFFFFF3
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 67
Assignment Operator
We have already see this one:= (and not == which is comparison)
Others exist:+= for example: a += 2; which is the same
as a = a + 2;Others: -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 68
The Conditional Operator
The only operator to take three operands: … ? … : …Example:a > 10 ? b+1 : c-2
If a>10 then the entire thing evaluates to the value of the expression b+1, else the value of c-2
Really is an if-expression (as opposed to an if statement.
Can be used as an expression: d = a>2 ? 4 : 8;
The two last operand expressions must be the same type
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 69
The Conditional Operator
Example of the conditional operator Compute max value of x and y and assign to z;
if (x > y) z = x;else z = y;
Orz = (x > y) ? x : y;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 70
The instanceof Operator
We will return to this one later Determines if the left hand side object expression is
an object of a certain class type: o instanceof A
True if o is an object based on class A.
Note, if o instanceof A is true, and B is a super class of A, o instanceof B will also be true.
Tells us when it is safe to ‘cast’ an object reference to a different class type.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 71
Special Operators
A number exist, let’s just consider explicit castingExplicit casting is “changing the type of a
value”(byte) 28
(float) 3.14Objects can be cast as well.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 72
Statements
A Statement is a single command that has no return value. They include Expression statements (Expressions where return values are
ignored) Compound (block) statements: { … } Empty statement: ; Local variable declarations: int a; If/else statement: if (…) … else … Switch statement: switch (…) { case ..: …. ….. } While statement: while (…) … Do statement: do … while (…) For statement: for (…;…;…) … Break- / continue- / return-statement
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 73
Expression Statements
An expression statement is an expression used as a statement (value of expression is ignored)a = 1;
a *= 2;
--c;
f(7);
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 74
Compound Statements
a = 10;
b = 1;
while (a > 0)
a = a - 1;
b = b * 2;
What is the value of a and bafter the loop?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 75
Compound Statements
a = 10;
b = 1;
while (a > 0)
a = a - 1;
b = b * 2;
What is the value of a and bafter the loop?
a = 0b = 2
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 76
Compound Statements
A compound statement is a number of statements grouped together using { }
a = 10;b = 1;
while (a > 0) { b = b * 2; a = a - 1;
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 77
The Empty Statement
The empty statement is just a semicolon: ;
for (int i=0; i<10; a[i++]++)
;
Rarely a use for it! The above example should be written differently
for (int i=0; i<10; i++) {
a[I]++;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 78
Local Variable Declarations
We know how to do these:<type> name;
<type> name = <expr>But for how long is a name ‘valid’?
The part of the code where a name can be referenced is called the name’s scope.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 79
Scope
{
int a = 10;
int b = 1;
while (a > 0) {
int c = b * 2;
b = c;
}
}
Scope of a in red
{int a = 10;int b = 1;while (a > 0) { int c = b * 2; b = c;
}}
{int a = 10;int b = 1;while (a > 0) { int c = b * 2; b = c;
}}
Scope of c in redScope of b in red
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 80
The scope of a local variable is the rest of the closest enclosing block! { } creates a block….. Others to come later
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 81
If-statements
Used for flow control (decisions)Two general forms:
if (<bexpr>)<then-stmt>
…
if (<bexpr>)<then-stmt>
else<then-stmt>
If <bexpr> evaluates to true,then the <then-stmt> is executed,If <bexpr> evaluates to false,execution continues at …
If <bexpr> evaluates to true,then the <then-stmt> is executed.If <bexpr> evaluates to false,then the <else-stmt> is executed
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 82
If-statements
Be careful about nested if-statements:if (i==j)
if (j==k)
System.out.println(“i = k”);
else
System.out.println(“i != j”);
An else always matches the inner-most if. To make sure you get it right use { }
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 83
If-statements
if (i==j) {
if (j==k) {
System.out.println(“i = k”);
}
} else {
System.out.println(“i != j”);
}
Technically { } and { } are not needed.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 84
If-statements
If-statements can also be chained:if (i == 2) { b = 3;} else if (i == 3) {b = 5;
} else if (i == 4) {b = 7;
} else {b = 9;
}
if (i == 2) b = 3;else if (i == 3)b = 5;
else if (i == 4)b = 7;
else b = 9;
or without { }
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 85
Switch-statement
A multi-case replacement for a lot of if-statementsif (n == 1) a = 2;else if (n == 2) a = 4;else if (n == 3) a = 6;else if (n == 4 || n == 5) a = 7;else a = 9;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 86
Switch-statement
A multi-case replacement for a lot of if-statementsif (n == 1) a = 2;else if (n == 2) a = 4;else if (n == 3) a = 6;else if (n == 4 || n == 5) a = 7;else a = 9;
switch (n) { case 1: a = 2; break; case 2: a = 4; break; case 3: a = 6; break; case 4: case 5: a = 7; break; default: a = 9; break;}
Same as
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 87
Switch-statement
A few things are important to remember about switch-statements.The default label is optional (just like else is!)
The break statement for each case is optional (but almost always needed)
When hitting a break (!) in a switch statement, control jumps to the end of it (I.e., the } )
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 88
Switch-statement
Consider this:a = b = c = 0;
switch (n) {
case 1: a = 1;
case 2:
case 3: b = 1;
default: c = 2;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 89
Switch-statement
Consider this:a = b = c = 0;
switch (n) {
case 1: a = 1;
case 2:
case 3: b = 1;
default: c = 2;
}
n a b c
1
2
3
4
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 90
Switch-statement
Consider this:a = b = c = 0;
switch (n) {
case 1: a = 1;
case 2:
case 3: b = 1;
default: c = 1;
}
n a b c
1 1 1 1
2
3
4
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 91
Switch-statement
Consider this:a = b = c = 0;
switch (n) {
case 1: a = 1;
case 2:
case 3: b = 1;
default: c = 1;
}
n a b c
1 1 1 1
2 0 1 1
3
4
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 92
Switch-statement
Consider this:a = b = c = 0;
switch (n) {
case 1: a = 1;
case 2:
case 3: b = 1;
default: c = 1;
}
n a b c
1 1 1 1
2 0 1 1
3 0 1 1
4
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 93
Switch-statement
Consider this:a = b = c = 0;
switch (n) {
case 1: a = 1;
case 2:
case 3: b = 1;
default: c = 2;
}
n a b c
1 1 1 1
2 0 1 1
3 0 1 1
4 0 0 1
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 94
While-statement
Simple looping mechanismwhile (<bexpr>)
<statement>While the <bexpr> is true, execute <statement> and go back and evaluate the <bexpr>
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 95
While-statement
Remember, if more than one statement is to be executed, use { }:
b = 1; b = 1;
while (a > 0) { while (a > 0)
a = a - 1; vs. a = a - 1;
b = b * 2; b = b * 2;
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 96
While-statement
Remember, if more than one statement is to be executed, use { }:
b = 1; b = 1;
while (a > 0) { while (a > 0)
a = a - 1; vs. a = a - 1;
b = b * 2; b = b * 2;
}
a = 0 and b = 2a a = 0 and b = 2
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 97
Do Statement
Almost like a while:
do statementwhile ( expression );
statement always executes at least once.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 98
While vs do
a = 100; a = 100;
b = 1; b = 1;
while (a > 0) { do {
a = a - 1; a = a - 1;
b = b * 2; b = b * 2;
} }
Are these two pieces of the same?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 99
While vs do
while (expression) do
statement statement while (expression)
Are these two pieces of the same? Always???
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 100
While vs do
b = 0; b = 0;
while (a > 0) { do {
b = b + 2; b = b + 2;
a = a - 1; a = a - 1;
} } while (a > 0)
For which values of a do they produce the same result?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 101
Do statement
Can we make a do loop work like a while loop?while (expression) statement
if (expression)
do
statement
while (expression)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 102
Do statement
Can we make a do loop work like a while loop?while (expression) statement
if (expression)
do
statement
while (expression)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 103
For statement
One last loop mechanism: the for loopfor (initialize; test; update)
statement
initialize is executed ONCEtest is executed BEFORE the statement; the
statement is executed for as long as test is true
update is executed after the statement
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 104
For statement
for (initialize; test; update)
statement
is equivalent toinitializetest; statement; update; test; statement; update; …test; statement; update; test;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 105
For statement
int result = 0;
for (int i=1; i<=100; i++) result = result + i;
Sums up the first 100 numbers. Note:
You may declare variables in the initializer. The scope of these variables is the body of the loop. More than one variable can be initialized and more than
one variable can be updated. If declaring one or more variable in the initializer nothing
else can go there!
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 106
For statement
int result, count, i;
for (result=0, count=0, i=0; i<=100; i=i+2, count++) result = result + i;
For loops can be written using while loops easily:
initialize;
while (test) {
statement;
update;
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 107
For/in statement
Special type of for loop:for (declaration : expression) statement
Often used to ‘iterate’ through a collection/arrayint[] primes = new int[] {2,3,5,7,9,11,13,17,19,23,29}for (int n: primes) System.out.println(n);
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 108
For/in statement
int[] primes = new int[] {2,3,5,7,9,11,13,17,19,23,29}for (int n: primes) System.out.println(n);
The base type of the iterating variable must match that of the collection.More on arrays soon!
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 109
Skipping for now
BreakContinueReturn
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 110
Skipping completely
SynchronizedThrow/exceptionsAssert
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 111
Methods
A method is a way to abstract away computation.Just like math: f(x,y) = x*x + y*y;
It has formal paramters (x,y) It has a (return) type: what ever type x*x + y*y is. It can be applied to many different pairs of actual
parameters: f(6,7), f(8,9), f(g(5),5),….
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 112
Methods
Simple example:public int f(int x, int y) {
int result;
result = x*x + y*y;
return result;
}
public is a modifier (more about that later)int is the type that the method returnsf is the name, int x, int y the formal
paramters.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 113
Methods
Simple example:public int f(int x, int y) {
int result;
result = x*x + y*y;
return result;
}
int a;
a = f(5,7);
5 and 7 are the actual parameters.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 114
Scoping in Methods
Methods have the same scoping rules as what we have used until now except for the parametersThe scope of a parameter is the entire body
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 115
Call by value
A method in Java uses call by value call semantics:void f(int a) {
a = 10000;
}
int a = 0;
f(a);
// value of a? The variable a is not passed to f, its VALUE is.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 116
Methods
When calling a method, the order of the actual parameters must match the order of the formal parameters.
The same number of actual parameters as formals must be passed to a method.
If a method does no return anything, its type is void.
Return value may be ignored.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 117
Arrays
An array is a collection of values all of the same type (more or less!)Either all of a primitive typeOr all of a reference type (more about that
later)Not a primitive type, but an object type.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 118
Arrays
Arrays are allocated dynamicallyCannot be allocated statically on the stack,
but must be on the heap.
int[] intArray;
declares a variable that can hold a reference to an array of integers.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 119
No Static Arrays
We cannot declare static arrays:
int[3] myLittleArray;
or
int myBigArray[1000];
are both illegal.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 120
Creating an array
All arrays must be allocated/created before they can be used.Unlike other primitives which are just there
when declaredint a; // you can assign to a
//and use it as an int
int[] as; // you cannot use as until
// it has been given a
// value
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 121
Creating an Array
Let us create an array of 100 integers:
int[] myInts;
myInts = new int[100];
Or
int[] myInts = new int[100];
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 122
Indexing an array
An array is indexed by an integer value starting at 0. The first element is at index 0, the second at index 1 etc.
int[] myInts = new int[100]; // index
0..99
for (int i=0; i<100; i++)
myInts[i] = i;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 123
Indexing an array
The first index of an array is index 0The last is l-1 where l is the length of
the array.The length can be obtained like this:
int len = myInts.length;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 124
We could redo the code from 2 slides ago:
int[] myInts = new int[100]; // index 0..99for (int i=0; i<myInts.length; i++)
myInts[i] = i;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 125
Initializing arrays
We can write code to initialize an array like on the previous slide.
Or we can do it when the array is created:int[] myInts = new int[]{0, 1, 2, 3, 4};
When initializing an array like this, no size is given. I.e., this is illegal: int[] myInts = new int[5]{0, 1, 2, 3, 4};
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 126
Call by reference vs call by value
Consider the following code:public static void foo(int a) {
a = 900; }
public static void main(String[] args) { int a = 0; foo(a); int b=0; foo(b);
}
What is the value of a and b after the call to foo?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 127
Call by reference vs call by value
Consider the following code:public static void foo(int a) {
a = 900; }
public static void main(String[] args) { int a = 0; foo(a); // the value of a is still 0 int b=0; foo(b); // the value of b is still 0
}
Remember, copies of the values of a and b are transferred to foo, and the a parameter belongs to foo, and not main!
CALL BY VALUE:COPIES of the
ACTUAL parametersare passed to the
method. Any changesmade to the parameterseffect only the FORMALparameters inside the
method, not the ACTUALparameters passed.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 128
Call by reference vs call by value
Consider the following code:public static void foo(int a) {
a = 900; }
public static void main(String[] args) { int a = 0; foo(a); // the value of a is still 0 int b=0; foo(b); // the value of b is still 0
}
Remember, copies of the values of a and b are transferred to foo, and the a parameter belongs to foo, and not main!
CALL BY VALUE:COPIES of the
ACTUAL parametersare passed to the
method. Any changesmade to the parameterseffect only the FORMALparameters inside the
method, not the ACTUALparameters passed.
CALL BY REFERENCE:Changes made to
the FORMAL parametersWILL effect the ACTUAL
parameters.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 129
Call by reference vs call by value
All primitives in Java are passed by value (call-by-value)
Arrays are passed by reference (call-by-reference) Any chances made in a method to an array
parameter will be made to the actual parameter
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 130
Call by reference
public class ArrayTest { public static void fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i; // <-- will change intArray }
public static void main(String[] args) { int[] intArray = new int[100]; fill(intArray);
for(int i=0;i<100;i++) System.out.println(intArray[i]); }}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 131
Aliasing
public class ArrayTest { public static int[] fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i;
return array; }
public static void main(String[] args) { int[] intArray = new int[100];
int[] newIntArray; newIntArray = fill(intArray);
for(int i=0;i<100;i++) { System.out.println(intArray[i]);
System.out.println(newIntArray[i]); } }}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 132
Aliasing
public class ArrayTest { public static int[] fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i;
return array; }
public static void main(String[] args) { int[] intArray = new int[100];
int[] newIntArray; newIntArray = fill(intArray);
for(int i=0;i<100;i++) { System.out.println(intArray[i]);
System.out.println(newIntArray[i]); } }}
intArray and newIntArraywill contain the same data.NOT copies of the samedata, but THE SAMEdata
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 133
Aliasing
public class ArrayTest { public static int[] fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i;
return array; }
public static void main(String[] args) { int[] intArray = new int[100] int[] newIntArray; newIntArray = fill(intArray);
for(int i=0;i<100;i++) { System.out.println(intArray[i]);
System.out.println(newIntArray[i]); }}
The integer array is onlyallocated once; all other‘copies’ of it are just copiesof ‘arrows’ pointing to the same set of integers.
This is called aliasingWhen a method is invoked with an array parameter it is passed by reference
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 134
Multi-dimensional Arrays
Java supports multi-dimensional arrays:int[][] twoDimArray;twoDimArray = new int[10][10];
This creates a 2D array indexed like this:twoDimArray[0][0] = 100;twoDimArray[9][9] = 900;
Java allows ‘ragged arrays’ (where higher dimensions’ entries aren’t the same length.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 135
Ragged Arrays
int[][] bs = new int[2][];bs[0] = new int[5];bs[1] = new int[]{1,2,3};
bs is 2 dimensional
bs[0] is 1 dimensional of type int[] bs[1] is 1 dimensional of type int[]
bs[0]
bs[1]
bs[0][0]Val: ?
bs[0][1]Val: ?
bs[0][2]Val: ?
bs[0][3]Val: ?
bs[1][0]Val: 1
bs[0][4]Val: ?
bs[1][1]Val: 2
bs[1][2]Val: 3
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 136
Multi-dimensional arrays
You may leave the allocation of a higherdimension to later (last slide), but you may not leave lower ones:
int[][] bs = new[][2]; // illegal
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 137
Multi-dimensional array constants
We can write constants of multi-dimensional type as well:
int[][] myInts = new int[][]{ {1,2},
{3,4,5,6},
{7,8,9} };
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 138
Copying arrays
As we have seen using = on array variables just copies a ‘pointer’
If we want to copy an entire array we can either use a for loop and copy the elements by hand, or use .clone()int[] a = new int[]{1,2,3};
int[] b = a.clone();
a[1] = 900; // a = {1,900,3}, b={1,2,3}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 139
Copying array
int[][] bs = new int[2][];
bs[0] = new int[]{100,200,300};
bs[1] = new int[]{1,2,3};
int[][] q = bs.clone();
bs[0][1] = 999;
System.out.println(q[0][1]);
What is printed?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 140
Copying array
int[][] bs = new int[2][];
bs[0] = new int[]{100,200,300};
bs[1] = new int[]{1,2,3};
int[][] q = bs.clone();
bs[0][1] = 999;
System.out.println(q[0][1]);
What is printed? 999
.clone() is a SHALLOWcopy - it copies only the TOP level. If an arraycontains entries that arereference, then they arecopied as REFERENCESnot as VALUES.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected]) 141
Traversing an array
We are familiar with this:int sum = 0;
for(int i=0; i<myArray.lengh; i++)
sum = sum + myArray[i]
We can use a different for-loop int sum = 0;
for (int e : myArray)
sum = sum + e;