-6
class New{
    public static void main(String args[]){
        int x=1;
        switch(x){
            default : System.out.print("default");
            case 1 : System.out.print(1);
            case 2 : System.out.print(2); 
        }
    }
}

This code works properly when I use the break keyword. But I have no idea why this doesn't work properly. Can someone explain the code to me?

abdulwasey20
  • 747
  • 8
  • 21
Thisura
  • 40
  • 10
  • 4
    Step through it in your debugger. Using a debugger isn't an advanced skill, learning to do it is basically the next thing every beginner should do after "Hello, World". – T.J. Crowder Mar 11 '19 at 16:29

1 Answers1

2

The switch statement jumps to the case that matches, and continues processing from there until it sees a break. Since there are no breaks in that code, it starts at case 1, outputs 1, and then continues with case 2 and outputs 2. Although it's rare, sometimes this "fall through to the next case" is what you actually want. But usually, you want break to stop it.

It would say "default", too, if you moved it to the end:

class New {
    public static void main(String args[]){
        int x=1;
        switch(x){
            case 1 : System.out.print(1);
            case 2 : System.out.print(2); 
            default : System.out.print("default");
        }
    }
}

outputs

12default

Similarly, if you set x to 2, it would skip the case 1:

class New {
    public static void main(String args[]){
        int x=2; // <===
        switch(x){
            case 1 : System.out.print(1);
            case 2 : System.out.print(2); 
            default : System.out.print("default");
        }
    }
}

outputs

2default
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • But x=1 right? So why does the case 2 get executed? – Thisura Mar 11 '19 at 16:33
  • 1
    @ThisuraThenuka - As I said above, without the `break`, it continues executing the code from `case 1` onward. It continues into `case 2` (and in my later examples, into `default`). That's why you need `break` if you don't want that to happen, otherwise execution continues with the next case. Although it's rare, *sometimes* this "fall through to the next `case`" is what you actually want. – T.J. Crowder Mar 11 '19 at 16:34