Who are the switch and if else statements used for?

We all know that there are two types of select statements in Java, switch and if statements, but when do you use them? Which one is better to use? This has always been a small doubt in everyone's mind.

Now briefly review the basic structure of switch and if statement, and then understand the difference between their usage.

First review the basic structure of switch and if


Without further ado, let's go directly to the code

    case 1:Statement 1;break;    
    case 2:Statement 2;break;    
    case 3:Statement 3;break;    
    default:default statement;

The above is an example of a simple switch statement. Depending on the value of choose, different case statements are selected for execution; if no case value is matched, the default statement is executed.

1. The data type of choose has certain requirements: it can be byte, short, char, int, String, enumeration, of course, different JDK versions have different effects on switch.
2.choose is generally recommended to be a variable, of course, it can also be a constant. The value behind the case is a constant, and the data type of the choose and the value of the case must be consistent.
3. Remember the break after each case statement? break means to exit the switch statement, if there is no break, the case statement will continue to execute.

The above are the more important knowledge points of switch, and make a brief review.

Next, review the if statement

if statement

There are more styles of if statements.
There are three types of if statements: simple if statement, double-branch if statement, and multi-branch if statement

simple if statement

Shown in code as:

    Statement 1
Statement 2

You can directly see from the code that a simple if statement means only if exists. As a simple judgment, no matter whether statement 1 is executed or not, it does not prevent the execution of statement 2 below.

After reviewing the simple if statement, let's talk about the double branch if statement.

Double branch if statement

Remember what a double branch if statement is?
It is to add an opposite conditional else statement to the simple if statement
For example the following code:

if(Condition 1){
    Statement 1
    Statement 2
Statement 3

Judge whether statement 1 needs to be executed by condition 1. If condition 1 is true, execute statement 1 directly; otherwise, execute statement 2. But whether statement 1 or statement 2 is executed, statement 3 will be executed

In the double-branch if statement, you need to know the value range of its else at all times.

multi-branch if statement

What is a multi-branch if statement? It is to add more conditions to choose on the basis of if...else.

if(Condition 1){
    Statement 1
}else if(Condition 2){
    Statement 2
    Statement 3
Statement 4

Since there is an else if, the value of each judgment has changed, but in the multi-branch if statement, although we can add more else if conditions like the following code, but the selected statement will only have one , that is to say, there will only be one execution of statements 1, 2, and 3. Whoever executes the latter first will be invalid, but it will not affect the execution of statement 4.

if(Condition 1){
    Statement 1
}else if(Condition 2){
    Statement 2
}else if(Condition 3){
    Statement 3
    Statement 4
Statement 5

Many students have already mastered the above content

Next, look at a different if statement

double if statement

What is a double if statement?

if(Condition 1){//first if statement
    Statement 1
}if(Condition 2){//second if statement
    Statement 2
Statement 3

This code is a little weird! Multiple if statements appear in a row in a code. The question is, which if statement is executed? The answer is: all may be executed, each if statement has no effect, no matter how many if statements, as long as the conditions are met, they will run.

In the above code, condition 1 and condition 2 have no relationship. As long as condition 1 is satisfied, statement 1 is executed, and as long as condition 2 is satisfied, statement 2 is executed. Both may be executed, of course, they may not be executed; but please note that statement 3 will definitely execute.

Note: Do not confuse the double if statement with the multi-branch if statement.

Now on to our topic

Who are the switch and if else statements used for?

The above review of the basic structure of switch to if else statement.

The difference can also be seen from the basic structure:

switch: mainly compares the value in choose with a case value, and the case value is a definite value.

if else: There will be a condition before each executed statement. This condition can be a Boolean expression like x==0 that matches a certain value, or it can be a Boolean expression that matches a range such as x>10 Mode.

From their structure, we can roughly analyze their usage differences. Here are a few examples to show their differences in detail.

Example 1: According to the requirements of 0-59: E-level 60-69: D-level 70-79: C-level 80-89: B-level 90-100: A-level requirements to grade the input grades

If using an if else statement:

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();//The first two steps are to get the input value
if(x>=0&&x<60){//Note that you need to use &&/|| or &/| to divide the interval between ranges, and the writing of 0<=x<60 is prohibited
    System.out.println("E class");
}else if(x>=60&&x<69){
    System.out.println("D class");
}else if(x>=70&&x<79){
    System.out.println("C class");
}else if(x>=80&&x<89){
    System.out.println("B class");
}else if(x>=90&&x<=100){
    System.out.println("A class");
}else{//Of course, it cannot be ruled out that some students are naughty and input data less than 0 or greater than 100
    System.out.println("wrong input");

And what about using switch to complete that code?

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();//The first two steps are to get the input value
switch(x/10){//Since there are 100 data between 0-100, it is very troublesome to use case to divide one by one,
  //So let x/10 first, such as: the interval of 70-79/10, then both are 7
  case 10:  //It is estimated that some students will have questions. Why do they have to write 10 without processing it?
  //The reason is that 100/10 is equal to 10, so there is the case 10 option, but since the output of 100 and 90-99 is the same,
  //Do not write break, if it is 100, select case 10, do not output, and then directly execute the statement of case 9 to achieve the effect
  case 9:System.out.println("A class");break;  
  case 8:System.out.println("B class");break;  
  case 7:System.out.println("C class");break;  
  case 6:System.out.println("D class");break;  
  case 5:  
  case 4:  
  case 3: 
  case 2:  
  case 1:  
  //Why are there so many statements that are not executed by the case statement above?
  //It is the same as case 10 in between, and the effect of case 5/4/3/2/1/0 is the same, all need to output E level,
  //If you select a value of 0, 1, 2, 3, 4, 5, the effect of case 0 will be executed in the end
  case 0:System.out.println("E class");break;  
  default:System.out.println("wrong input");

As can be seen from the above, the if else statement feels very comfortable to use in this question, but what about switch? It's a lot more complicated.

Let's look at another example

Example 2: The following options are given, and the effect is displayed according to the options:
Input 1: output "normal attack";
Input 2: output "magic attack";
Input 3: then output "use props";
Input 3: then output "escape";

Of course, this question appears more in the content of the game

So what if we use the if else statement?

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();//The first two steps are to get the input value
    System.out.println("Normal Attack");
}else if(x==2){
    System.out.println("Magic attack");
}else if(x==3){
    System.out.println("use props");
}else if(x==4){
    System.out.println("run away");
}else{//Of course, there will still be classmates who are naughty and play cards not according to common sense.
    System.out.println("wrong input");

And what about using a switch statement?

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();//The first two steps are to get the input value
    case 1:System.out.println("Normal Attack");break;    
    case 2:System.out.println("Magic attack");break;    
    case 3:System.out.println("use props");break;    
    case 4:System.out.println("run away");break;    
    default:System.out.println("wrong input");

It can be seen from this example that switch is more concise than if else, and it is unavoidable to feel strange when it is written in such ways as x==0.

From the above two questions, it can be seen that switch is more suitable for selection with exact values, while if else is more suitable for range judgment.

Of course, the above two questions can be converted into each other, that is to say, there is no strict requirement on whether to use switch or if else, and every programmer needs to think carefully about using the right method in the right place.

Of course, our discussion is not over yet. The above is just an example to illustrate the difference between switch and if else. Next, we will explain from their execution efficiency.

The execution efficiency of switch and if else!

In terms of the execution efficiency of the JVM alone, the execution efficiency of switch is higher than that of the if statement:

The reason is: when the switch statement is running, it will first generate a "jump table" to indicate the address of the actual case branch, and the index number of this "jump table" is equal to the case value in switchh, so, switch does not need to traverse all the conditions like if else until the correct condition is found, but only needs to access the table entry corresponding to the index number to achieve the purpose of locating the branch.

Simply put, switch will generate a data statistics table, and count all the values ​​behind the case. When matching, compare the data in the table first. If there is, it will jump directly to the corresponding case statement; if not, it will jump directly. to the default statement.

What about if else? In fact, just now we have briefly said its workflow, here is another explanation:

The if else statement needs to judge the value range one by one until the correct option position is found, which is bound to waste a lot of time.

Therefore, from the point of view of the efficiency of its operation, the switch statement is better.


Here is a brief summary:

1. The switch statement has a higher execution efficiency due to its unique case value judgment method, while the if else statement is slightly slower due to the judgment mechanism.

2. Which select statement to use is related to the current code environment. If it is a range value, it is faster to use an if else statement; if it is a determined value, using switch is a good choice.

All good programs are finally completed after constant thinking, constant pondering, and effort.

Tags: Java data structure JavaSE jvm

Posted by php? on Thu, 06 Oct 2022 22:02:11 +0530