Java puzzle 10: Switch statement

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

Java puzzle 10: A switch statement

Level: Normal

What is the output of this program and why?

public class MySwitch
{
  public static void main(String[] args)
  {
    int x = 2;
    switch(x)
    {
      case 1:
        x += 2;
        break;
      case 2:
        x++;
      case 3:
        x += 4;
      default:
        x += 2;
    }
    System.out.print(x);
  }
}
Author: Sar Maroof

Answer explanation

Answer explanation

  1. The initial value of x is 2. So, case 1 doesn’t match the value of x.
  2. The statement x++; under case 2 is executed and the value of x is incremented by 1, x = 2 + 1 = 3.
  3. There is no break in case 2. Therefore, the statement under case 3 x += 4; is executed and the value of x becomes  x = 3 + 4 = 7.
  4. There is no break statement in case 3. Therefore, the statement x += 2 under default is executed. The value of  x is incremented by 2. x = 7 + 2 = 9.
    The correct answer is 9.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *