Search code examples
javaswitch-statementcoding-style

how does the output became 2? don't understand


public class Ex33 {
    public static void main(String[] args) {
        int x = 3, result = 4;
        switch (x + 3) {
            case 6: result = 0;
            case 7: result = 1;
            default: result += 1;
        }
        System.out.println(result);
    }
}

Don't understand how the answer became 2?


Solution

  • Because of the absence of break; in each case, your case statements are falling through and fail to come out of the loop. All your cases are being applied, hence resulting in result = 2.

    The correctly formatted code will look like this:

        int x =3, result=4;
    
        switch (x+4){
            case 6: 
                result = 0;
                break;
    
            case 7: 
                result = 1;
                break;
    
            default: 
                result+=1;
        }
    
        System.out.println(result);