[Solved] Why does this code print 12 instead of 1? [duplicate]


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

2

solved Why does this code print 12 instead of 1? [duplicate]