1

I have a case to study it i had this question which confused me about Switch statement i just need to understand why i dont need the solution of this code .

This switch compares values of an array

It execute the switch and then goes to one of the cases with the same value as current value, but this case is empty with no break and no code so it jumps and execute the code of the next case which has different value from the current one.

if i included a break it will work fine and not execute the next case code but i need to understand why it execute the next case with false value.

public class HelloWorld{

    public static void main(String []args){
        int wd=0;
        String days[]={"sun","mon","wed","sat"};
        for(String s:days){
            switch(s){
            // current value is sat it will execute case "sun"
            case "sat":
            case "sun":
            /*
            *after going through all array values it will execute this    value's code 
            *when the current value is sat
            */
                wd -= 1; 
                break;
            case "mon":
                wd -= 1;
                break;
            case "wed":
                wd+=2;
            }

        }
        System.out.print(wd);
    }
}

i expected the output to be 0 since wd=-1-1+2=0 actual = -1 since its executing case "sun" again

cesarse
  • 362
  • 2
  • 14

2 Answers2

1

switch cases fall through - the execution starts and the label matches and continues until the execution of the case is terminated, usually with a break (although a return, throwing an exception or any other form on abnormal ending will also do the trick).

You can read more about this behavior in Java's tuturoial.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1
case "sat":
case "sun":

If you would change this to an if else statement it would read:

if (s == "sat" || s == "sun")

Basically if you have two cases following each other in that manner, java sees it as a logical or. If you put a break in between, each case is handled on it's own.

Mirko Brandt
  • 455
  • 3
  • 8