Java ternary operator

Java's conditional operator evaluates a boolean expression and then evaluates only the selected operand. Write it as condition ? valueIfTrue : valueIfFalse.

A simple example

Choose one value

  1. Start with n is 2
  2. Do this Choose by sign
  3. Result positive
The condition selects which word becomes the result.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int n = 2;
        System.out.println(n > 0 ? "positive" : "other");
    }
}
Output
positive
Empty group: No samples. Measured group: 18 ÷ 3. Display: 6.
Handle an empty reading

A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.

Java source code
class ConditionalStatement {
    public static void main(String[] args) {
        int a = 3;
        int b = 6;

        String result = (a == b) ? "The numbers are equal" : "The numbers are not equal";
          
        System.out.println(result);
    }
}
Output
The numbers are not equal
Advertisements

Example: #2 - inline if (iif), or ternary if with compiler error

Choose 6.3 when a equals 5 and 9 otherwise. Numeric promotion determines the result type.

Java source code
class ConditionalStatement {
    public static void main(String[] args) {
        int a = 5;

        double x = 6.3;
        int y = 9;

        /**
         * Compiler Error: Type mismatch: cannot convert from double to int
         * 
         * The conditional expression has type double. Assign it to a double
         * or explicitly convert it to int if truncation is intended.
         */
        int result = a == 5 ? x : y;
    }
}
Compiler error
Compile-time error: possible lossy conversion from double to int.

Example: #3 - inline if (iif), or ternary if Statement with no left hand operand

Choose a message based on whether the two values are equal.

Java source code
class ConditionalStatement {
    public static void main(String[] args) {
        int a = 3;
        int b = 6;

        /**
         * Compiler Error: Compile-time error: a conditional expression cannot stand alone as a statement.
         * 
         * terniary if requires an operand in the left hand side to receive the value
         * otherwise it will throw an compiler error
         */
        (a == b) ? "The numbers are equal" : "The numbers are not equal";
    }
}
Compiler error
Compile-time error: a conditional expression cannot stand alone as a statement.

Java Nested ternary Operator ? :

A conditional expression can appear inside another conditional expression. Parentheses can clarify which alternatives belong together.

Example: #4 - Nested ternary Operator Statement

Use nested conditional expressions to classify a student's score.

Java source code
class ConditionalStatement {
    public static void main(String[] args) {
        int mark = 60;

        String message = mark <= 50
            ? mark < 30 ? "Below average" : "Average"
            : mark < 75
                ? mark < 60 ? "Performer" : "Good Performer"
                : "Out Standing";
          
        System.out.println(message);
    }
}
Output
Good Performer
Advertisements

Related tags

  • java
  • ? :
  • inline if
  • iif
  • ternary if
  • terniary operator
  • conditional operator
  • nested terniary operator