1

I came across this basic question, where switch case is used with string.

Break statement is not used between cases but why it going to all the cases even when it is not matching the case string?

So I'm curious to know why is the output 3 and not 1?

 public static void main(String [] args)
      {
        int wd=0;

        String days[]={"sun","mon","wed","sat"};

        for(String s:days)
        {
          switch (s)
          {
          case "sat":
          case "sun":
            wd-=1;
            break;
          case "mon":
            wd++;
          case "wed":
            wd+=2;
          }
        }
        System.out.println(wd);
      }
2
  • But your code contains a break statement. Commented Apr 4, 2019 at 11:11
  • you should had use "debug" before posting your question here. Commented Apr 4, 2019 at 11:24

2 Answers 2

5

You don't have a break; at the end of case "mon" so value is also incremented by 2

which you didn't expect, flow:

0    -1   -1   +1+2  +2 = 3
^     ^    ^   ^     ^
init sat  sun  mon  wed 

Adding a break as below will result with output 1

case "mon":
  wd++;
  break;
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I am not able to understand. "mon" is not equal to "wed" so why the value is getting incremented by two?
@ChandreshMishra switch is finding mon and it continue to wd+=2; because there's no stopping break;, you can test different flows it by removing existing break;
Thanks man. what I was thinking that Break will only stop the unnecessary checking and save the cpu and time. lol.
1

There is no break; at the end of cases for "sat" and "mon". This means that when an element matches "sat" and "mon" case it will execute the code contained in that case but then fall into the next case.

When the break is reached, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block.

In this instance. When it tests "sat" and "mon", it does not see a break and therefore continues testing.

0   -1    0    2    4    3
^    ^    ^    ^    ^    ^
    sun  mon  mon  wed  sat

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.