Skip to main content
InterviewHubPRO
Section Overview
Q5

Question 5 of 50

Part 1: Core Language, Memory Model & Collections (1 - 10)

10%
Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)

What are Java Records, Sealed Classes, and Pattern Matching?

junior LevelCode ExamplejavaCore Language

In Simple Words:

  • Records (Java 16+): Immutable data carrier classes that automatically generate equals(), hashCode(), toString(), and private final fields.
  • Sealed Classes (Java 17+): Restricts which classes or interfaces may extend or implement them using permits, enabling exhaustive compile-time domain modeling.
  • Pattern Matching for Switch (Java 21+): Type pattern matching with guard clauses (when), replacing ugly chains of instanceof casts.
java
// Domain modeling with Sealed Interface and Records
public sealed interface PaymentStatus permits Approved, Declined, Pending {}

public record Approved(String transactionId, double amount) implements PaymentStatus {}
public record Declined(String reasonCode) implements PaymentStatus {}
public record Pending(long queuedAtTimestamp) implements PaymentStatus {}

// Pattern Matching Switch
public String processPayment(PaymentStatus status) {
    return switch (status) {
        case Approved a when a.amount() > 10_000 -> "Large Approval: " + a.transactionId();
        case Approved a -> "Standard Approval: " + a.transactionId();
        case Declined d -> "Declined: " + d.reasonCode();
        case Pending p -> "Waiting for gateway";
    };
}