Core Java Fundamentals ยท Operators

Ternary Operator

Learn how to use the ternary operator, a compact, inline conditional for simple if-else logic.

TernaryExample.java

public class TernaryExample {
    public static void main(String[] args) {
        int number = 10;
        String result;

        // Using the ternary operator to check if the number is even or odd
        result = (number % 2 == 0) ? "Even" : "Odd";

        System.out.println("The number is " + result);
    }
}

Step by step

  1. The main method begins. We declare an integer variable number and initialize it with the value 10.
  2. Next, we declare a String variable named result. It is initialized to null by default as it has no assigned value yet.
  3. This line uses the ternary operator. First, the condition (number % 2 == 0) is evaluated.
  4. Since number is 10, 10 % 2 is 0. The condition 0 == 0 evaluates to true.
  5. Because the condition is true, the first value after the ? is chosen. The expression evaluates to "Even".
  6. The evaluated value, "Even", is now assigned to the result variable. The string "Even" is added to the String Pool.
  7. Finally, the println method is called. It concatenates the string "The number is " with the value of result and prints the output to the console.