Module Review: Modern Syntax

1. Key Takeaways

  • Records are Semantic: They are not just data holders; they are transparent carriers for immutable data. They provide thread safety and stable hash codes by default.
  • Sealed Classes Control Hierarchy: Use them to define Algebraic Data Types (ADTs). They allow the compiler to reason about exhaustiveness, eliminating the need for default cases.
  • Pattern Matching is O(1): Modern switch uses optimized bytecode (tableswitch or type switch) to dispatch based on type in constant time, unlike O(N) if-else chains.
  • Switch Expressions are Safer: Arrow syntax (->) prevents fall-through, and expression usage enforces exhaustiveness.
  • Flow Scoping: Pattern variables (e.g., instanceof String s) are only in scope where the pattern is guaranteed to have matched.

[!NOTE] This module explores the core principles of Module Review: Modern Syntax, deriving solutions from first principles and hardware constraints to build world-class, production-ready expertise.

1. Flashcards

Test your knowledge of Modern Java features. Click to flip.

Canonical Constructor

What is it?

The constructor in a Record that takes all components as arguments. It is automatically generated, but you can override it (or use a Compact Constructor) for validation.

tableswitch vs lookupswitch

Which is faster?

tableswitch is O(1) (instant jump) but requires dense keys. lookupswitch is O(log n) (binary search) for sparse keys. Both are faster than O(N) if-else chains.

Subclass Rules

What must a subclass of a sealed class be?

It must be one of three modifiers: final (closed), sealed (restricted), or non-sealed (open).

Flow Scoping

Does the variable exist here: if (!(o instanceof String s)) return; System.out.println(s);

Yes! Since the method returns if it is NOT a string, the compiler knows that if we reach the print statement, 's' MUST be a String.


2. Cheat Sheet

Feature Syntax Example Purpose
Record record P(int x) {} Immutable data carrier
Compact Constructor public P { if (x<0) throw... } Validation without boilerplate
Sealed Interface sealed interface A permits B Restricted inheritance (ADT)
Switch Expression var x = switch(y) { ... }; Switch as a value
Arrow Case case 1 &rarr; "One" Prevents fall-through
Yield yield 10; Return from block in switch
Pattern Match obj instanceof String s Check & Cast in one
Guarded Pattern case String s when s.isEmpty() Pattern + Condition
Record Pattern case Point(var x, var y) Destructure record fields
Null Switch case null &rarr; ... Handle null explicitly

3. Next Steps