Multiple choice technology programming languages

public class Fun { public static void main(String[] args){ int x=0; boolean b=true; String str; str=(b)?"success": (x=0)?"Failure":"Neither"; System.out.println(str); } }

  1. Failure

  2. success

  3. Exception will be thrown

  4. Compilation error

  5. Neither

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

The ternary operator has left-associativity. The expression str=(b)?"success": (x=0)?"Failure":"Neither" is parsed as str = ((b)?"success": (x=0))?"Failure":"Neither". Since b is true, the first ternary returns "success". Then it tries to evaluate ("success")?"Failure":"Neither", which attempts to use a String as a boolean condition - this is a compilation error because you cannot use a String as a boolean expression in Java.