Java OCA OCP Practice Question 467

Question

What is the output of the following application?


public class MyClass { 
        public final static void main(String... args) { 
           int flavors = 30; 
           int myField = 0; 
           switch(flavors) { 
              case 30: myField++; 
              case 40: myField+=2; 
              default: myField--; 
           } //from   w  ww .  ja  v a 2 s. c o m
           System.out.print(myField); 
        } 
} 
  • A. 1
  • B. 2
  • C. 3
  • D. The code does not compile.


B.

Note

The code compiles without issue, so Option D is incorrect.

In this question's switch statement, there are no break statements.

Once the matching case statement, 30, is reached, all remaining case statements will be executed.

The variable myField is increased by 1, then 2, then reduced by 1, resulting in a final value of 2, making Option B the correct answer.




PreviousNext

Related