Chandresh Mishra
Chandresh Mishra

Reputation: 1189

Switch statement with string wrong output

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);
      }

Upvotes: 1

Views: 252

Answers (2)

SandstormNick
SandstormNick

Reputation: 2011

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

Upvotes: 1

Ori Marko
Ori Marko

Reputation: 58822

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;

Upvotes: 5

Related Questions