Conditional Operator (Ternary Operator)
Conditional operator is also known as the ternary operator. Java includes a ternary (three-way) operator that can replace certain types of if-then-else statements. It has the following syntax:
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. For example,
As shown in above example the condition a != 1 is true then b will have a value 20. The program for the use of conditional operator is given below.
PROGRAM
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. For example,
int a=10;
int b = (a != 1) ? 20: 30;
As shown in above example the condition a != 1 is true then b will have a value 20. The program for the use of conditional operator is given below.
PROGRAM
class ConditionalOpDemo {
public static void main(String[] args) {
int x = 25, y = 22;
System.out.println("x = "+x);
System.out.println("y = "+y);
x = (y>25) ? y : 50;
System.out.println("x = (y>25) ? y : 50");
System.out.println("Now, x = "+x);
}
}
OUTPUT
C:\javac ConditionalOpDemo.java C:\java ConditionalOpDemo x = 25 y = 22 x = (y>25) ? y : 50 Now, x = 50