Latest Posts

Sunday, January 8, 2017

JAVA :: Ternary Operator


Interested in expressing a lot using minimal words. Well, Ternary Operator comes as saviour. Its a conditional operator which works with three operands. 

To put in simple words, its a one line replacement for if-then-else statement. It helps to ensure that the code is concise without impacting its readability.

Syntax

condition ? <expression-if-True> : <expression-if-False>

The above syntax is a booelan expression which evalautes the above condition as either True or False. If evaluated True, then "expression-if-True" is evaluated else "expression-if-False" is evaluated.




Lets take an example to 

if (condition) {
   doThis();
}else {
   doThat();
}
// can be also expressed as 
condition ? doThis() : doThat(); 


Ternary Operartor as Expression

Since the Ternary operator is an expression, it can therefore be used at the right hand side of an assignment statement.

Lets have a look at the following example. Here a variable can be assigned a value based on the boolean condition.

int speedLimit = isHighway() ? 80 : 40;


Lets take another example, here we can see it helps reduce multiple return statements.

int speedLimit() {

    if (isHighway()) {
      return 80;
    }
   else {
      return 40;
    }
   }

// can be also expressed as 

int speedLimit() {   return isHighway() ? 80 : 40;}

1 comment:

  1. Nice answers in replace of the question with real point of view and explaining about that.
    user experience agency

    ReplyDelete