Switch Statements

前端 未结 4 665
遇见更好的自我
遇见更好的自我 2021-01-18 22:14

For switch statements, is it possible to change the value of the switch inside the switch statement so that it can jump around to different cases? Ex:

int w          


        
4条回答
  •  情歌与酒
    2021-01-18 22:33

    No, it will not change and will not execute new case statement.

    Remember that, once appropriate match is found with the case statement corresponding to a value inside the switch statement, that particular case is executed and once that is executed ( if break is provided after each case to prevent falling through all cases) , then the control returns to the end of switch statement.

    Sample Code :

    public  class A {
                public static void main(String [] args) {
                        int i=1;
                        switch(i) {
                                case 1 : 
                                        System.out.println("Case 1");
                                        i = 2;
                                        break;
                                case 2 : 
                                        System.out.println("Changed to Case 2");
                                        break;
    
                                 default:
                                        System.out.println("Default");
                                        break;
                                }
    
                        System.out.println("Final value of i " + i);
                }
        }
    

    Output :

    Case 1
    Final value of i 2  
    

    Note : Inserting proper breakpoints, try to debug. You will come to know yourself, what exactly is happening.

提交回复
热议问题