18 How to use the switch branch statement of learning Java from scratch?

Author : Sun Yuchang, nicknamed [ Brother Yiyi ], and [ Brother Yiyi ] is also me

CSDN blog expert, Wanfan blogger, Alibaba cloud expert blogger, Nuggets high-quality author

Supporting project information

https://github.com/SunLtd/LearnJava
https://gitee.com/sunyiyi/LearnJava

foreword

In the last article, Brother Yi introduced the concepts of sequence, branch, and loop structure in Java, and focused on explaining the conditional branch in the branch structure. And in the conditional branch, I explained the use of the if conditional branch in detail. Now we should know that the if conditional branch can have various forms such as single branch, multiple branches, and nesting. But in fact, the effect that the if branch can achieve can sometimes be replaced by another technique, which is the switch branch structure.

---------------------------------------------- Foreplay is done After the end, the excitement begins ------------------------------------------

The full text is about [ 3300] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article contains rich cases and videos with pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. Switch branch structure

1 Introduction

Switch combined with case can judge whether a variable or expression is equal to a certain value in a series of values, and each value here is called a branch. When the switch statement is executed, it will first match the value, and when the match is successful, it will enter the corresponding case statement. Then, according to whether there is a break statement, it is judged whether to continue to output, or to jump out of the current switch judgment.

2. Basic Grammar

Before using switch, we must first remember its basic grammatical structure, and its basic grammatical format is as follows:

switch(值){ 
    case 值1: 
        //switch中的值与值1相等时执行的代码 
      break; //可选
    case 值2: 
        //switch中的值与值2相等时执行的代码 
      break; //可选
    case 值3: 
        //switch中的值与值3相等时执行的代码 
      break; //可选
    case 值4: 
        //switch中的值与值4相等时执行的代码 
      break; //可选
    default: 
        //switch中的值与以上所有值都不相等时执行的代码 
      break; //可选
}

So what are the specific requirements for this grammar? please watch the following part.

3. Grammatical rules (emphasis)

According to the grammatical structure of switch introduced above, Brother Yi will give you a detailed explanation of the grammatical rules and requirements of switch.

  • The "value" in the switch (value) statement supports the following types:
    • Integer types: byte, short, int, char and their corresponding packaging classes;
    • Enumeration type, supported from JDK 5 (later Yige will explain enumeration type in detail);
    • String type, supported since JDK 7, and the value after the case tag must be a string constant or literal.
  • There can be multiple case statements after the switch, and each case must be followed by a value to be compared and a colon.
  • The data type of the value behind the case label must be the same as the data type in the switch (value), and it can only be a constant or a literal constant.
  • When the value of the switch (value) is equal to the value in the case statement, the statement behind the case label starts to execute, and the switch statement stops when the break label is encountered.
  • A case statement does not have to have a break statement. If there is no break statement after the case, the program will continue to execute the next case statement until a break statement appears. This phenomenon is called "case penetration".
  • The switch statement can contain a default default branch, which is generally the last branch of the switch statement and is executed when the value of the switch is not equal to the value of the case statement. There is no need to have a break statement in the default branch, and this branch can be placed anywhere, but it is recommended to write it at the end.

4. Execution logic

According to the above grammatical rules, we can combine the following figure to understand the execution logic of the switch statement. The execution logic of the switch is actually equivalent to listing multiple situations separately, and judging which situation matches according to the value we input. Whichever situation is met, enter the corresponding branch to execute. The overall execution logic is like this, as shown in the following figure:

After understanding these theoretical contents, Brother Yi will design a few switch cases for you, and let's do it together.

2. Switch case

1. Basic case

Case requirements: Enter a serial number, which represents the day of the week today, and choose what to do today.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * 千锋教育
 */
public class Demo01 {

	public static void main(String[] args) {
		// switch结构
		Scanner sc=new Scanner(System.in);
		
		//根据输入的数字,选择每天要做的事情
		System.out.println("请输入日期序号,代表今天是星期几");
		int day = sc.nextInt();
		switch (day) {
		case 0:
	        System.out.println("星期天,休息休息");
	        break;
	    case 1:
	    	System.out.println("星期一,开始搬砖");
	        break;
	    case 2:
	        System.out.println("星期二,搬砖好累");
	        break;
	    case 3:
	        System.out.println("星期三,离周末还有3天");
	        break;
	    case 4:
	        System.out.println("星期四,明天就是周五啦");
	        break;
	    case 5:
	        System.out.println("星期五,明天就是周六啦");
	        break;
	    case 6:
	        System.out.println("星期六,开心.....");
	        break;
	    default: 
	        System.out.println("希望天天都是周末...");
	        break;
	}

}

2. case penetration

Brother Yi told you before that if there is no break statement in the case statement, when the value in the switch matches the case successfully, it will start from the current case and execute all subsequent case statements. This phenomenon is called case wear-through through. In general, we need to avoid case penetration and prevent multiple statements from being executed at once. But sometimes, we can also take advantage of this feature to deliberately "penetrate". For example, when several situations have the same processing strategy, you can reduce code writing through "penetration".

Next, Brother Yi will demonstrate the penetration phenomenon through a case. Case requirements: choose A, output "excellent"; choose B: output "good"; choose C: output "average"; choose D, E, etc.: output "poor", and handle other cases by default. It is not case sensitive, that is, selecting A and a is the same result.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * 千锋教育
 */
public class Demo01 {

	public static void main(String[] args) {
		// switch结构-case穿透
		Scanner sc=new Scanner(System.in);
        
		// 根据输入的数字,选择每天要做的事情
		System.out.println("请输入成绩等级");
		String level = sc.next();
		switch (level) {
		case "a":
		case "A":
			System.out.println("优秀");
			break;
		case "b":
		case "B":
			System.out.println("良好");
			break;
		case "c":
		case "C":
			System.out.println("一般");
			break;
		case "d"://故意case穿透
		case "D":
		case "E":
		case "F":
			System.out.println("很差");
			break;
		default:
			System.out.println("成绩无效");
			break;
	}

}

3. New features of switch (understand)

1 Overview

We know that "case penetration" may occur when using a switch. If you omit the break statement, it may cause serious logic errors, and such errors are not easy to find in the source code. Therefore, in order to prevent accidental "case penetration", starting from JDK 12, the switch statement has been upgraded to a simpler expression syntax, using a method similar to pattern matching (Pattern Matching) to ensure that only one path will be executed , and we no longer need to manually add break statements.

This new feature can be said to simplify a lot of invalid codes and avoid certain risks, so don’t praise it too much. Next, Brother Yi will design a few cases for you, and talk about the use of switch in JDK 12. Because Yi Ge's current JDK version is JDK 17, which is backward compatible with JDK 12, so we don't need to install JDK 12 separately.

2. Code example

2.1 ->Symbols

In the switch statement of JDK 12, the -> symbol is supported . Of course, the -> symbol can not be used. It is no problem to continue to use the previous writing method. If there is only one statement behind the case, you can write the statement directly after ->; if there are multiple statements, you need to enclose them with {} . In addition, in the switch statement of JDK 12, there is no need to write the break statement . The new syntax will only execute the matching statement, and there will be no "penetration effect".

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * 千锋教育
 */
public class Demo01 {

	public static void main(String[] args) {
		// switch结构-case穿透
		System.out.println("请选择你的国家");

		Scanner sc = new Scanner(System.in);
		String country = sc.next();
		switch (country) {
		case "中国" -> System.out.println("我是中国人,我自豪!");
		case "日本" -> System.out.println("鬼子脚盆鸡");
		case "美国" -> {
			System.out.println("暂时还是老大");
			System.out.println("喜欢欺负人");
		}
		default -> System.out.println("未知国籍,黑户");
		}
	}

}

2.2 Return result in switch

In JDK 12, we can return the result generated in the switch statement directly, without using the break statement to end . In general, we only return simple values ​​inside switch expressions. But if you want to process multiple complex statements, you can actually write a lot of statements, put these codes in {...} , and then use the yield keyword (described in detail later) to return . The supporting cases are as follows:

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * 千锋教育
 */
public class Demo01 {

	public static void main(String[] args) {
		// switch结构-case穿透
		System.out.println("请选择你的国家");

		Scanner sc = new Scanner(System.in);
		String country = sc.next();

		// 注意:这里的返回值类型,可以是任意类型。我们后面在学习方法时再细说返回值的问题
		String result = switch (country) {
		case "中国" -> "我是中国人,我自豪!";
		case "日本" -> "鬼子脚盆鸡";// 返回值只能有一个
		case "美国" -> {
			String str = "我们就喜欢以德服人";
			// 注意:这里需要返回一个变量!!!
			yield str;
		}
		default -> "未知国籍,黑户";
		};// 注意:这里需要有个“;”,表示语句的结束

		System.out.println("你的国家情况:" + result);
	}

}

------------------------------------------------ The feature film is over, come Smoke afterward --------------------------------------------

4. Conclusion

In this article, Brother Yi introduced the switch branch structure to everyone. So far, we have completed the study of the branch structure in the three major process control structures. Combined with the if statement learned in the previous article, Brother Yi will summarize the similarities and differences between if and switch.

1. Similarities

  • Both if and switch are branch selection statements in Java, and they both belong to conditional branch statements;
  • In many cases, if and switch can achieve similar effects.

2. Differences

  • The switch structure can only handle the case of equivalent condition judgment, and the condition must be an integer, enumeration variable or character variable;
  • The multiple if selection structure does not have many restrictions of the switch structure, especially suitable for the situation when a certain variable is in a certain continuous interval;
  • if is more versatile and flexible than switch. The conditional judgment that can be realized by if may not be realized by switch; the conditional judgment that can be realized by switch must be realized by if.
  • if is more common in applications, but the structure of switch is clearer.
  • The switch uses a lookup table comparison method, so that the conditions of the case must be continuous constants, but the if statement does not have these restrictions.
  • In general, switch is more efficient than if-else . Because the switch uses the Binary Tree algorithm inside, no matter how many cases there are, it only calculates the value once and jumps directly, without comparing and querying one by one, unless the first condition of if-else is true.
  • The efficiency of switch has nothing to do with the number of branches. Only when there are fewer branches, the if statement is more efficient than switch, because switch has a jump table. When there are many branches, it is recommended to use the switch statement.

So if you encounter conditional judgments in the future, do you know how to choose to implement it? In the next article, Brother Yi will lead you to continue to learn the cyclic structure, so please continue to pay attention.

In addition, if you find it difficult to study alone, you can join Yi Ge 's learning mutual aid group, and everyone can exchange and learn together.

5. Supporting video

If you are not used to reading technical articles, or do not have a good understanding of the technical concepts in the article, you can take a look at the video tutorials selected by Yige for you. The Java learning video accompanying this article is linked as follows:

bilibili html5 player

6. Homework for today

1. The first question

Xiao Ming set up automatic dialing for his mobile phone, the functions are as follows:

Press 1: Dial Dad's number

Press 2: dial mother's number

Press 3: dial grandpa's number

Press 4: dial grandma's number

Others: Dial 110

Please use code to simulate this function, and you can give your code implementation in the comment area.

Guess you like

Origin blog.csdn.net/syc000666/article/details/130053033