![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
The ternary operator is used for replacement of if-else statement
The ternary operator is combination of ?
and :
and takes three operands.This ? operator is also known as the conditional
operator.
expression1 ? expression2 : expression3;
class IfElseGreater { public static void main(String args[]) { int first = 159; int second = 415; if ( first > second) { System.out.println("Greater is "+first); } else { System.out.println("Greater is "+second); } } }
Now let's see above example using Ternary Operator.
class TernaryOpeGreater { public static void main(String args[]) { int first = 159; int second = 415; int greater; greater = ( first > second ? first : second); System.out.println("Greater is "+greater); } }
In above example 415 > 159 becomes true hence 415 variable is stored into the greater variable.
Ternary Operator helps you to use shortened way of writing if-else statement.
We can also write nested ternary operator statements inside another ternary statement.
Instead of storing result of the expression,there will be another ternary statement executed and it's result will be returned.
expr 1 ? (sub-expr1 ? expr1 : expr2) : (sub-expr2 ? expr1 : expr2);
Syntax Explanation
public class Test { public static void main(String[] args) { String result; int pin=1199,balance=0; result = ((pin==1199 ? (balance>0? "Cash available":"No balance") : "Wrong PIN")); System.out.println("Result : "+result); } }
Result : No balance