Professional Documents
Culture Documents
Operators and
Statements
HENNING ARTHUR
Operators
Arithmetic operators
+, -, *, /, %
Numeric promotion
byte/short/char → int → long
float → double
Unary operators
!, -
Increment/Decrement operators
++, --
Logical operators
&, |, ^
&&, || - short-circuit operators
Operators
Assignment Operators
=
Compound Assignment Operators
+=, -=, *=, /=
Equality Operators
==, !=
Relational Operators
<, <=, >, >=
Ternary Operator
booleanExpression ? expression if true : expression if false;
Exam essentials
What data type (or types) will allow the following code snippet to compile?
(Choose all that apply)
byte x = 5;
byte y = 10;
_____ z = x + y;
A. int
B. long
C. boolean
D. double
E. short
F. byte
Statements
if
If-then
Put braces for readability
If no braces, only first line is executed after if
If-then-else
Watch out for unreachable code on else-if branches
Review questions
Switch
switch(variableToTest) {
case constantExpression1:
// Branch for case1;
break;
case constantExpression2:
// Branch for case2;
break;
...
default:
// Branch for default
}
Statements
switch
While
while(booleanExpression) {
// Body
}
Do-while
do {
// Body
} while (booleanExpression);
Executed at least once
Review questions
For
for(initialization; booleanExpression; updateStatement)
Each component is optional
For each
for(datatype instance : collection)
Review questions
Example
int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}};
OUTER_LOOP: for(int[] mySimpleArray : myComplexArray) {
INNER_LOOP: for(int i=0; i<mySimpleArray.length; i++) {
System.out.print(mySimpleArray[i]+"\t");
}
System.out.println();
}
Advanced flow control
break/continue
Break
Stops and exits the enclosing statement (loop)
Continue
Finishes the current iteration of the loop, and moves to the next one
Review questions