---===[ Message from the authors: This wiki will be configured to use SSL - may be down 22.00-06.00 (Swedish time) during the period 2019-02-21 - 2019-02-23. Use wiki2.juneday.se during hose hours ===----

Java:Language - Ternary operator

From Juneday education
Jump to: navigation, search

Introduction

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 Boot.java) 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";

Links

Lecture slides and videos

Further reading