Java 21 Interview Questions

Java 21, the latest release in the Java platform, brings numerous new features, enhancements, and performance improvements. If you're preparing for a job interview that involves Java 21, it's essential to understand its core concepts, new features, and best practices. This blog post covers some of the most commonly asked Java 21 interview questions and answers to help you prepare effectively.

1. What are the key new features introduced in Java 21?

Answer: Java 21 introduces several new features and enhancements, including:

  • Pattern Matching for switch: Enhanced pattern matching capabilities in switch statements.
  • Sequenced Collections: A new collection type that maintains insertion order.
  • Virtual Threads (Project Loom): Lightweight threads for better scalability in concurrent applications.
  • Record Patterns: Improved pattern matching with records.
  • String Templates (Preview): Simplified string interpolation for creating formatted strings.
  • Foreign Function & Memory API: Enhanced support for interfacing with non-Java code and memory.
  • Universal Generics (Preview): Enhanced generics that can work with primitives.

2. What is Pattern Matching for Switch in Java 21, and how does it work?

Answer: Pattern Matching for a switch in Java 21 extends the switch statement and expression with pattern matching capabilities. This allows more concise and readable code when working with different types and conditions.

Example:

public String formatShape(Object shape) {
    return switch (shape) {
        case Circle c -> "Circle with radius " + c.radius();
        case Rectangle r -> "Rectangle with width " + r.width() + " and height " + r.height();
        case null -> "Unknown shape";
        default -> "Unknown shape type";
    };
}

In this example, the switch statement matches the type of the shape variable and binds it to a variable (c or r) if it matches the specified type.

3. What are Sequenced Collections in Java 21?

Answer: Sequenced Collections in Java 21 are a new type of collection that maintains the order of elements based on their insertion order. They provide methods for accessing elements by their order and for iterating over the elements in insertion order.

Example:

import java.util.SequencedCollection;
import java.util.SequencedHashSet;

SequencedCollection<String> sequencedCollection = new SequencedHashSet<>();
sequencedCollection.add("A");
sequencedCollection.add("B");
sequencedCollection.add("C");

for (String element : sequencedCollection) {
    System.out.println(element); // Output: A B C
}

4. What are Virtual Threads in Java 21, and how do they improve concurrency?

Answer: Virtual Threads, introduced as part of Project Loom in Java 21, are lightweight threads that provide better scalability for concurrent applications. Unlike traditional platform threads, virtual threads are managed by the Java runtime and can handle a large number of concurrent tasks with lower overhead.

Example:

public void runConcurrentTasks() throws InterruptedException {
    ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
    List<Callable<String>> tasks = List.of(
        () -> "Task 1",
        () -> "Task 2",
        () -> "Task 3"
    );

    List<Future<String>> results = executor.invokeAll(tasks);
    for (Future<String> result : results) {
        System.out.println(result.get()); // Output: Task 1 Task 2 Task 3
    }
    executor.shutdown();
}

5. What are Record Patterns in Java 21, and how are they used?

Answer: Record Patterns in Java 21 enhance pattern matching by allowing patterns to be used with records. This simplifies the extraction of values from record instances.

Example:

public record Point(int x, int y) {}

public void printPoint(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        System.out.println("Point coordinates: (" + x + ", " + y + ")");
    } else {
        System.out.println("Not a point");
    }
}

Point point = new Point(1, 2);
printPoint(point); // Output: Point coordinates: (1, 2)

6. How do String Templates work in Java 21?

Answer: String Templates (introduced as a preview feature) simplify string interpolation by allowing embedded expressions within string literals. This makes it easier to create formatted strings.

Example:

int x = 10;
int y = 20;
String message = STR."The sum of \{x} and \{y} is \{x + y}";
System.out.println(message); // Output: The sum of 10 and 20 is 30

7. What is the Foreign Function & Memory API in Java 21?

Answer: The Foreign Function & Memory API in Java 21 provides enhanced support for interfacing with non-Java code and managing native memory. This API allows Java programs to call native functions and manipulate native memory safely and efficiently.

Example:

import jdk.incubator.foreign.*;

public class ForeignMemoryExample {
    public static void main(String[] args) {
        try (MemorySegment segment = MemorySegment.allocateNative(100)) {
            MemoryAccess.setIntAtOffset(segment, 0, 42);
            int value = MemoryAccess.getIntAtOffset(segment, 0);
            System.out.println("Value: " + value); // Output: Value: 42
        }
    }
}

8. What are Universal Generics in Java 21?

Answer: Universal Generics (introduced as a preview feature) enhance Java generics to work with both reference types and primitive types. This allows for more flexible and efficient generic programming.

Example:

public class UniversalGenericExample {
    public static <T> T identity(T value) {
        return value;
    }

    public static void main(String[] args) {
        int intValue = identity(42);
        String stringValue = identity("Hello");
        System.out.println("Int: " + intValue + ", String: " + stringValue); // Output: Int: 42, String: Hello
    }
}

9. What improvements have been made to the Java language in Java 21?

Answer: Java 21 includes several language improvements, such as:

  • Enhanced Pattern Matching: Improved support for pattern matching in various constructs.
  • Sequenced Collections: Introduction of sequenced collections that maintain insertion order.
  • String Templates: Simplified string interpolation with embedded expressions.
  • Universal Generics: Enhanced generics for both reference and primitive types.
  • New and Enhanced APIs: Improvements to existing APIs and introduction of new APIs for better functionality and performance.

10. How do you migrate a project to Java 21?

Answer: To migrate a project to Java 21, follow these steps:

  1. Update JDK: Download and install the Java 21 JDK.
  2. Update Build Tools: Ensure that your build tools (e.g., Maven, Gradle) are compatible with Java 21.
  3. Update Project Settings: Update your project's settings to use the Java 21 JDK.
  4. Refactor Code: Refactor your code to take advantage of new features and improvements in Java 21.
  5. Run Tests: Run your project's tests to ensure compatibility and correctness.
  6. Address Deprecations: Address any deprecated APIs or features that have been removed or changed in Java 21.

Example (Maven pom.xml update):

<properties>
    <java.version>21</java.version>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>21</source>
                <target>21</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Conclusion

Java 21 brings many new features and enhancements that improve the language's expressiveness, performance, and ease of use. Understanding these new features and how to leverage them in your projects is crucial for any Java developer. This blog post covered some of the most commonly asked Java 21 interview questions, helping you prepare effectively for your next interview. By mastering these concepts, you will be well-equipped to tackle any Java 21-related challenges you may encounter.

Comments