Conditional Operator ( ? : ) operator in Java
The trend of brevity was started by C programming language and Java inherits most of its virtues from C. The conditional ? : operator can create a very small code of what an if else statement would take.
To understand the conditional operator using ? : consider the following code written with if else. The code computes the minima of two numbers x and y.
|
These six lines of codes can be replaced with a single line of code.
min = (x < y ) ? x : y;
(x < y ) ? x : y; is an expression which returns one of two values, x or y. The condition, (x < y), is tested. If it is true the first value, x, is returned. If it is false, the second value, y, is returned. Whichever value is returned is dependent on the conditional test, x
The conditional ? : operator is called ternary operator and its general syntax olooks like
result = testCondition ? value1 : value2
If testCondition is true, result is assigned value1; otherwise, result is assigned value2.
Here is the complete Java example that prints the min of three numbers using ternary conditional statement.
|
If you compile and run, you get the following output
Minimum of three numbers is 18 |