CHAPTER 2 Operators and Statements
1. Binary Arithmetic Operators
Includes addition(+), subtraction(-), multiplication(*), division(/) and modulus(%).
All arithmetic operators may be applied to any java primitives, except boolean and String.
Only addition operators + and += may be applied to String values, which results String concatenation
1) Numeric Promotion
-If two values have two different data types, Java will automatically promote one of the values to the larger of the two data types;
-If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value's data type;
-Smaller data types, namely byte, short, and char, are first promoted to int any time they're used with a Java binary arithmetic operator, even if neither of the operands is int;
-After all promotions has occured and the operands have the same data type, the resulting value will have the same data type as its promoted operands;
2. Unary Operators
1) Logical complement and Negation operators
You can't apply logical complement ! to a numeric expression, nor can you apply a negation operator - to a boolean expression.
int x = -5;
booean y = !true;
2) Increment ++ and Decrement Operators --
pre-increment and pre-decrement operators: new value returned;
post-increment and post-decrement operators: original value returned.
int x = 5;
int y = ++x; // x=6, y=6
int z = x++; // z=6, x=7
3. Additional Binary Operators
1) assignment operators =
Java will automatically promote from smaller to larger data types, but will throw compile exception if it detects you are trying to convert from larger to smaller data types.
byte x = 5;
short y = 5;
int z = 5;
long w = 5;
byte x = 5+5;
short r = y + z; // compile error
short r = (short) (y + z); //casting int to short
The return of assignment is the result of the assignment.
int y;
int x = (y=10); // y=10, x=10
2) compound assignment operator
includes +=, -=, *=, /=, %=
automatically cast result.
long x = 5;
int y = 5;
y = x + y; // compile error
y +=x; // first cast y to long, then cast the result to int
3) relational operators
compare two expressions and return a boolean value
<, >, <=, >=, instanceof
4) logical operators
&: and is true only if both operands are true.
|: inclusive OR is true if either operand is true.
^: exclusive OR is true if the operands are different.
5) short-circuit operators
&&, || are identical to &, | except that the right-hand of the expression may never be evaluated if the result can be determined by the left-hand of the expression.
if(x != null && x.getValue()<5){} // prevent nullPointerException from being thrown if x=null
6) equality operators
==, !=
used in three scenarios
-comparing two numeric primitive types, values are automatically promoted
-comparing two boolean values
-comparing two objects, including null and String
4. Statements
A Java statement is a complete unit of execution in Java, terminated with semicolon(;)
Control flow statement break up the flow of the execution by using decision making, looping, and branching, allowing the application to selectively execute particular segments of the code.
A block of code in Java is a group of zero or more statements between balanced braces {}.
1) if-then-else statement
if (boolean expression)
{ branch if true} // {} optional for single statement, but necessary for multiple lines.
else if (boolean expression)
{branch if true} // {} optional for single statement, but necessary for multiple lines.
else
{branch if false} // {} optional for single statement, but necessary for multiple lines.
Ternary operation is a condensed form of if-then-else statement that returns a value.
boolean expression ? expression1 : expression2
if (boolean expression){expression1}
else{expression2}
example:
int y = 10;
int x = (y>5) ? (y*2) : (y*3); //equals to following code
int x;
if(y>5){x = y*2;}
else{x=y*3;}
expression 1 and expression 2 must be a return value, not a statement. example as following.
System.out.println(x < 5 ? "x < 5" :"x >= 5");
x < 5 ? System.out.println("x < 5") : System.out.println("x >= 5"); //compile error
2) switch statement
switch(variableToTest){
case constantexpression1:
//branch for case1;
break;
case constantexpression2:
//branch for case2;
break;
......
default:
// branch for default;
break;
}
Data types supported:
-int and Integer
-byte and Byte
-short and Short
-char and Character
-String
-emum values
boolean, long, floating-point and their associated classes are not supported by switch statement
The values in each case statement must be compile-time constant values of the same data type as the switch value.
This means you can only use literals, enum constants or final constant variables of the same data type.
Final constant variable is marked with final modifier and initialized with a literal value in the same expression in which it is declared.
procedures to execute:
-jump to match case and execute
- if there is no break keyword in the case, execute the following cases until encountering an break keyword
-if there is no matched case, execute the default case; if there is no break keyword in default case, execute the following cases until encountering an break keyword.
3) while and do-while statement
while (booleanExpression){ //{} optional for single statement, but necessary for multiple lines.
//codebody
}
To avoid infinite loop, to make sure two things:
- the loop variable is modified
-the termination condition will be eventually reached
do{
//codebody
} while(booleanExpression); //guarantees that the statement will be executed at once
4) for statement
for (initialization; booleanExpression; updateStatement) { //{} optional for single statement, but necessary for multiple lines.
//body
}
Note:
-each section is separated by semicolon, which is required;
-initialization and update sections may contain multiple statements, separated by comma;
-variables declared in initialization block of a for loop are only accessible within the for loop
examples:
infinite loop:
for( ; ; ) System.out.println("hello");
multiple terms:
for(long x =1, y=2; x<5 && y<10; x++,y++){}
redeclaration error:
int x = 0;
for(long x =1, y=2; x<5 && y<10; x++,y++){}
incompatible error:
for(long x =1, int y=2; x<5 && y<10; x++,y++){}
outside the loop error:
for(long x =1, y=2; x<5 && y<10; x++,y++){}
System.out.println(x); //compiler error
5) for-each statement
for (datatype instance : collection){ //{} optional for single statement, but necessary for multiple lines.
//body
}
the right-side of the for-each statement must be a java built-in array or an object whose class implements java.lang.Iterable.
6. advanced flow control
nested loops
label: optional pointer that allows the application to jump to it or break from it, a single word proceed by colon (:).
break: transfer the flow of control to the enclosing statement, terminate the nearest inner loop it is currently in the process if there is not label.
continue: terminate the current loop, and continue the next loop