Java OCA OCP Practice Question 713

Question

Consider the code shown below :

public class Main{ 
  public static int switchTest (int k){ 
     int j = 1; //from  w w w  . j  a  va  2  s.c  o  m
     switch (k){ 
        case 1: j++; 
        case 2: j++; 
        case 3: j++; 
        case 4: j++; 
        case 5: j++; 
        default  : j++; 
      } 
     return j + k; 
   } 
  public static void main (String [] args){ 
     System.out.println ( switchTest (4) ); 
   } 
} 

What will it print when compiled and run?

Select 1 option

  • A. 5
  • B. 6
  • C. 7
  • D. 8
  • E. 9


Correct Option is  : D

Note

The control in the case falls through till reaches the break statement.

switch(4) will take the control to case 4:.

Since there is no break statement, all the statements till the end will be executed.

So j will be incremented 3 time making it 4. finally 4 + 4 i.e. 8 will be returned.




PreviousNext

Related