In Java (or in C programming also), in case if we have to take decision making with two conditions we can take using Ternary operator or If-Else also. Many times people get confused when to use the both. In this article I would like to capture few points on this.
Example 1:
int a = 100;
int b = 200;
int c;
Problem: We have to assign value of c with max between a and b.
Case 1: Using Ternary Operator
c = a >b ? a : b;
Case 2: Using If-else block
if( a>b){
c = a;
} else{
c = b
}
- Ternary Operator will be returning the value. In the Case 1 of the example above, it will return either a or b. So when we want to have returning a value or initializing value to variable based on this or that; then we can use Ternary operator.
- Check the Case 2, the amount of lines this block is very high. We will use If-Else when we have to execute several lines of code.
- Nested Ternary operator are difficult to read; it decreases the code quality while Nested If.. else-if... else are easily readable.
- If there is only one block based exection, then If case alone can be used. But the same is difficult in ternary operator