Junior — Middle
Can you explain what pattern matching means in programming?
sobes.tech AI
Answer from AI
Pattern matching is a mechanism in programming that allows you to check the structure of data and extract values from it if it matches a certain pattern. In Java, starting from version 16 and above, pattern matching features have been introduced, for example, for instanceof and switch operators.
Example with instanceof:
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.toUpperCase()); // s is already a String variable
}
Here, we simultaneously check that obj is a string and create a new variable s that contains the cast value.
Pattern matching simplifies code, making it more readable and eliminating the need for explicit type casts and nested conditions.