The default switch

When default would perform? The default position for the results affect you?

default is only performed in the case when the match failed

        int a=4;
        switch (a){
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            case 3:
                System.out.println("3");
                break;
            default:
                System.out.println("default");
                break;
        }

Print result: default

Of course there are special circumstances, is to match the success of the case, but the lack of break statement

        int a=3;
        switch (a){
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            case 3:
                System.out.println("3");
            default:
                System.out.println("default");
                break;
        }

Print Results:

3

default

Under the default location of the results have no effect, there is no default key to use the break, look at what the situation is there break results

        int a=4;
        switch (a){
            default:
                System.out.println("default");
                break;
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            case 3:
                System.out.println("3");
                break;
        }

Print result: default

Then take a look at what the results without break


        int a=4;
        switch (a){
            default:
                System.out.println("default");
            case 1:
                System.out.println("1");
            case 2:
                System.out.println("2");
                break;
            case 3:
                System.out.println("3");
                break;
                }

Print Results:

default
1

2

You can see without break, then we will continue down until it encounters a break or return or switch end

 

 

default statement is not required. switch case statement is a conditional selection statement, find the same case as the value of the entrance, behind the implementation of the program; if all of the case are not met, then find the default entry; If you do not find the exit entire switch statement. Therefore, only a backup default entry, there does not matter. However, it is best to add the code specification for a default in the back, with reference to the code plug specification Alibaba!

Guess you like

Origin blog.csdn.net/qq_30054199/article/details/90439779