Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

? :

Picks one of two values by a condition — a short form of if-else.

Available since: Java 1.0

Syntax

condition ? valueIfTrue : valueIfFalse

Examples

Choosing a value:

void main() {
    int age = 20;
    String status = age >= 18 ? "adult" : "minor";
    IO.println(status);
 
    int count = 1;
    IO.println(count + (count == 1 ? " item" : " items"));
}

Output:

adult
1 item

Notes

The ternary operator is an expression and has a value; if is a statement. Nested ternaries are hard to read — for three or more cases a switch expression is better. When combined with string concatenation, wrap the ternary in parentheses.

See also

  • if / else — Runs a block of code only if a condition is true.
  • switch — Picks a branch by value; as an expression it returns a result.

In the tutorial

  • Conditions — Branching in Java: if, else, else if, compound conditions and the ternary operator.

Thanks for reading!

Donate to the site — we work hard for you.