Using Operators and Decision Constructs
Using Operators and Decision Constructs
This domain covers operator precedence, short-circuit evaluation, increment/decrement, assignment operators, and the if, switch, and ternary decision forms. The exam favors expressions that look plausible but fail at compile time or surprise you at runtime.
Core rules
- Precedence runs from postfix and unary, through multiplicative, additive, shift, relational, equality, bitwise, logical, ternary, to assignment. Parentheses override it.
&&and||short-circuit;&and|evaluate both sides. The condition ofif/whilemust beboolean.i++returns the old value then increments;++iincrements then returns. Integer division truncates toward zero;%takes the sign of the dividend.- Compound assignments such as
s += 1include an implicit cast. switchacceptsbyte,short,char,int,String, andenum. Case labels must be compile-time constants, unique, and compatible with the selector. Fall-through continues untilbreak;defaultmay appear anywhere. Anullselector throwsNullPointerException.
Worked example
int i = 1;
int j = i++ + ++i;
System.out.println(i + " " + j);
Evaluation is left to right. i++ yields 1 and leaves i = 2; ++i makes i = 3 and yields 3; so j = 4 and the output is 3 4.
Traps
if (x = 1)is an assignment and fails unlessxis boolean; use==.==compares references for objects;equalscompares content when overridden.- A
switchonStringusesequalssemantics, but a null selector is not handled gracefully. - Watch overflow and sign effects in
byte/shortarithmetic, which promotes toint. - The ternary operator may promote both branches to a common type.