Question:

What will be the output of the following Java code?

public class Check {
 public static void main(String[] args) {
    int a = 5;
    System.out.println(a > 2 ? a < 5 ? 10 : 20 : 30);
  }
}

Show Hint

Nested ternary groups from the right. a > 2 is true, then a < 5 is false because 5 is not less than 5.
Updated On: Jul 2, 2026
  • 5
  • 10
  • 20
  • 30
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is C

Solution and Explanation

Step 1: The ternary operator is right associative, so it reads as \( a > 2 \; ? \; (a < 5 \; ? \; 10 : 20) : 30 \).

Step 2: Check the outer condition. Is \( a > 2 \)? Here \( 5 > 2 \) is true, so we move to the inner ternary.

Step 3: Check the inner condition. Is \( a < 5 \)? Here \( 5 < 5 \) is false, so it returns 20.

Step 4: println prints 20. Answer is (C).
Was this answer helpful?
0
0