Java ternary operator can replace certain types of if-then-else statements.
The ? has this general form:
expression1 ? expression2 : expression3
expression1
must evaluate to a boolean value.
If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the ? operation is that of the expression evaluated.
Both expression2 and expression3 are required to return the same or compatible type and can't be void.
Here is an example of the way that the ? is employed:
double ratio = denom == 0 ? 0 : num / denom;
If denom equals zero, ratio is assigned to 0.
If denom is not zero, do the calculation.
Here is a program that demonstrates the ? operator. It uses it to obtain the absolute value of a variable.
// Demonstrate ?. public class Main { public static void main(String args[]) { int i, k;//from w w w.j a v a 2 s . c o m i = 1; k = i < 0 ? -i : i; // get absolute value of i System.out.print("Absolute value of "); System.out.println(i + " is " + k); i = -1; k = i < 0 ? -i : i; // get absolute value of i System.out.print("Absolute value of "); System.out.println(i + " is " + k); } }