Java conditional operator (also known as ternary operator) is a conditional statement and can also be considered as a short version of if else. Ternary operator has three operands and return one of the 2nd or 3rd values depends on the first boolean expression.
Java Conditional Operator ? : (Ternary Operator)
Conditional Operator Syntax
booleanExpression? expression1: expression2
If the booleanExpression is true, then expression1 value is returned. If it is false, then expression2 value is returned.
Example 1: (a > b) ? a : b;
(a > b) ? a : b;
Hint: if (a > b) is true, then a will be returned. else, b will be returned.
int a = 5; int b = 4; int c = (a > b) ? a : b; //since a>b //c = 5
Example 2: To compare the conditional statement with the if-else statement, let's write the if-else equivalent of the first example.
int a = 5; int b = 4; int c; //int c = (a > b) ? a : b; if (a > b) c = a; else c = b; //since a>b //c = 5
Example 3: It is also possible to write nested conditional statements in Java. Let's write a nested if/else if/else statement with both if and The Ternary Operators.
IF Version:
int a=5; int b=5; String c; if(a > b) { c = "greater"; } else if(a == b) { c = "equals"; } else { c = "smaller"; } System.out.println(c); //equals
Conditional Statement Version:
Hint: nested Sytax is:
Condition1 ? X : (Condition2 ? Y : Z);
Solution:
int a=5; int b=5; String c; c = a > b ? "greater" : (a == b ? "equals" : "smaller"); System.out.println(c); //equals