From the course: Pattern Matching for Switch in Java 21
Patterns in case labels - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
Patterns in case labels
- [Instructor] If you look at the basic structure of a switch, "obj" here is known as the target or the select expression. From Java 21, it is possible to use any type to test as the target or select expression that is any custom type. A case label of the switch can use a type pattern. Let's examine this. If you compare the "instanceof" with the new switch, with instanceof you write, "if(obj) instanceof String s" here, the target is obj and string s is the type pattern. Similarly in switch, now you can write, "switch(obj) case String s." Here the target is obj and the case label contains the type pattern In this code, pattern matching for instanceof is used to check a type of an object obj, we can write a switch expression to replace this if errors block that uses pattern matching for switch. Let's command the if errors block. You can assign the message variable with the value return from the switch expression like this. Then type "switch." The target or the select expression is obj. Remember to add the semicolon at the end of the switch block like this. Now add the case labels. Type "case," and then a type pattern can be added to the case label like this. Let's say, String s. Next, add the arrow operator. Remember it was introduced back in Java 12 in place of break. Then let's type this statement, "This is a string." And append the variable S. This will be the return value from the switch expression for this case. Similarly, you can add the other two cases as well, integer and double. So let's add them. Case integer I as the type pattern with the I as the pattern variable, and let's say this is an integer. And append the variable I. Case double with the pattern variable D. The type pattern is double D. This is a double, and let's append the variable D. Finally, you need to add the default label. Let's say, unknown type default, let's say, unknown type. Now in line number five, assign obj with some value. Let's say, 100, and run it. It says this is an integer 100. So this is how it works. A case label with the pattern applies if the value of the select expression obj matches the pattern. This is how patterns in case labels look like.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.