Java OCA OCP Practice Question 2867

Question

Given this code in a method:

4.     int x = 0;  
5.     int[] primes = {1,2,3,5};  
6.     for(int i: primes)  
7.       switch(i) {  
8.         case 1: x += i;  
9.         case 5: x += i;  
10.         default: x += i;  
11.         case 2: x += i;  
12.       }  /*from  w  ww  .j av a  2s  . c  o m*/
13.     System.out.println(x); 

What is the result?

  • A. 11
  • B. 13
  • C. 24
  • D. 27
  • E. Compilation fails due to an error on line 7.
  • F. Compilation fails due to an error on line 10.
  • G. Compilation fails due to an error on line 11.


D is correct.

Note

The code is all legal.

A switch's cases don't have to be in any particular order.

Also remember that when a case is matched, its code, and all the subsequent cases' code, will run unless a break is encountered.




PreviousNext

Related