if, else and the ternary

A condition in Java is a boolean expression, and the statement that uses it is if, with optional else if and else branches. The same choice can be a value with the conditional operator, and the choice between two strings needs a method rather than an operator.

if, else if and else

The branches are tested in order and the first true one runs. A later else if is therefore not a second test of the same thing: it is reached only when every test before it was false. The final else is optional, and when it is missing a false condition simply does nothing.

The file Conditions.java grades a score and then reads the hour with a nested if:

public class Conditions { public static void main(String[] args) { int score = 78; if (score >= 90) { System.out.println("grade: A"); } else if (score >= 80) { System.out.println("grade: B"); } else if (score >= 70) { System.out.println("grade: C"); } else { System.out.println("grade: F"); } boolean passed = score >= 60; String label = passed ? "passed" : "failed"; System.out.println("score " + score + ": " + label); int hour = 13; if (hour < 12) { System.out.println("morning"); } else { if (hour < 18) { System.out.println("afternoon"); } else { System.out.println("evening"); } } int year = 2024; boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; System.out.println(year + " is a leap year: " + leap); } }

javac -Xlint:all Conditions.java
java Conditions

grade: C
score 78: passed
afternoon
2024 is a leap year: true

The score is 78, so the first two tests are false and the third is true: the program never looks at the final else. The leap year line shows the shape of a condition with &&, || and parentheses, in which the parentheses decide what belongs to what.

Blocks and the dangling else

An if takes one statement, and a block { ... } counts as one statement. Without braces the body is the single statement that follows, and an else binds to the nearest unmatched if, which is not always the one the indentation suggests.

public class DanglingElse { public static void main(String[] args) { int score = 95; boolean extra = false; if (score >= 90) if (extra) System.out.println("A with bonus"); else System.out.println("not A"); if (score >= 90) { if (extra) { System.out.println("A with bonus"); } } else { System.out.println("not A"); } System.out.println("after the braced if"); } }

javac -Xlint:all DanglingElse.java
java DanglingElse

not A
after the braced if

The score is 95, and the unbraced version still prints not A: the else belongs to if (extra), so it runs when extra is false even though the score passed. The braced version has no such ambiguity, and its else belongs to the outer if. The braces are not decoration; they are the statement structure.

The conditional operator

condition ? a : b is an expression: it evaluates the condition and gives a when it is true and b when it is false. It is the shortest way to choose a value, and it nests badly, so it is best kept to one line and one decision.

public class Ternary { public static void main(String[] args) { int score = 78; String label = score >= 60 ? "passed" : "failed"; System.out.println(label); int a = 5; int b = 9; int max = a > b ? a : b; System.out.println("max: " + max); } }

javac -Xlint:all Ternary.java
java Ternary

passed
max: 9

The two branches of a conditional expression must have a type in common, which is why the first line gives a String; a mix of int and String in the two branches would be joined by the compiler into an Object, and a later use would need a cast.

Comparing strings

A string is an object, and == between two objects compares the references, not the text. equals compares the contents, and equalsIgnoreCase does the same without case. Two literals with the same text are the same object because the compiler pools them, which is why == sometimes looks right and is not.

public class StringCompare { public static void main(String[] args) { String a = "java"; String b = "java"; String c = new String("java"); String d = "ja" + "va"; String e = "ja" + a.substring(2); System.out.println("a == b: " + (a == b)); System.out.println("a == c: " + (a == c)); System.out.println("a.equals(c): " + a.equals(c)); System.out.println("a == d: " + (a == d)); System.out.println("a == e: " + (a == e)); System.out.println("a.equals(e): " + a.equals(e)); System.out.println("equal ignore case: " + a.equalsIgnoreCase("JAVA")); } }

javac -Xlint:all StringCompare.java
java StringCompare

a == b: true
a == c: false
a.equals(c): true
a == d: true
a == e: false
a.equals(e): true
equal ignore case: true

The == bug read from a run

The run above is the bug in full. a == b is true because both names point at the pooled literal, and a == d is true because the compiler folds two literals into one constant. a == c is false because new String creates another object, and a == e is false because a concatenation with a non-constant result is a new object. In all four cases equals gives the answer the program wanted.

The rule to remember is one line: compare text with equals, and compare null with ==. A call such as "java".equals(input) puts the constant first, so it also works when the argument is null.

Exercises

  1. Change the score in Conditions.java to 65 and predict every line before you run it.
  2. Remove the braces from the second if in DanglingElse.java and explain the output.
  3. Rewrite the grade if chain as nested conditional expressions. Which version do you prefer, and why?
  4. Add a case to StringCompare.java with a string read from an argument, and compare it with == and with equals.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which method compares the contents of two strings?

    Answer

    equals

    equals compares the characters; == compares the references of the two objects.

  2. What does == compare between two string variables?

    Answer

    The references, not the text

    For references, == asks whether both point at the same object.

  3. When does the else branch of an if statement run?

    Answer

    When every condition before it was false

    The first true branch runs and the rest are skipped; the else is reached only when none was true.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int score = 85; if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else { System.out.println("C"); } } }

    Answer

    B

    85 is not at least 90, but it is at least 80, so the second branch runs.

  5. What does this program print? public class Q2 { public static void main(String[] args) { int a = 5; int b = 9; System.out.println(a > b ? a : b); } }

    Answer

    9

    The condition is false, so the operator gives the second value, b.

  6. What does this program print? public class Q3 { public static void main(String[] args) { String a = new String("java"); String b = "java"; System.out.println(a == b); } }

    Answer

    false

    new String creates a separate object, so the two references differ even though the text is equal.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println("java".equalsIgnoreCase("JAVA")); } }

    Answer

    true

    equalsIgnoreCase ignores the case of both strings and finds them equal.

  8. What does this program print? public class Q5 { public static void main(String[] args) { boolean ready = false; if (!ready) { System.out.println("go"); } else { System.out.println("stop"); } } }

    Answer

    go

    The negation of false is true, so the if branch runs.

  9. What does this program print? public class Q6 { public static void main(String[] args) { int score = 95; boolean extra = false; if (score >= 90) if (extra) System.out.println("bonus"); else System.out.println("plain"); } }

    Answer

    plain

    The else belongs to the inner if, whose condition is false, so plain is printed.

  10. Which comparison is safe when the variable may be null?

    Answer

    "java".equals(input)

    Calling equals on the constant cannot throw; a call on a null input throws NullPointerException.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev