Skip to main content

Command Palette

Search for a command to run...

Which one to Use Ternary Operator or If-Else Block

Published
2 min read
V
  • Open Source Contributor
  • Loves Developer Education
  • Passionate about Developer Experience;
  • Currently working as Lead Developer at Zoho.

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
2 views
J

I had no idea this was a thing. I can already think of areas I could apply this to and it's so much quicker than an if else!

1
V

Was randomly poking one of my friend about this question. And got to learn we miss it so quickly. Few years back I was nudged by my friend by same question. Hope you will remember this article in future while working.

1