Java If...else if...else Statements
The If statement can be followed by a elseif...else statement, which detects a variety of possible scenarios.
When using the If,else if,else statement, the following points need to be noted:
- The IF statement has at most 1 else statements, and ELSE statements after all ElseIf statements.
- An If statement can have several ElseIf statements, which must precede the Else statement.
- Once one of the else if statements detects true, the other else if and else statements will skip execution. (This is different from JS, can be self-testing)
Java
The switch statement has the following rules:
The variable type in the switch statement can be: Byte, short, int, or char. Starting with Java SE 7, switch supports string types, and case labels must be string constants or literals.
A switch statement can have more than one case statement. Each case is followed by a value and a colon to compare.
The data type of the value in the case statement must be the same as the data type of the variable, and can only be constants or literal constants.
When the value of a variable is equal to the value of the case statement, the statement after the case statement starts executing until the break statement appears and jumps out of the switch statement.
The switch statement terminates when a break statement is encountered. The program jumps to the statement following the switch statement execution. The case statement does not have to contain a break statement. If no break statement appears, the program continues to execute the next case statement until a break statement appears.
A switch statement can contain a default branch, which must be the last branch of a switch statement. Default is executed when there is no case statement with the value equal to the value of the variable. The default branch does not require a break statement.
If...else if...else and switch statements, as well as the difference between the If...else If...else and JS