Core Java Fundamentals ยท Operators
Learn how to use the ternary operator, a compact, inline conditional for simple if-else logic.
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);
}
}number and initialize it with the value 10.result. It is initialized to null by default as it has no assigned value yet.(number % 2 == 0) is evaluated.number is 10, 10 % 2 is 0. The condition 0 == 0 evaluates to true.true, the first value after the ? is chosen. The expression evaluates to "Even"."Even", is now assigned to the result variable. The string "Even" is added to the String Pool.println method is called. It concatenates the string "The number is " with the value of result and prints the output to the console.