The ? Operator

The ? operator is a ternary (three-way) operator. The ? has this general form:


expression1 ? expression2 : expression3

The expression evaluated is the result of the ? operation.

Both expression2 and expression3 are required to return the same type, which can't be void. Here is an example of ? operator:

 
public class Main {
  public static void main(String[] argv) {
    int denom = 10;
    int num = 4;
    double ratio;

    ratio = denom == 0 ? 0 : num / denom;
    System.out.println("ratio = " + ratio);
  }
}

The output:


ratio = 0.0

Here is another program that demonstrates the ? operator. It uses it to obtain the absolute value of a variable.


public class Main {
  public static void main(String args[]) {
    int i, k;
    i = 10;
    k = i < 0 ? -i : i; 
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);

    i = -10;
    k = i < 0 ? -i : i; 
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);

  }
}

The output generated by the program is shown here:


Absolute value of 10 is 10 
Absolute value of -10 is 10
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.