Conditional Logic, Block Statements and Looping
Arithmetic Operators
Basic
Produce a result, no impact on values used.
1 + 2 = 3
5 - 4 = 1
4 * 2 = 8
13.0 / 5.0 = 2.6
13 / 5 - 2
13 % 5 = 3
Prefix & Postfix
Increase or decrease a value, replace original value.
int a = 5;
System.out.println(++a); // 6, increase before being used in an expression
System.out.println(a); // 6
int b = 5;
System.out.println(b++); // 5
System.out.println(b); // 6, increase after being used
Compound Assignment
Operate on a value, replace original value.
+= -= *= /= %=
Operator Precedence
Postfix (X++, X--) Prefix (++X, --X) Multiplicative (* / %) Additive (+ -)
Logical Operators
| Operator | What resolves to true | |
|---|---|---|
| AND | & | true & true |
| OR | | | false | true true | false true | true |
| XOR (exclusive or) | ^ | false ^ true true ^ false |
| NOT | ! | false |
Conditional Logical Operators
Similar to standard logical operators. Right side executes only when needed:
&&executes right only when left istrue||executes right only when left isfalse
| Operator | What resolves to true | |
|---|---|---|
| AND | && | true && true |
| OR | || | false || true true || ---- |
Q: So what's so different?
A: When you use &, both sides are executed. With &&, right side is not always be executed. Consider below example:
// this could crash if denom == 0, cause divided by 0 is not allowed
if ( denom != 0 & numer / denom > 10 ) {
}
// so, you should do this
if ( denom != 0 && numer / denom > 10 ) {
}
Condition Logic
Relational Operators
> >= < <= == !=
Conditional Assignment
result = condition ? true-value : false-value;
If-else
if ( condition ) {
statement;
}
else if ( condition ) {
statement;
}
else {
statement;
}
Block
Use { and } to create block.
Block and Variable Scope
Variable scope is limited to block.
Switch
Only primitive types supported (byte, short, int, long, char)
switch (value-to-test) {
case matching-value-1:
statements
break;
.
.
.
case matching-value-N:
statements
break;
default:
statements
}
Looping
While
while ( condition ) {
statement;
}
Do-while
do {
statment;
} while ( condition );
For
for (initialize; condition; update) {
statement;
}