Java:Language - Ternary operator

From Juneday education
Jump to: navigation, search


Introduces the ternary operator. It works like a conditional expression - starting with a boolean expression, then the expression if true, followed by the expression if false.

boolean isAmbitiousStudent = true;
System.out.println( (isAmbitiousStudent ? "See these lectures!" : "Do something else") );

The operator has two symbols, ‘?’ and ‘:’ (question mark and colon). It is used as a short form for making decisions. The operands are three. First there is a boolean expression followed by the question mark. Next, there is an expression which is to be the value produced if the boolean expression was true, next there is the colon followed by and expression which is the value to be produced if the boolean expression was false. This requires an example, probably:

 Boot myBoots = isRaining ? Boots.WELLINGTONS : Boots.REGULAR_BOOTS;

Video about ternary: Java Ternary operator (pdf)

In the example, we pretend we have a type Boot (which is described somewhere, perhaps in a class defined in a file and a reference variable myBoot. We want to decide what type of boot it should be and let the variable isRaining decide for us. If it is raining, Wellington boots are suitable. Otherwise, we go for regular boots.

It is important to understand that the ternary operator produces an expression of the type as its two last operands. It may superficially look like an IF statement, but IF statements are not expressions. The whole expression using the ternary operator is an expression and can therefore be used as a value, e.g. in an assignment as in the example of the Boot above.

The first part is always a boolean expression, used to select one of the two following value expressions.

Ternary expressions can be chained together but that rarely produces readable code.

String name = "Mr. Anderson";
String sex = name.startsWith("Mr") ? "male" : name.startsWith("Mrs") || name.startsWith("Miss") ? "female" : "Unknown";


Lecture slides and videos

Further reading