Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8): Using Operators and Decision Constructs

Java SE 8 Programmer I (OCAJP 8) · Work through your exam, one topic at a time.

All guide sections

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 of if/while must be boolean.
  • i++ returns the old value then increments; ++i increments then returns. Integer division truncates toward zero; % takes the sign of the dividend.
  • Compound assignments such as s += 1 include an implicit cast.
  • switch accepts byte, short, char, int, String, and enum. Case labels must be compile-time constants, unique, and compatible with the selector. Fall-through continues until break; default may appear anywhere. A null selector throws NullPointerException.

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 unless x is boolean; use ==.
  • == compares references for objects; equals compares content when overridden.
  • A switch on String uses equals semantics, but a null selector is not handled gracefully.
  • Watch overflow and sign effects in byte/short arithmetic, which promotes to int.
  • The ternary operator may promote both branches to a common type.