LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 6 of 13

Java 8 to Java 21 Features

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Write Java like it is 2026

Interviewers often ask you to rewrite a loop with streams or model a domain with records and sealed types. Show that you know when the modern feature makes code clearer — and when a plain loop is still the better choice.

  • Functional styleLambdas, method references and streams.
  • Data modellingRecords, sealed types and pattern matching.
  • Everyday winsvar, text blocks, Optional and sequenced collections.

Most companies now run Java 17 or 21, and interviewers expect you to write modern Java: streams instead of loops where they help, records instead of boilerplate classes, and switch expressions instead of long if-else chains. These are the features asked about most.

1. What is a functional interface? Name a few built-in ones.

An interface with exactly one abstract method, so a lambda can implement it. @FunctionalInterface makes the compiler check that. The ones to know: Predicate<T> (test), Function<T,R> (apply), Consumer<T> (accept), Supplier<T> (get) and BiFunction.

Predicate<String> isEmail = s -> s.contains("@");
Function<String, Integer> length = String::length;
Supplier<LocalDate> today = LocalDate::now;

2. Explain the Stream API with a practical example.

A stream is a pipeline over data: a source, zero or more intermediate operations (lazy — nothing runs yet) and one terminal operation that triggers the work. Streams do not modify the source and can be used only once.

// Top 3 cities by revenue from delivered orders
Map<String, Double> revenue = orders.stream()
    .filter(o -> o.status() == Status.DELIVERED)
    .collect(Collectors.groupingBy(Order::city, Collectors.summingDouble(Order::amount)));

revenue.entrySet().stream()
    .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
    .limit(3)
    .forEach(e -> System.out.println(e.getKey() + " → " + e.getValue()));

3. What is the difference between map() and flatMap()?

map() transforms each element into exactly one element. flatMap() transforms each element into a stream and flattens all of them into one stream — useful when each item holds a list.

List<String> skills = candidates.stream()
    .flatMap(c -> c.skills().stream())   // List<List<String>> → Stream<String>
    .distinct()
    .toList();

4. How should Optional be used — and misused?

Optional makes “might be absent” explicit in a method's return type and gives you map, orElse and orElseThrow instead of null checks. Do not use it for fields, method parameters or collections (return an empty list instead), and never call get() without checking.

String city = userRepo.findById(id)
    .map(User::address)
    .map(Address::city)
    .orElse("Unknown");

5. What are records and when would you use them?

A record (Java 16) is a concise, immutable data carrier. The compiler generates the constructor, accessors, equals(), hashCode() and toString(). Use records for DTOs, API responses, map keys and value objects. You can add validation in a compact constructor.

public record Money(BigDecimal amount, String currency) {
    public Money {
        if (amount.signum() < 0) throw new IllegalArgumentException("negative amount");
    }
}

6. What are sealed classes?

A sealed class or interface (Java 17) lists exactly which classes may extend it. That gives you a closed set of types, so the compiler can check that a switch covers every case — perfect for modelling results, events or payment types.

sealed interface Payment permits Card, Upi, NetBanking { }
record Card(String last4) implements Payment { }
record Upi(String vpa) implements Payment { }
record NetBanking(String bank) implements Payment { }

7. Show a switch expression with pattern matching.

Switch expressions return a value and use arrows, so there is no fall-through. In Java 21, pattern matching for switch plus sealed types lets you deconstruct records and the compiler enforces exhaustiveness — no default needed.

String describe(Payment p) {
    return switch (p) {
        case Card c       -> "Card ending " + c.last4();
        case Upi(var vpa) -> "UPI " + vpa;              // record pattern
        case NetBanking n -> "Net banking via " + n.bank();
    };
}

8. What other modern features are worth mentioning?

var for local type inference (Java 10), text blocks for multi-line strings such as JSON or SQL (Java 15), instanceof pattern matching (Java 16), helpful NullPointerException messages, sequenced collections with getFirst()/getLast() (Java 21) and virtual threads (Java 21).

String query = """
    SELECT id, name
    FROM employees
    WHERE dept = ?
    """;
if (obj instanceof String s && !s.isBlank()) {
    System.out.println(s.toUpperCase());
}

Remember

Key points

  • Streams are lazy

    Nothing runs until a terminal operation is called.

  • Optional is for return types

    Not for fields, parameters or collections.

  • Records are immutable carriers

    Equals, hashCode and toString are generated.

  • Sealed + switch = exhaustive

    The compiler checks you handled every case.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the difference between findFirst() and findAny()? Intermediate

    findFirst() respects encounter order. findAny() may return any element, which is faster on parallel streams.

  2. 2 When can parallel streams make things slower? Advanced

    For small data, I/O-bound work, operations with shared state, or sources that split poorly such as LinkedList. They also share the common ForkJoinPool with the rest of the application.

  3. 3 What is the difference between a lambda and an anonymous class? Intermediate

    A lambda has no own this (it refers to the enclosing instance), does not create a new class file per use, and can only implement functional interfaces. An anonymous class can have state and implement interfaces with several methods.

  4. 4 Can a record extend another class? Basic

    No — records implicitly extend java.lang.Record and are final. They can implement interfaces.

  5. 5 Collect a list of employees into a map of department → names. Intermediate

    Use groupingBy with a downstream mapping collector.

    Map<String, List<String>> byDept = employees.stream()
        .collect(Collectors.groupingBy(Employee::dept,
                 Collectors.mapping(Employee::name, Collectors.toList())));

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links