You are here
Home > java > Core Java >

Java 21 Coding Interview Questions and Answers

Java 21 Coding Interview Questions and Answers (17 Practical Programs)

Java 21 Coding Interview Questions and Solutions covering Pattern Matching, Record Patterns, Virtual Threads, Sequenced Collections, Sealed Classes and Java Streams.Java continues to evolve with new language features and APIs that make application development more efficient, readable, and maintainable. Java 21 is an important Long-Term Support (LTS) release that introduces several improvements, including Record Patterns, Pattern Matching for switch, Virtual Threads, and Sequenced Collections.

In this article, we will explore Java 21 Coding Interview Questions and Answers with practical programming examples, complete source code, expected outputs, and detailed explanations.

The questions cover both modern Java 21 features and commonly asked coding problems involving collections, Streams, sorting, grouping, and concurrency.

Whether you are preparing for a Java developer interview or upgrading your knowledge from Java 8 or Java 17, these coding examples will help you understand how to apply modern Java capabilities to real-world programming problems.

Table of Contents

Who Should Read This Article?

This article is particularly useful for:

  1. Java developers preparing for technical interviews.
  2. Developers upgrading their skills from Java 8 or Java 17 to Java 21.
  3. Software engineers with 2–10 years of experience.
  4. Developers preparing for Java coding rounds.
  5. Developers interested in modern Java programming techniques.

Important Java 21 Features Covered in This Article

Before exploring the coding questions, let’s understand the major Java 21 features used in the examples.

Feature JEP Status in Java 21
Record Patterns JEP 440 Final
Pattern Matching for switch JEP 441 Final
Virtual Threads JEP 444 Final
Sequenced Collections JEP 431 Final
Structured Concurrency JEP 453 Preview
String Templates JEP 430 Preview
Unnamed Patterns and Variables JEP 443 Preview
Scoped Values JEP 446 Preview

Note: Some features listed above are preview features, not permanent Java 21 features. We will clearly identify them in the relevant coding examples. Also, Sealed Classes and Records were finalized before Java 21, but they are useful when demonstrating Java 21 programming techniques.

Java 21 Coding Interview Questions and Answers

Q#1. How to process different object types using Pattern Matching for switch?

Problem Statement:

Suppose you are developing an application that processes different types of objects, such as Integer, Double, String, and Boolean.

Write a Java program that identifies the object’s type and performs the appropriate operation using Pattern Matching for switch.

Solution:

Java 21 finalized Pattern Matching for switch through JEP 441.

It allows developers to match an object against different types and access the matched value directly without explicit type casting.

public class PatternMatchingSwitchExample {

    public static String processObject(Object obj) {

        return switch (obj) {
            case Integer i -> "Integer value: " + i;
            case Double d -> "Double value: " + d;
            case String s -> "String value: " + s;
            case Boolean b -> "Boolean value: " + b;
            case null -> "Object is null";
            default -> "Unsupported data type";
        };
    }

    public static void main(String[] args) {

        System.out.println(processObject(100));
        System.out.println(processObject(25.5));
        System.out.println(processObject("Java 21"));
        System.out.println(processObject(true));
        System.out.println(processObject(null));
    }
}

Output:

Integer value: 100
Double value: 25.5
String value: Java 21
Boolean value: true
Object is null

Explanation:

  • case Integer i checks whether the supplied object is an Integer and binds it to variable i.
  • case Double d matches Double objects.
  • case String s matches String objects.
  • case Boolean b matches Boolean objects.
  • case null explicitly handles null values.

The default branch handles unsupported object types.

One important advantage is that Java automatically handles the type matching and variable binding.

Java 21 feature used: Pattern Matching for switch (JEP 441).

Interview Tip: Understand the difference between traditional switch statements, instanceof pattern matching, and Pattern Matching for switch.

Q#2. How to extract nested record values using Record Patterns?

Problem Statement:

Suppose an application stores employee information along with residential address details.

Create records for Employee and Address. Write a Java 21 program that extracts employee and address information using nested Record Patterns.

Solution:

Record Patterns were finalized in Java 21 through JEP 440.

They allow developers to deconstruct record objects and extract their component values directly.

record Address(String city, String country) {}

record Employee(String name, int age, Address address) {}

public class RecordPatternExample {

    public static void displayEmployee(Object obj) {

        if (obj instanceof Employee(
                String name,
                int age,
                Address(String city, String country))) {

            System.out.println("Employee Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("City: " + city);
            System.out.println("Country: " + country);
        }
    }

    public static void main(String[] args) {

        Employee employee = new Employee(
                "Rahul", 30,
                new Address("Delhi", "India"));

        displayEmployee(employee);
    }
}

Output:

Employee Name: Rahul
Age: 30
City: Delhi
Country: India

Explanation:

The nested pattern:

Employee(
    String name,
    int age,
    Address(String city, String country)
)

deconstructs the Employee record and its nested Address record.

Without Record Patterns, developers would typically call multiple accessor methods:

employee.name();
employee.age();
employee.address().city();
employee.address().country();

Record Patterns make the extraction process more concise and readable.

Java 21 feature used: Record Patterns (JEP 440).

Q#3. How to implement a payment processing system using Sealed Classes?

Problem Statement:

Design a payment processing system that supports three payment methods:

  1. Credit Card
  2. UPI
  3. Net Banking

Use Sealed Classes or Interfaces to restrict the payment methods supported by the system.

Solution:

Sealed Classes were finalized in Java 17. They are fully supported in Java 21.

A sealed interface or class restricts which classes can extend or implement it.

sealed interface Payment
        permits CreditCard, UPI, NetBanking {
}

record CreditCard(double amount) implements Payment {}

record UPI(double amount) implements Payment {}

record NetBanking(double amount) implements Payment {}

public class PaymentProcessor {

    public static String processPayment(Payment payment) {

        return switch (payment) {

            case CreditCard c ->
                    "Processing Credit Card payment: " + c.amount();

            case UPI u ->
                    "Processing UPI payment: " + u.amount();

            case NetBanking n ->
                    "Processing Net Banking payment: " + n.amount();
        };
    }

    public static void main(String[] args) {

        System.out.println(processPayment(new CreditCard(5000)));
        System.out.println(processPayment(new UPI(2000)));
        System.out.println(processPayment(new NetBanking(3000)));
    }
}

Output:

Processing Credit Card payment: 5000.0
Processing UPI payment: 2000.0
Processing Net Banking payment: 3000.0

Explanation:

  • sealed interface Payment restricts the permitted implementations.
  • The permits clause explicitly specifies the permitted classes.
  • Each payment type is represented using a record.
  • Pattern Matching for switch processes each payment type.
  • The switch expression is exhaustive because all permitted payment implementations are covered.

Java features used: Sealed Interfaces, Records, and Pattern Matching for switch.

Interview Tip: Understand the differences between sealed, non-sealed, and final classes.

Q#4. How to calculate the area of different shapes using Pattern Matching?

Problem Statement:

Create a Java program that calculates the area of different geometric shapes, such as circles and rectangles.

Use Sealed Interfaces and Pattern Matching for switch.

Solution:

sealed interface Shape permits Circle, Rectangle {}

record Circle(double radius) implements Shape {}

record Rectangle(double length, double width) implements Shape {}

public class ShapeCalculator {

    public static double calculateArea(Shape shape) {

        return switch (shape) {

            case Circle c ->
                    Math.PI * c.radius() * c.radius();

            case Rectangle r ->
                    r.length() * r.width();
        };
    }

    public static void main(String[] args) {

        Shape circle = new Circle(5);

        Shape rectangle = new Rectangle(10, 5);

        System.out.println(
                "Circle Area: " + calculateArea(circle));

        System.out.println(
                "Rectangle Area: " + calculateArea(rectangle));
    }
}

Output:

Circle Area: 78.53981633974483
Rectangle Area: 50.0

Explanation:

This example combines three useful Java features:

  • Sealed Interfaces restrict the permitted shape implementations.
  • Records represent shape data.
  • Pattern Matching for switch identifies the shape and calculates its area.

The compiler can verify that all permitted shape types are handled.

Java 21 relevance: This demonstrates how modern Java language features can work together to solve practical programming problems.

Q#5. How to retrieve the first and last elements of a List using Java 21?

Problem Statement:

Given a List of programming languages, write a Java program to retrieve its first and last elements.

Solution:

Java 21 introduced Sequenced Collections through JEP 431.

The new SequencedCollection interface provides methods to access elements at both ends of a collection.

import java.util.ArrayList;
import java.util.List;

public class SequencedCollectionExample {

    public static void main(String[] args) {

        List<String> languages = new ArrayList<>();

        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");
        languages.add("Go");

        System.out.println("First: " + languages.getFirst());

        System.out.println("Last: " + languages.getLast());
    }
}

Output:

First: Java
Last: Go

Explanation:

Java 21 introduces useful methods for ordered collections:

Method Purpose
getFirst() Returns the first element
getLast() Returns the last element
addFirst() Adds an element at the beginning
addLast() Adds an element at the end
removeFirst() Removes the first element
removeLast() Removes the last element
reversed() Returns a reverse-ordered view

These methods are particularly useful when implementing queues, ordered data structures, and applications that process elements from either end.

For an empty collection, getFirst() and getLast() throw NoSuchElementException.

Java 21 feature used: Sequenced Collections (JEP 431).

Q#6. How to reverse a collection using Sequenced Collections?

Problem Statement:

Given a list of employee names, write a Java program to display its elements in reverse order using Java 21.

Solution:

import java.util.ArrayList;
import java.util.List;

public class ReverseCollectionExample {

    public static void main(String[] args) {

        List<String> employees = new ArrayList<>(
                List.of("Amit", "Rahul", "Priya", "Neha"));

        System.out.println("Original List: " + employees);

        System.out.println(
                "Reversed View: " + employees.reversed());

        System.out.println(
                "Original List Again: " + employees);
    }
}

Output:

Original List: [Amit, Rahul, Priya, Neha]
Reversed View: [Neha, Priya, Rahul, Amit]
Original List Again: [Amit, Rahul, Priya, Neha]

Explanation:

The reversed() method returns a reverse-ordered view of the original collection.

It does not create an independent reversed copy.

Therefore, the original list remains unchanged in this example.

If the underlying list changes, the reversed view reflects those changes as well.

Java 21 feature used: Sequenced Collections (JEP 431).

Interview Tip: Understand the difference between reversing a collection using Collections.reverse() and obtaining a reverse-ordered view using reversed().

Q#7. How to create and execute Virtual Threads in Java 21?

Problem Statement:

Write a Java program to create and execute a Virtual Thread.

Solution:

Virtual Threads are one of the most important features finalized in Java 21 through JEP 444.

They are lightweight threads designed to support applications that execute large numbers of concurrent tasks, particularly tasks involving blocking I/O.

public class VirtualThreadExample {

    public static void main(String[] args)
            throws InterruptedException {

        Thread thread = Thread.startVirtualThread(() -> {

            System.out.println(
                    "Executing thread: "
                    + Thread.currentThread());

        });

        thread.join();

        System.out.println("Main thread completed");
    }
}

Output (illustrative):

Executing thread: VirtualThread[#...]/runnable
Main thread completed

The exact virtual thread identifier and state representation may vary.

Explanation:

  • Thread.startVirtualThread() creates and starts a virtual thread.
  • The lambda expression represents the task executed by the thread.
  • join() makes the main thread wait until the virtual thread completes.

Virtual Threads reduce the resource overhead associated with creating large numbers of platform threads.

Java 21 feature used: Virtual Threads (JEP 444).

Interview Tip: Virtual Threads are particularly useful for I/O-intensive workloads. They do not automatically make CPU-intensive operations execute faster.

Q#8. How to execute multiple tasks concurrently using Virtual Threads?

Problem Statement:

Suppose an application needs to execute multiple independent tasks concurrently.

Write a Java program that executes five tasks using Virtual Threads.

Solution:

Java 21 provides Executors.newVirtualThreadPerTaskExecutor() to create an ExecutorService that starts a new virtual thread for each submitted task.

Java 21 provides Executors.newVirtualThreadPerTaskExecutor() to create an ExecutorService that starts a new virtual thread for each submitted task.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VirtualThreadExecutorExample {

    public static void main(String[] args) {

        try (ExecutorService executor =
                     Executors.newVirtualThreadPerTaskExecutor()) {

            for (int i = 1; i <= 5; i++) {

                int taskId = i;

                executor.submit(() -> {

                    System.out.println(
                            "Executing Task: " + taskId
                            + " | Thread: "
                            + Thread.currentThread());

                });
            }
        }
    }
}

Output (illustrative):

Executing Task: 1 | Thread: VirtualThread[...]
Executing Task: 3 | Thread: VirtualThread[...]
Executing Task: 2 | Thread: VirtualThread[...]
Executing Task: 5 | Thread: VirtualThread[...]
Executing Task: 4 | Thread: VirtualThread[...]

The actual execution order and thread identifiers may vary because the tasks execute concurrently.

Explanation:

  • newVirtualThreadPerTaskExecutor() creates an executor that assigns a new virtual thread to each submitted task.
  • submit() schedules each task for execution.
  • The try-with-resources statement automatically closes the executor.
  • Closing the executor waits for submitted tasks to complete.

Java 21 feature used: Virtual Threads.

Interview Tip: Virtual Threads are not a replacement for every concurrency mechanism. They are especially useful for workloads with many concurrent blocking operations. CPU-intensive tasks still need to be managed according to available processor resources.

Q#9. How to filter employee records using Record Patterns?

Problem Statement:

Suppose an application maintains employee information using records.

Write a Java program to identify employees whose salary exceeds a specified amount using Record Patterns.

Solution:

import java.util.List;

record EmployeeData(
        String name,
        String department,
        double salary) {}

public class EmployeeRecordPatternExample {

    public static void main(String[] args) {

        List<EmployeeData> employees = List.of(
                new EmployeeData("Amit", "IT", 80000),
                new EmployeeData("Rahul", "HR", 50000),
                new EmployeeData("Neha", "IT", 95000)
        );

        for (EmployeeData employee : employees) {

            if (employee instanceof EmployeeData(
                    String name,
                    String department,
                    double salary)
                    && salary > 70000) {

                System.out.println(
                        name + " | " + department
                        + " | " + salary);
            }
        }
    }
}

Output:

Amit | IT | 80000.0
Neha | IT | 95000.0

Explanation:

The Record Pattern extracts the employee’s name, department, and salary.

The condition then checks whether the extracted salary exceeds 70,000.

This demonstrates how Record Patterns can simplify the processing of structured data.

Java 21 feature used: Record Patterns (JEP 440).

Q#10. How to implement a notification system using Sealed Interfaces?

Problem Statement:

Design a notification system that supports Email, SMS, and Push notifications.

Use a Sealed Interface to restrict the supported notification types.

Solution:

sealed interface Notification
        permits EmailNotification,
                SMSNotification,
                PushNotification {
}

record EmailNotification(String email)
        implements Notification {}

record SMSNotification(String mobile)
        implements Notification {}

record PushNotification(String deviceId)
        implements Notification {}

public class NotificationProcessor {

    public static void send(Notification notification) {

        switch (notification) {

            case EmailNotification e ->
                    System.out.println(
                            "Sending Email to: " + e.email());

            case SMSNotification s ->
                    System.out.println(
                            "Sending SMS to: " + s.mobile());

            case PushNotification p ->
                    System.out.println(
                            "Sending Push Notification to: "
                            + p.deviceId());
        }
    }

    public static void main(String[] args) {

        send(new EmailNotification("[email protected]"));

        send(new SMSNotification("9876543210"));

        send(new PushNotification("DEVICE123"));
    }
}

Output:

Sending Email to: [email protected]
Sending SMS to: 9876543210
Sending Push Notification to: DEVICE123

Explanation:

The Sealed Interface ensures that only the specified notification classes can implement the interface.

Pattern Matching for switch identifies the notification type and executes the corresponding operation.

This approach is useful when implementing payment systems, notification services, event processors, and other applications with a known set of possible types.

General Java Coding Interview Questions

The following problems are not exclusive to Java 21. However, they remain important in Java coding interviews and help assess a developer’s problem-solving ability.

Q#11. How to find the second-highest number in a List using Java Streams?

Problem Statement:

Given a List of integers, write a Java program to find the second-highest distinct number.

Solution:

import java.util.List;
import java.util.Comparator;

public class SecondHighestExample {

    public static void main(String[] args) {

        List<Integer> numbers =
                List.of(11, 13, 65, 76, 45, 98, 123, 100, 111, 44);

        int secondHighest = numbers.stream()
                .distinct()
                .sorted(Comparator.reverseOrder())
                .skip(1)
                .findFirst()
                .orElseThrow(() ->
                        new IllegalArgumentException(
                                "No second distinct number"));

        System.out.println(
                "Second Highest Number: " + secondHighest);
    }
}

Output:

Second Highest Number: 111

Explanation:

  1. distinct() removes duplicate numbers.
  2. sorted() sorts numbers in descending order.
  3. skip(1) skips the highest number.
  4. findFirst() retrieves the second-highest number.
  5. orElseThrow() throws an exception if no second distinct value exists.

Interview Tip: Be prepared to explain how you would solve this problem without sorting the complete collection.

Q#12. How to find duplicate elements in a List using Java Streams?

Problem Statement:

Given a List of integers, identify all duplicate elements using Java Streams.

Solution:

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class DuplicateElementsExample {

    public static void main(String[] args) {

        List<Integer> numbers =
                List.of(10, 20, 30, 20, 40, 10, 50);

        Set<Integer> seen = new HashSet<>();

        Set<Integer> duplicates = numbers.stream()
                .filter(n -> !seen.add(n))
                .collect(Collectors.toCollection(
                        LinkedHashSet::new));

        System.out.println("Duplicates: " + duplicates);
    }
}

Output:

Duplicates: [20, 10]

Explanation:

The HashSet stores elements already encountered in the stream.

The add() method returns false when an element already exists in the set.

The filter() operation therefore retains duplicate occurrences.

A LinkedHashSet is used to collect the duplicate values while preserving their encounter order.

Important: This solution uses state inside a stream predicate and is intended for sequential streams. Avoid using this approach with parallel streams.

Q#13. How to count the frequency of characters in a String?

Problem Statement:

Given a String, write a Java program to count the frequency of each character.

Solution:

import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharacterFrequencyExample {

    public static void main(String[] args) {

        String input = "programming";

        Map<String, Long> frequency = input.codePoints()
                .mapToObj(cp -> new String(
                        Character.toChars(cp)))
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        TreeMap::new,
                        Collectors.counting()));

        frequency.forEach((character, count) ->
                System.out.println(
                        character + " = " + count));
    }
}

Output:

a = 1
g = 2
i = 1
m = 2
n = 1
o = 1
p = 1
r = 2

Explanation:

  • codePoints() processes Unicode code points instead of individual UTF-16 code units.
  • mapToObj() converts each code point into a String.
  • groupingBy() groups identical characters.
  • TreeMap maintains the keys in sorted order.
  • counting() calculates the number of occurrences.

This approach is more suitable than chars() when the input may contain supplementary Unicode characters, such as certain emoji.

Q#14. How to group employees by department and calculate average salary?

Problem Statement:

Given a list of employees, group them by department and calculate the average salary for each department.

Solution:

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Employee(String name, String department, double salary) {}

public class EmployeeGroupingExample {

    public static void main(String[] args) {

        List<Employee> employees = List.of(
                new Employee("Amit", "IT", 80000),
                new Employee("Neha", "IT", 90000),
                new Employee("Rahul", "HR", 50000),
                new Employee("Priya", "HR", 60000)
        );

        Map<String, Double> averageSalary =
                employees.stream()
                        .collect(Collectors.groupingBy(
                                Employee::department,
                                TreeMap::new,
                                Collectors.averagingDouble(
                                        Employee::salary)));

        averageSalary.forEach((department, average) ->
                System.out.println(
                        department + " = " + average));
    }
}

Output:

HR = 55000.0
IT = 85000.0

Explanation:

  • groupingBy() groups employees by department.
  • Employee::department extracts the department name.
  • TreeMap::new ensures that department keys are displayed alphabetically.
  • averagingDouble() calculates the average salary for each group.

This is a common interview problem involving Java Streams and Collectors.

Q#15. How to find the most frequently occurring word in a String?

Problem Statement:

Given a sentence, write a Java program to identify the word that occurs most frequently.

Solution:

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostFrequentWordExample {

    public static void main(String[] args) {

        String sentence =
                "Java is powerful and Java is popular Java";

        Map<String, Long> frequency =
                Arrays.stream(sentence.toLowerCase()
                                .split("\\s+"))
                        .collect(Collectors.groupingBy(
                                Function.identity(),
                                TreeMap::new,
                                Collectors.counting()));

        Map.Entry<String, Long> result =
                frequency.entrySet()
                        .stream()
                        .max(Map.Entry.comparingByValue())
                        .orElseThrow();

        System.out.println("Word: " + result.getKey());
        System.out.println("Count: " + result.getValue());
    }
}

Output:

Word: java
Count: 3

Explanation:

The program converts the sentence into lowercase words, groups identical words, and counts their occurrences.

Finally, max() identifies the entry with the highest count.

In this example, Java occurs three times, making it the most frequently occurring word.

For sentences containing punctuation, additional text normalization should be performed before splitting the words.

Q#16. How to sort employee records using multiple conditions?

Problem Statement:

Given a list of employees, sort them first by department and then by salary in descending order.

Solution:

import java.util.Comparator;
import java.util.List;

record EmployeeInfo(
        String name,
        String department,
        double salary) {}

public class EmployeeSortingExample {

    public static void main(String[] args) {

        List<EmployeeInfo> employees = List.of(
                new EmployeeInfo("Amit", "IT", 80000),
                new EmployeeInfo("Neha", "IT", 95000),
                new EmployeeInfo("Rahul", "HR", 50000),
                new EmployeeInfo("Priya", "HR", 60000)
        );

        employees.stream()
                .sorted(
                        Comparator.comparing(
                                EmployeeInfo::department)
                        .thenComparing(
                                EmployeeInfo::salary,
                                Comparator.reverseOrder()))
                .forEach(System.out::println);
    }
}

Output:

EmployeeInfo[name=Priya, department=HR, salary=60000.0]
EmployeeInfo[name=Rahul, department=HR, salary=50000.0]
EmployeeInfo[name=Neha, department=IT, salary=95000.0]
EmployeeInfo[name=Amit, department=IT, salary=80000.0]

Explanation:

  • Comparator.comparing() sorts employees by department in ascending order.
  • thenComparing() applies the secondary sorting condition.
  • Comparator.reverseOrder() sorts salary in descending order.

Records also provide automatically generated implementations of methods such as toString(), making the output easier to read.

Java 21 Preview Feature Coding Questions

The following questions demonstrate features that were available as preview features in Java 21.

They require additional compiler and runtime options. Do not confuse these APIs with permanent Java 21 features.

Q#17. How to execute concurrent tasks using Structured Concurrency?

Problem Statement:

Suppose an application needs to retrieve customer information and order information from two independent services.

Write a Java program using Structured Concurrency to execute both tasks concurrently.

Solution:

Structured Concurrency was introduced as a preview feature in Java 21 through JEP 453.

It provides an API for treating related concurrent tasks as a single unit of work.

Java 21 example:

import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.ExecutionException;

public class StructuredConcurrencyExample {

    public static void main(String[] args)
            throws InterruptedException, ExecutionException {

        try (var scope =
                new StructuredTaskScope.ShutdownOnFailure()) {

            var customerTask =
                    scope.fork(() -> "Customer Details");

            var orderTask =
                    scope.fork(() -> "Order Details");

            scope.join();

            scope.throwIfFailed();

            System.out.println(customerTask.get());
            System.out.println(orderTask.get());
        }
    }
}

Output:

Customer Details
Order Details

Explanation:

  • StructuredTaskScope manages related concurrent tasks.
  • fork() starts a subtask.
  • join() waits for the subtasks to complete.
  • ShutdownOnFailure coordinates cancellation when a subtask fails.
  • throwIfFailed() propagates a failure after the tasks complete.

Compilation and execution:

javac --release 21 --enable-preview StructuredConcurrencyExample.java

java --enable-preview StructuredConcurrencyExample

Important: Structured Concurrency was a preview API in Java 21. Its API evolved in subsequent Java releases, so this example must be compiled and executed using a Java 21 JDK.

Important Java 21 Coding Interview Tips

While preparing for Java 21 coding interviews, developers should understand both the practical implementation and the underlying concepts.

Here are some important areas to revise:

Topic What you should understand
Pattern Matching for switch Type matching, guards, null handling and exhaustive switches
Record Patterns Nested record deconstruction and component extraction
Sealed Classes sealed, permits, final and non-sealed
Virtual Threads Thread creation, executors, blocking operations and scalability
Sequenced Collections First/last elements and reverse-ordered views
Records Immutable data carriers and generated methods
Java Streams Grouping, sorting, filtering and reduction
Structured Concurrency Task lifecycle, failure handling and cancellation
String Templates Template processors and preview status

Other Coding Interview Questions References

Topic Reference Link
Java 17 Coding Interview Questions and Answers Java 17 Coding Interview Questions and Answers 
Java 8 Coding Interview Questions and Answers Java 8 Coding Interview Questions and Answers
Java, Spring, Microservices Interview QnA Java, Spring, Microservices & others Interview QnA
Spring Boot Annotations Questions & Answers Spring Boot Annotations MCQs & Explanations

Frequently Asked Questions (FAQs)

Q#1. What are the most important Java 21 coding interview questions?

Some important Java 21 coding interview questions involve concepts of Pattern Matching for switch, Record Patterns, Virtual Threads, Sealed Classes, and Sequenced Collections. Developers should also practise common problems involving Java Streams, collections, sorting, grouping, and string processing.

Q#2. Which Java 21 features are most important for coding interviews?

The most important finalized features include:

  • Record Patterns.
  • Pattern Matching for switch.
  • Virtual Threads.
  • Sequenced Collections.

You should also understand Structured Concurrency and String Templates as Java 21 preview features.

Q#3. Are Java 21 coding interview questions different from Java 17 questions?

Yes. Java 21 introduces additional capabilities, including Record Patterns, Pattern Matching for switch as a finalized feature, Virtual Threads, and Sequenced Collections.

Java 17 introduced finalized features such as Sealed Classes and Pattern Matching for instanceof.

Q#4. Are Virtual Threads suitable for every application?

No. Virtual Threads are particularly useful for applications that handle many concurrent tasks involving blocking I/O.

They are not intended to make CPU-intensive operations execute faster automatically.

Q#5. Is Java 21 an LTS release?

Yes. Java 21 is a Long-Term Support (LTS) release, making it an important version for enterprise application development.

Q#6. Can I run Java 21 preview features without enabling preview mode?

No. Preview language features and APIs require the appropriate preview compiler and runtime options.

For Java 21, use –enable-preview along with the appropriate release setting when compiling.

Conclusion

Java 21 brings several important improvements that make Java applications more expressive, scalable, and maintainable.

Features such as Record Patterns, Pattern Matching for switch, Virtual Threads, and Sequenced Collections provide practical solutions to common programming challenges.

However, preparing for Java 21 interviews should not be limited to learning new language features. Developers should also strengthen their understanding of collections, Streams, sorting, grouping, concurrency, and problem-solving techniques.

Practising the coding questions discussed in this article will help you understand how modern Java features can be applied to real-world programming problems and prepare more effectively for Java developer interviews.

If you are upgrading your skills from earlier Java versions, I also recommend exploring our Java 8 and Java 17 coding interview preparation articles to understand how Java programming capabilities have evolved across these releases.

Technical References

These official OpenJDK references are useful for validating the Java 21 features discussed in the article.


You may also go through Java 21 New Features With Examples  & Java Features after Java 8 to check any other version’s feature.

Leave a Reply



Top