Java Ternary Operator

Ternary Operator (?:)

 

This operator is called ternary since it acts on 3 expressions.

 

The syntax for using it is:

variable = expression1 ? expression2 : expression 3

 

Here,

expression1 can be any expression that evaluates to a boolean value.

If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.

Both expression2 and expression3 are required to return the same or compatible type that can not be void.

 

In If…else format, the above ternary expression evaluates to :

 

If(expression1){

variable = expression2

}

else{

variable = expression3

}

 

Here is an example that determines the absolute values of a number using the ternary operator ?:

// Program for getting absolute value of a number

package firstpackage;

public class TernaryOperator {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int i ;
    i =10;
    System.out.println("Absolute value of " + i + " is = " + getAbsoluteValue(i));
    
    i=-10;
    System.out.println("Absolute value of " + i + " is = " + getAbsoluteValue(i));
  }
  
  private static int getAbsoluteValue(int number){
    return number < 0 ? -number : number;
  }

}


 

Here, when i=10, number < 0 check will be false and number (10) will be returned.

 

Again, when i=-10, number < 0 will be true and -number (10) will be returned.

 

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags