OCA Java SE 8 Operators/Statements - OCA Mock Question Operator and Statement 11








Question

What is the output of the following code?

     1: public class Main { 
     2:   public static void main(String[] args) { 
     3:     int x = 5; 
     4:     System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7); 
     5: }
     6:} 
     
  1. 5
  2. 4
  3. 10
  4. 8
  5. 7
  6. The code will not compile because of line 4.




Answer



D.

Note

((x > 2) ? ((x < 4) ? 10 : 8) : 7)

can be rewritten as follows

x > 2 ? 
     (x < 4 ? 10 
                : 
             8 
     ): 
     7
     public class Main { 
        public static void main(String[] args) { 
            int x = 5; 
            System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7); 
        }
     } 

The code above generates the following result.