Responsive Ads Here

Tuesday, April 14, 2020

Ternary operator | Ternary if - else operator

Ternary if-else operator

The ternary operator, also called the conditional operator, is unusual because it has three operands. It is truly an operator because it produces a value, unlike the ordinary if-else statement.

The expression is of the form : 

boolean-expression ? value0 : value1






If boolean-expression evaluates to true, value0 is evaluated, and its result becomes the value produces by the operator. If boolean-expression is false, value1 is evaluated and its result becomes the value produced by the operator.

Of course, you could use an ordinary if-else statement, but the ternary operator is much terser. Although C prides itself on being a terse language, and the ternary operator might have been introduced partly for efficiency,  you should be somewhat wary of using it on an everyday basis.

The conditional operator is different from if-else because it produces a value.

Here's an example comparing the two:

package com.javawins;

public class TernaryIfElse {

 public static void main(String[] args) {
  System.out.println(ternary(4));
  System.out.println(ternary(5));

  System.out.println(standardIfElse(4));
  System.out.println(standardIfElse(5));

 }

 static int ternary(int i) {
  return i < 5 ? i * 100 : i * 10;
 }

 static int standardIfElse(int i) {
  if (i < 5) {
   return i * 100;
  } else {
   return i * 10;
  }
 }
}

Output

400
50
400
50


You can see that code in ternary() is more compact than in standardIfElse(). However standardIfElse() is easier to understand, and does not require a lot more typing. So be sure to ponder your reasons when choosing the ternary.


Bitwise operators




No comments:

Post a Comment