Oracle Java Foundations study materials
Oracle Java Foundations study resources

Oracle Java Foundations: Using Operators and Decision Constructs

Oracle Java Foundations · Work through your exam, one topic at a time.

All guide sections

Using Operators and Decision Constructs

Arithmetic and increment

Division of two integers truncates toward zero, and the sign of % follows the left operand (-7 % 3 is -1). Post-increment returns the old value, pre-increment the new one: int x = 5; int y = x++ + x; yields y = 11 with x = 6.

Logical and comparison operators

&& and || short-circuit; &, |, ^ on booleans evaluate both operands. == compares primitive values but reference identity for objects, so use equals for String content. The ternary operator requires both branches to be compatible types. && binds tighter than ||, and assignment is lowest.

if / else and switch

Conditions must be boolean, so if (x = 5) and while (1) are compile errors. A switch selector may be byte, short, char, int, their wrappers, String, or an enum - never long, float, double, or boolean. Case labels must be compile-time constants, unique, and of a type assignable to the selector; default may appear anywhere. Without break (or a return/throw), execution falls through into the next case.

Traps that appear in questions

Dangling-else binds to the nearest if. Comparing floating-point values with == is unreliable. A switch on a String throws NullPointerException when the selector is null. Arrow-form switch (case 1 -> ...) does not fall through and does not need break.

Rule of thumb

Before answering any expression question, rewrite it one operator at a time using precedence: parentheses, unary/++, * / %, + -, relational, ==/!=, &&, ||, ternary, assignment.

Worked example

int a = 5; if (a > 3 && a++ < 10) { } - a becomes 6 because the right side is evaluated. With || and a true left side, the right side would be skipped entirely.