As other programming languages, Java also provides ternary operator. The ternary operator is the simple one liner statement of an if-then-else statement. A ternary operator uses ? and : simbles. A simple ternary operator works similar to the if-then-else statement. If any condition evaluates to true then true statement executed else false statement executed. Below is the basic syntax of ternary operator in java:
condition ? trueStatement : falseStatement
Basically, there are 3 parts of statement seprated with ? and : symbols.
- Condition : First part is the condition section.
- trueStatement : Second is the code block which executes in case of first part condition goes true.
- falseStatement : The Third part code block executes if condition results as false.
For an example, if any account exists in application record then complete sign in process for user else open signup form for that user.
1 | ifAccountExists() ? signIn() : signUp(); |
#1. Ternary Operator vs If-Else
For example, if you have to compare two variables and provide the output based on the result. Using If-Else you need to write code like below:
1 2 3 4 5 6 | if( a > b ) { return "a is greater"; } else{ return "b is greater"; } |
The same code can be written in a single line using a ternary operator.
1 | a > b ? "a is greater" : "b is greater"; |
#2. Ternary Operator in Java Example
For example, below example code will return the result as “b is greater” because the value of b is 20 which is greater than the value of a.
1 2 3 4 5 6 7 8 9 10 11 | public class TernaryOperator { public static void main(String[] args) { int a = 10; int b = 20; String result = a > b ? "a is greater" : "b is greater"; System.out.println(result); } } |
#3. Nested Ternary Operator Example
You can also use Ternary operated as nested conditions. For the example, if we compare for greatest value among three integer variables. Then if-else statement will be something like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | if( a > b ) { if ( a > c ){ return "a is greatest"; } else{ return "c is greatest"; } else{ if ( b > c ){ return "b is greatest"; } else{ return "c is greatest"; } } |
The same can be check with single line code using nested ternary operator. Below is the working example of comparing tree variable values and print which variable have the highest integer value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /* TernaryOperator.java */ public class TernaryOperator { public static void main(String[] args) { int a = 10; int b = 20; int c = 30; String result = a > b ? a > c ? "a is greatest" : "c is greatest" : b > c ? "b is greatest" : "c is greatest"; System.out.println(result); } } |
Conclusion
In this tutorial, you learned about how to use ternary operator in Java and convert the if-else code in single line statement.
1 Comment
hi…
thx for the great article…
its very basic.. its help me a lot..
but i want to ask you about Polymorphism..
did you have an article about it??
thx…