Skip to content
Guest
Learn Java · Course Syllabus Show lessons
Production Java 21 · 8 min read · Beginner

Pattern Matching & Text Blocks

Write expressive Java 21 code with switch pattern matching, record deconstruction, and multi-line text blocks.

What you'll learn

  • Match types and bind variables cleanly with pattern matching for switch
  • Write clean multi-line JSON or SQL strings using triple-quoted text blocks
  • Use instanceof pattern variables without redundant casts

Java 21 eliminates verbose instanceof casts with pattern matching: if (obj instanceof String s) tests the type and binds s in one step, and switch can match directly on types and guarded conditions (case String s when !s.isBlank() -> ...).

Fill-in-the-Blank Exercise

Pattern Matching instanceof

Check if obj is a String and bind it to s without a manual cast.

if (obj  String ) {
  System.out.println(s.toUpperCase());
}

Live Code Lab

JavaPatternsJava21.java
Expected OutputClick “Run Live” to compile with OpenJDK 21
Int: 42
Text(7): DevPath

Check Your Understanding

Score: 0 / 1

1. What does Java 21's switch pattern matching allow you to do?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind