OCA Java SE 8 Mock Exam - OCA Mock Question 4








Question

What is the output of the following program?

     1:public class Main { 
     2:   public static void main(String[] args) { 
     3:     int i = 10; 
     4:     if((i>10 ? i++: --i)<10) { 
     5:       System.out.print("Foo"); 
     6:     } if(i<10) System.out.print("Bar"); 
     7:   } 
     8:} 
  1. Foo
  2. Bar
  3. FooBar
  4. The code will not compile because of line 4.
  5. The code will not compile because of line 6.
  6. The code compiles without issue but does not produce any output.




Answer



C.

Note

The code compiles and runs without issue, so options D and E are not correct.

Only one of the right-hand ternary expressions will be evaluated at runtime.

Since i is not less than 10, the second expression, --i, will be evaluated, and since the pre-increment operator was used, the value returned will be 9, which is less than 10.

The first if-then statement will be visited and Foo will be output.

Since i is still less than 10, the second if-then statement will also be reached and Bar will be output.

public class Main { 
   public static void main(String[] args) { 
     int i = 10; 
     if((i>10 ? i++: --i)<10) { 
       System.out.print("Foo"); 
     } /*from   ww  w .j a va 2 s. c om*/
     if(i<10) {
       System.out.print("Bar"); 
     }
   } 
} 

The code above generates the following result.