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








Question

What is the output of the following code snippet?

     3: java.util.List<Integer> list = new java.util.ArrayList<Integer>(); 
     4: list.add(1); 
     5: list.add(2); 
     6: for(int x : list) { 
     7:   System.out.print(x + ", "); 
     8:   break; 
     9: } 
     
  1. 1, 2,
  2. 1, 2
  3. 1,
  4. The code will not compile because of line 7.
  5. The code will not compile because of line 8.
  6. The code contains an infinite loop and does not terminate.




Answer



C.

Note

The break statement on line 8 causes the loop to execute once and finish, C is correct.

public class Main{
   public static void main(String[] argv){
        java.util.List<Integer> list = new java.util.ArrayList<Integer>(); 
        list.add(1); //w  ww. j  a v  a 2s .c  o  m
        list.add(2); 
        for(int x : list) { 
           System.out.print(x + ", "); 
           break; 
        } 
   }
}