Java ternary, three-way, ? Operator convert from if statement

Question

We would like to convert if statement to ternary, three-way, ? operator.

The following statement assigns 1 to y if x is greater than 0, and -1 to y if x is less than or equal to 0.

if (x > 0) 
     y = 1; 
else 
     y = -1; 


y = (x > 0) ? 1 : -1;

Note

With no explicit if in the statement.

Conditional expression syntax is:

boolean-expression ? expression1 : expression2; 

The result of this conditional expression is expression1 if boolean-expression is true; otherwise the result is expression2.


public class Main {
  public static void main(String args[]) {
    int x = 3;/*w w  w .j av a 2s .c  o  m*/
    int y = -1;
    if (x > 0)
      y = 1;
    else
      y = -1;

    System.out.println(x);
    System.out.println(y);

    y = (x > 0) ? 1 : -1;
    System.out.println(x);
    System.out.println(y);
  }
}



PreviousNext

Related