HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
4 Topics
Chapter•75 Minutes

Modern Java Language Features

Explore switch expressions, pattern matching, records, sealed classes, text blocks, modules, and modern Java evolution.

Switch Expressions

Switch expressions allow a switch to produce a value and support arrow labels that avoid accidental fall-through.

String category = switch (status) {
    case NEW -> "pending";
    case PROCESSING -> "active";
    case COMPLETED -> "done";
    case FAILED -> "error";
};

When multiple statements are needed before producing a value, yield can return the result from a block. Exhaustiveness is especially useful with enums and sealed hierarchies.

Key Takeaways
  • Switch expressions return values.
  • Arrow cases do not fall through by default.
  • Exhaustiveness can improve safety for closed domains.

Pattern Matching

Pattern matching reduces repetitive type checks and casts.

if (value instanceof String text && !text.isBlank()) {
    System.out.println(text.trim());
}

Modern Java also extends pattern matching to switch in supported releases, making handling of sealed hierarchies more concise.

Use pattern matching to clarify domain logic rather than replacing good object design with large type-dispatch blocks.

Key Takeaways
  • Pattern variables eliminate many explicit casts.
  • Pattern matching works well with sealed hierarchies.
  • Use it to clarify domain logic.

Records and Sealed Hierarchies

Records are concise data carriers. Sealed types restrict extension to a known set.

sealed interface Shape permits Circle, Rectangle {}

record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}

Together, these features help model closed domains where the variants are intentionally known.

Key Takeaways
  • Records reduce boilerplate for data carriers.
  • Sealed types explicitly close an inheritance hierarchy.
  • The combination is useful for finite domain variants.

Text Blocks, Modules, and API Evolution

Text blocks improve multiline string readability.

String json = \"\"\"
    {
      "name": "Java",
      "version": 26
    }
    \"\"\";

The Java Platform Module System introduced modules, explicit dependencies, and stronger encapsulation. Modules can be valuable for large modular applications, although many server applications still primarily use packages and build-tool dependency management.

When adopting new features, consider the deployed JDK, build plugins, runtime environment, and library compatibility.

Key Takeaways
  • Text blocks improve multiline string readability.
  • Modules provide dependency and encapsulation boundaries.
  • Feature adoption must consider the complete toolchain.