Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java switch basic introduction and how to use it


May 10, 2021 Java



In writing code, logical judgment is unavoidable, the function of switch case statements in many programming languages is used for conditional judgment, java for the multiple branch selection process specifically provides switch statements, switch statements according to the value of an expression, choose to run one of several operations. /b11> The use of switch statements is more concise when equal judgment of options is required. /b12> Switch's case statement can handle the values of int, short, byte, char types, but not long, String, etc. /b20> You should also think of another commonly used conditional judgment statement, if else, which focuses on the use of switch case statements in java, but summarizes the differences between the two statements at the end of the article.


Java switch basic introduction and how to use it


Java switch basic syntax

switch(表达式){ 
case 表达式常量1:语句1breakcase 表达式常量2:语句2break; 
...... 
case 表达式常量n:语句n; 
break; 
[default:语句n+1;] 
} 

Where a case expression constant becomes a label, representing the entry point of a case branch. T he switch statement first evaluates the value of "expression" in switch parentheses at run time, which must be integer or character type, and the value of the following case expression constants should be the same as the value type of "expression" in switch parenthesis. A case statement represents a formulation operation and then turns to the structural outlet. T he default clause is optional, and when the value of the expression does not match the value of the case expression constant, the default clause is run and turned to the structure exit.

The order in which switch is executed in java

The value of the switch expression determines which case branch to select, and if the branch cannot be found, output directly from "default".
When a program executes a case statement, because there are no break and return statements in the case branch in the example, the program executes the statement immediately after it.

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

The output is as follows:

default
1
2

public class Switch {
    public static void main(String[] args) {
        int x = 0;
        switch (x) {
        default:
            System.out.println("default");
        case 0:
            System.out.println(0);
        case 1:
            System.out.println(1);
       case 2:
            System.out.println(2);
        }
    }
}
The output is as follows:
0
1
2

public class Switch {
    public static void main(String[] args) {
        int x = 0;
        switch (x) {
        case 0:
            System.out.println(0);
        case 1:
            System.out.println(1);
        case 2:
            System.out.println(2);
        default:
            System.out.println("default");
        }
    }
}
The output is as follows:
0
1
2
default

Java switch basic introduction and how to use it

Java switch statement considerations

switch(A), the value of A in parentheses can only be an integer or can be converted to an integer numeric type, such as byte, short, int, char, and enumeration;

case B:C;case is a constant expression, that is, the value of B can only be a constant (need to define a final-type constant, followed by a detailed description of the reason) or inint, byte, short, char (e.g. 1, 2, 3, 200000000000 (note that this is an integer), if you need to write an expression or variable here, then add a single quote after the statement can not be braces; Is that C does not need to be wrapped in braces;

Default is to execute it without a compliant case, and default is not required.


Case study:

1. Standard (there are break statements after case, the values after case are integers)

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

2. Constant type (there are break statements after case, the values after case are constants)

private final int NUM1=1private final int NUM2=1int i=3; 
switch(i) 
{ 
case NUM1: 
System.out.println(1); 
break; 
case NUM2: 
System.out.println(2); 
break;  
default: 
System.out.println("default"); 
break; 
} 

3. Expression type (there are break statements after case, the values after case are expressions)

int i=3; 
int b = 2;
switch(i) 
{ 
case ‘类名.getId()‘: 
System.out.println(1); 
break; 
case ‘b‘ 
System.out.println(2); 
break;  
default: 
System.out.println("default"); 
break; 
}

Example: Java uses the switch statement to solve the monthly salary range problem

public class SwitchDemo {
    public static void main(String[] args) {
 
        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

Java switch basic introduction and how to use it

The difference between a switch and an if statement in Java

Switch and if statements are Java's choice statements, both of which allow you to control the execution of a program while it is running.

Switch is faster than if-else because of the Binary Tree algorithm, except that the first condition of if-else is true.


Compiler compiles switch with compilation if... e lse... D ifferent. No matter how many case, jump directly, without comparing queries one by one.

Switch is definitely much more efficient than the if-else structure, but switch uses the method of finding tables to determine that the case condition must be a continuous constant. If-else, on the other, is much more flexible.


Switch is efficient, as can be seen from the assembly code. Switch calculates the value only once, and then test.

The efficiency of switch is independent of the number of branches. W hen only there are fewer branches, if efficiency is higher than switch (because switch has a jump table). There are more branches, and that's of course using switch.