Java 21 Pattern Matching Simplifies Code

Pattern Matching in Java 21 — this one quietly changed how we write Java. Before Java 21, checking and casting an object looked like this: if (obj instanceof String) { String s = (String) obj; System.out.println(s.toUpperCase()); } With Java 21 pattern matching for instanceof: if (obj instanceof String s) { System.out.println(s.toUpperCase()); } One line. No explicit cast. The variable s is already scoped and typed. But the real power is in pattern matching for switch (JEP 441): String result = switch (obj) { case Integer i -> "Integer: " + i; case String s -> "String: " + s; case null -> "null value"; default -> "Something else"; }; This is now stable in Java 21. It replaces chains of if-instanceof-cast that every Java developer has written a hundred times. It's also a key topic in the 1Z0-830 Oracle Java SE 21 exam. Our Java 21 OCP Exam Cram Course covers this and all 14 exam objectives — 40 hours (5 days), monthly, Woodmead JHB + online. 📋https://lnkd.in/dJYmDVqP #Java21 #PatternMatching #JavaDeveloper #OracleJava #1Z0830 #CodeCollege #JavaCertification #CleanCode #SouthAfricaTech

I love Java! Nice to see how Java evolved over the years, staying right at the top!

Like
Reply

To view or add a comment, sign in

Explore content categories