5.3 if / if-else Statements & the Ternary Operator

Key Takeaways

  • Every if condition in Java must evaluate to boolean or Boolean; using an int (if (x)) or an int assignment (if (x = 3)) fails to compile

  • Assigning a boolean inside an if condition (if (flag = true)) compiles cleanly and evaluates to the assigned boolean value

  • Without braces, an if or else controls only one statement, and an else always binds to the nearest preceding unmatched if regardless of indentation

  • The ternary operator (cond ? expr1 : expr2) evaluates only the selected branch, skipping side effects in the unselected branch

  • Nested ternaries associate right to left. Numeric branches follow the Java SE 8 conditional type rules, and a reference conditional may use the assignment or invocation target type.

Last updated: November 2026

Decision statements control which path a Java program follows at runtime. While if and else look deceptively familiar, the 1Z0-808 exam packs them with compiler traps—most notably non-boolean conditions, = vs. == inside if, misleading indentation without braces, and subtle type rules in the ternary operator (?:).

Mandatory boolean Condition Rule

In Java, the condition inside if (...) must evaluate to boolean (or Boolean, which is unboxed). Java never converts numbers (0, 1), strings, or object references to boolean:

int x = 3;
if (x == 3) { }     // VALID: == produces boolean
// if (x) { }       // DOES NOT COMPILE: int cannot be converted to boolean
// if (x = 3) { }   // DOES NOT COMPILE: assignment yields int 3, not boolean

Now look closely at the boolean assignment trap—one of the highest-frequency traps on the exam:

boolean active = false;
if (active = true) {
    System.out.println("Active is now true");
}
System.out.println(active);

This compiles without error and prints both Active is now true and true! Why? Because active = true assigns true to the boolean variable active, and the assignment expression itself evaluates to boolean true. Whenever you see an if condition containing a boolean variable, verify whether the operator is = (assignment) or == (comparison).

Watch one more unboxing trap: if a Boolean wrapper is null, if (wrapperBool) compiles cleanly, then throws NullPointerException at runtime when Java tries to unbox null to a primitive boolean.

Braceless Bodies and the Dangling-else Rule

Braces { } are optional when an if or else body contains only one statement. However, indentation does not determine which statement belongs to the branch:

int score = 70;
if (score >= 90)
    System.out.println("Grade A");
    System.out.println("Honors"); // NOT part of the if! Always runs!

Output is Honors. Even worse, adding an else after two unbraced statements causes a compile-time error ('else' without 'if') because the second statement already closed the if.

The Dangling-else Rule

When if statements are nested without braces, an else binds to the nearest unmatched if available in that statement structure. Indentation cannot change the binding:

int a = 5, b = 10;
if (a > 10)
    if (b > 5)
        System.out.println("Both");
else
    System.out.println("Else ran");

Despite the indentation suggesting else belongs to if (a > 10), the compiler parses it as:

if (a > 10) {
    if (b > 5) {
        System.out.println("Both");
    } else {
        System.out.println("Else ran");
    }
}

Because a > 10 is false, neither branch runs and nothing is printed!

Caution

In if (cond); { work(); }, the semicolon is the whole body of the if. The separate block then runs unconditionally if evaluating the condition succeeds. An else immediately after the empty body can be legal, but one after that separate block cannot attach to the if.

else if Chains, Unreachable Branches & Variable Scope

An if / else if / else ladder evaluates conditions top-down and executes at most one branch—the first one whose condition is true:

int temp = 95;
if (temp > 70) {
    System.out.println("Warm");
} else if (temp > 90) {
    System.out.println("Hot");
} else {
    System.out.println("Cool");
}

This prints Warm—never Hot—because temp > 70 matches first. Note that Java does not report a compile error for a logically shadowed else if branch (temp > 90 after temp > 70), nor does if (false) { ... } fail to compile (JLS explicitly allows if (false) for conditional compilation, unlike while (false)).

However, definite assignment rules are enforced at compile time:

int discount;
boolean vip = true;
if (vip) {
    discount = 20;
}
// System.out.println(discount); // DOES NOT COMPILE: discount might not have been initialized

Even though vip is true on the line above, the compiler does not trace non-final variable values across if statements; adding an else { discount = 0; } satisfies definite assignment.

The Ternary Conditional Operator (? :)

Java's only ternary operator has the syntax:

booleanCondition ? expressionIfTrue : expressionIfFalse

Rule 1: Only the Selected Branch Evaluates

Just like && and ||, the ternary operator evaluates booleanCondition first and then evaluates only one of the two result expressions. Any increment, decrement, or method call in the unselected branch is skipped:

int x = 1, y = 1;
int z = (x < 5) ? x++ : y++;
System.out.println("x=" + x + ", y=" + y + ", z=" + z);
// Prints: x=2, y=1, z=1 (y++ never executed!)

Rule 2: Ternary Is an Expression, Not a Statement

A ternary is an expression. Use it in a value context, such as an initializer, a return expression, or a method argument:

  • Both branches must yield values (neither branch may invoke a void method, even inside System.out.println(...)).
  • Writing (x > 0) ? x++ : y++; as a standalone statement DOES NOT COMPILE (not a statement).

Rule 3: Nested Ternaries Are Right-Associative

When ternaries are chained without parentheses, Java groups from right to left:

int score = 75;
String label = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
// Parsed as: score >= 90 ? "A" : (score >= 80 ? "B" : (score >= 70 ? "C" : "F"))
System.out.println(label); // Prints: C

For clarity on tricky expressions like a ? b ? c : d : e, always match each ? with its corresponding : from the inside out.

Rule 4: Return-Type Compatibility (Assigning vs. Printing)

The compiler first classifies a conditional as boolean, numeric, or reference. For numeric conditionals, it determines the expression type before assignment. For reference conditionals in assignment or invocation contexts, the target type can apply to both result operands.

ExpressionCompiles?Result Type & Explanation
System.out.println(flag ? 10 : "ten");YesBoth branches fit the println(Object) overload, with boxing for the int branch
int n = flag ? 10 : "ten";No"ten" is String, incompatible with int
double d = flag ? 5 : 5.0;Yesint and double promote to double
int n = flag ? 5 : 5.0;NoResult type is double; cannot assign to int without cast
byte b = flag ? 1 : 127;NoBoth operands are int. If flag is an ordinary variable, the entire expression is not constant, so assignment cannot narrow it.
byte b = flag ? (byte) 1 : 127;YesWith a byte on one branch and an int constant that fits byte on the other, the conditional has type byte.
byte b = false ? 1 : 127;YesThe entire conditional is a constant expression of type int with value 127, so assignment narrows it.
byte b = flag ? 1 : 200;NoBoth branch expressions are int, and a nonconstant condition prevents constant narrowing at assignment

Tip

When a numeric conditional selects a wrapper and needs its primitive value, the wrapper unboxes. Integer a = null; int r = true ? a : 0; throws NullPointerException. In true ? Integer.valueOf(1) : Double.valueOf(2.0), Java unboxes the selected Integer to int and widens it to double, giving 1.0.

Test Your Knowledge

What is the output of the following code?

boolean flag = false;
int count = 0;
if (flag = true)
    if (count > 0)
        System.out.print("A");
else
    System.out.print("B");
System.out.print("C");
A

AC

B

BC

C

C

D

Does not compile

Test Your Knowledge

What is printed when this code runs?

int a = 5, b = 10;
int result = (a > 3) ? (b < 5 ? a++ : ++b) : --a;
System.out.println(a + ":" + b + ":" + result);
A

6:10:5

B

4:10:4

C

5:11:11

D

6:11:11

Test Your Knowledge

Which statement fails to compile?

A

int x = 10; if (x = 10) { x++; }

B

boolean ok = false; if (ok = true) { ok = false; }

C

System.out.println(true ? 42 : "forty-two");

D

byte b = false ? 10 : 100;

Sections you finish are checked off in the contents.