Ternary operator is a shorthand version of if-else statement. It has three operands and hence the name ternary. General format is:
condition ? if-true : if-false
The above statement means that if the condition evaluates to true, then execute the statements after the ?
else execute the statements after the :
.
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class Operators {
public static void main(String[] args){
int a = 20, b = 10, c = 30, result;
// result holds max of three
// numbers
result = ((a > b)
? (a > c)
? a
: c
: (b > c)
? b
: c);
System.out.println("Max of three numbers = "
+ result);
}
}
Max of three numbers = 30