The ? Operator

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


expression1 ? expression2 : expression3
  • expression1 can be any expression that evaluates to a boolean value.
  • If expression1 is true, then expression2 is evaluated.
  • Otherwise, expression3 is evaluated.

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
Home 
  Java Book 
    Language Basics  

Operators:
  1. Operators
  2. Arithmetic Operators
  3. Bitwise Operators
  4. Relational Operators
  5. Boolean Logical Operators
  6. The ? Operator
  7. Operator Precedence