Switch Patterns and instanceof
Pattern matching tests a type and names it in one step.
Example
public class Main {
public static void main(String[] args) {
Object o = "hello";
if (o instanceof String s && s.length() > 3) System.out.println(s.toUpperCase());
String r = switch (o) { case Integer i -> "int"; case String s -> "string " + s.length(); default -> "other"; };
System.out.println(r);
}
}Result
HELLO string 5
Exercise
Test a type.
o String s
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.