Introduction
Interested in saying a lot while writing a little? In a single line of code, Java's ternary operator let's you assign a value to a variable based on one or more boolean decisions. Think of this operator as a potential alternative to the if-then-else syntax.
Although it may be a little confusing when you first see it, the ternary operator lets you make powerful decisions with a minimal amount of coding.
A sample min/max comparison
A common use of the ternary operator (also called the conditional operator) is to assign the minimum (or maximum) value of two variables to a third variable, essentially replacing a Math.min(a,b) or Math.max(a,b) method call.
The ternary code that assigns the minimum of two variables, a and b, to a third variable named minVal is:
- // code to assign the minimum value
minVal = (a <>
In this code, if the variable a is less than b, minVal is assigned the value of a; otherwise, minVal is assigned the value of b. Note that the parentheses in this example are optional, but I use them to improve the readability of the code.
Also notice that the ternary operator is an expression that returns a value based on the conditional phrase it evaluates. This is different than the if-then-else syntax, which executes a statement block based on it's conditional phrase.
Syntax
operand1 ? operand2 : operand3
- also referred to as the conditional operator
- if operand1 is true, operand2 is returned, else operand3 is returned
true ? op2 : op3 // op2 returned
false ? op2 : op3 // op3 returned
- operand1 must be a boolean type
- operand1 can be an expression that evaluates to a boolean type
(5 == 5) ? "yes" : "no" // output: yes
- operand1 and operand2 must be promotable numeric types or castable object references, or null
- if one of operand2 or operand3 is a byte and the other a short, the type of the returned value will be a short
byte = true ? byte : short // found short, required byte
- if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands range, the type of the returned value will be the type of the other operand
short = true ? short : 1000 // compiles and runs ok
short = false ? short : 1000 // compiles and runs ok
- otherwise, normal binary numeric promotion applies
- if one of operand2 or operand3 is a null, the type of the return will be the type of the other operand
- if both operand2 and operand3 are different types, one of them must be compatible (castable) to the other type
Class_A a = new Class_A();
Class_B b = new Class_B(); // subclass of Class_A
Class_C c = new Class_C();
Class_A a1 = b;
Class_C c1;
c1 = false ? a : c; // compile-error: incompatible types
a1 = true ? b : a; // returns class type of Class_B