Ternary Operator is also known as the Conditional operator. It is used to evaluate Boolean expressions. We can say that it is a short version of the if-else statement. But here instead of operating on two operands, it operates on three operands, and therefore the name ternary.
Syntax: of Ternary Operator:
variable num1 = (expression) ? value if true : value if false
Java Program for Ternary Operator :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Ternary { public static void main(String args[]) { int number1, number2; number1 = 30; number2 = (number1 == 15) ? 200: 400; System.out.println( "For false, value of number2 is: "+number2); /* number1 is not equal to 15 the second value after colon that is false value is assigned to the variable number2 */ number2 = (number1 == 30) ? 200: 400; System.out.println( "For true, value of number2 is: "+number2); /* number1 is equal to 30 so the first value that is the true value is assigned to the variable number2 */ } } |
Output:
For false, value of number2 is: 400
For true, value of number2 is: 200