Tech and Media Labs
This site uses cookies to improve the user experience.


Java Ternary Operator

Jakob Jenkov
Last update: 2018-10-05

The Java ternary operator functions like a simplified Java if statement. The ternary operator consists of a condition that evaluates to either true or false, plus a value that is returned if the condition is true and another value that is returned if the condition is false. Here is a simple Java ternary operator example:

String name = case.equals("uppercase") ? "JOHN" : "john";

We will dissect this ternary operator example in the rest of this Java ternary operator tutorial.

Ternary Operator Condition

The ternary operator part of the above statement is this part:

case.equals("uppercase") ? "JOHN" : "john"

The condition part of the above ternary operator expression is this part:

case.equals("uppercase")

The condition is a Java expression that evaluates to either true or false. The above condition will evaluate to true if the case variable equals the Java String value uppercase, and to false if not.

The condition can be any Java expression that evaluates to a boolean value, just like the expressions you can use inside an if - statement or while loop.

Ternary Operator Values

The condition part of a ternary operator is followed by a question mark (?). After the question mark are the two values the ternary operator can return, separated by a colon (:). The values part of the ternary operator shown earlier is:

"JOHN" : "john";

The values part consists of two values. The first value is returned if the condition parts (see above) evaluates to true. The second value is returned if the condition part evaluates to false.

In the example above, if case.equals("uppercase") evaluates to true then the ternary operator expression as a whole returns the String value JOHN. If case.equals("uppercase") evaluates to false then the ternary operator expression as a whole returns the String value john. That means, that the String variable name will end up having the value JOHN or john depending on whether the expression case.equals("uppercase") evaluates to true or false.

The values returned can be the result of any Java expression that returns a value that can be assigned to the variable at the beginning of the statement. Because the Java variable at the beginning of the ternary operator example at the top of this article is of type String, then the values returned by the values part must be of type String.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC