Java Quiz 23

Test your understanding of Switch statement in java :

 

package quiz;

public class Quiz23 {

  public static void main(String[] args) {
    int x =0;
    
    int[] nums= {1,2,3,5};
    
    for (int i:nums)
      switch(i){
        case 1:
          x += i;
        case 5:
          x += i;
        default:
          x += i;
        case 2:
          x += i;
      }
    System.out.println(x);
  }

}

© 2015 – 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

6 comments

  1. But it’s illogical. For example, why it still takes all cases when I=5? It should consider order of cases, shouldn’t it? If we hit 5, we should not hit 1 and possibly should hit 2. I can’t see a reason.

  2. I couldn’t understand the result of Quiz 23.Can you give me a clear explanation?

    1. Hi.. let me try to explain it..

      In this quiz, we have a switch inside a for-each loop. This is allowed in java.
      Since we have 4 elements in nums, it the switch will be evaluated 4 times.
      For first time, i is checked for 1 and match is found in case 1. So, x =1.But since there is no break statement, it will fall through and i will be 4 when it comes out of switch.
      Similarly, the outputs on next iterations are 6, 12 and 27. 27 is the value of x after final loop.
      Let us know if you still have confusions.

      Thanks for visiting.

      1. But it’s illogical. For example, why it still takes all cases when I=5? It should consider order of cases, shouldn’t it? If we hit 5, we should not hit 1 and possibly should hit 2.

  3. […] confident yet ??   Here is a quiz on switch statement :   Java Quiz 23 – Switch statement […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: