Tuesday, October 20, 2015

Ternary operator alternate to IF in JAVA

Java has an operator that can be used as an alternative to if statement. You are familiar with this operator, the conditional operator ?: This operator can be used to replace if-else statements of the general forms:

if (expression)
Statement 1;
else
Statement 2;

The above forms of if can be alternatively written using conditional operator as follows:

expression? statement 1 : statement 2;

It works in the same way as the above given form of if does i.e., expression is evaluated, if it is true, statement 1 gets executed (i.e. its value becomes the value of entire expression) otherwise statement 2 gets executed (i.e. its value now becomes the value of the entire expression). Look out following example:

int c;
if (a > b)
c = a;
else
c = b;

Can be alternatively written as:

int c = a > b ? a : b;

The whole code fragment converts into a single line.

Comparing if and ?:

  • Compared to if-else sequence, ?: offers more concise, clean and compact code, but it is less obvious as compared to if.
  • Another difference is that the conditional operator ?: produces an expression, and hence a single value can be assigned or incorporated into a larger expression whereas, if is more flexible. The if statement can have multiple statements, multiple assignments and expressions (in form of a compound statement) in its body.
  • When ?: operator is used in its nested form, it becomes complex and difficult to understand. This form of ?: is generally used to conceal the purpose of code.
In the next article we will learn about how to use switch statement in JAVA with an example.

No comments:

Post a Comment