From the course: Pattern Matching for Switch in Java 21
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Using patterns in case labels - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
Using patterns in case labels
- [Instructor] Let's revisit the Person example. In this method, getPersonData. I'm going to implement a switch expression that returns the matched person's data. Because this is a switch expression, I'd start by returning the expression's value. So return and then switch. The target or the select expression would be obj because we are testing the obj object. Obj, the switch block. Put the semicolon at the end. Then you write the case labels. The case label can have a type pattern. That is the type, in this case, employee, followed by the pattern variable that is e. So case Employee e. In this case, you write the case where obj is an employee object. Next, you put the arrow operator and write the statement you want to return. So put the arrow operator. Let's get the employee salary and return it formatted as a float value. So type String.format, format it as a float value. E.getSalary. Similarly, you write another case label, case Student s. The type now is the student, and the…
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.