Java Reference
In-Depth Information
2.2.2 Ternary operator for branching instructions:
Predicate ? A : B
In Java, there is also a special compact form of the if else conditional
used for variable assignments called a ternary operator. This ternary operator
Predicate ? A : B provided for branching assignments is illustrated in the
sample code below:
double x1=Math . PI ; // constants defined in the Math class
double x2=Math .E;
double min=(x1 > x2) ? x2 : x1 ; // min value
double diff= (x1 > x2) ? x1 x2 : x2 x1 ; // absolute value
System . out . println (min+ " difference with max=" +diff ) ;
Executing this code, we get:
2.718281828459045 difference with max=0.423310825130748
The compact instruction
double min=(x1>x2)? x2 : x1;
...is therefore equivalent to:
double min;
if (x1>x2) min=x2;
else min=x1;
Figure 2.1 depicts the schema for unary, binary and ternary operators.
Unary operator
Binary operator
Ternary operator
++
*
?:
a
a
b
Predicate a
b
(Predicate?
a :
b)
a++
a*b
post-incrementation
multiplication
compact branching
Figure 2.1 Visualizing unary, binary and ternary operators
 
Search WWH ::




Custom Search