Here are 50 in-depth interview questions and answers on Java 21, tailored for a Java Tech Lead position, complete with explanations.

Core Language Features

1. What are the key language features introduced in Java 21?
Java 21, a Long-Term Support (LTS) version, introduces several significant features aimed at improving developer productivity, code readability, and performance. Key features include Virtual Threads, Sequenced Collections, Record Patterns, Pattern Matching for switch, and String Templates.geeksforgeeks+1

2. Explain Record Patterns (JEP 440) and how they enhance pattern matching.
Record Patterns allow for the deconstruction of record instances, enabling you to access their components directly within a pattern. This simplifies code by combining the type check and the extraction of components into a single operation, often used with instanceof or switch statements.geeksforgeeks

3. What is Pattern Matching for switch (JEP 441) and how does it improve code?
This feature enhances switch statements and expressions to work with patterns. It allows for more expressive and safe code by enabling you to test an expression against a number of patterns, each with a specific action. This reduces the need for long if-else chains and improves code readability.dev

4. How do you use a “guarded pattern” in a switch statement?
A guarded pattern is a pattern that includes a boolean expression in a when clause. The pattern only matches if both the type pattern matches and the boolean expression evaluates to true. This allows for more refined control flow within switch statements.javatechonline

5. What are Unnamed Patterns and Variables (JEP 443)?
This feature allows you to use an underscore _ to denote an unused pattern variable or an unused lambda parameter. This helps to improve code clarity by explicitly marking variables that are not needed, and the compiler can check that they are indeed not used.geeksforgeeks

6. What are String Templates (JEP 430) and how do they differ from string concatenation or String.format()?
String Templates provide a more readable and convenient way to create strings with embedded expressions. Unlike string concatenation, which can be verbose, or String.format(), which separates the template from the values, string templates allow you to mix expressions and code directly within a string literal for better clarity.geeksforgeeks

7. Can you provide an example of a String Template in use?
Before Java 21, you might write:
String s = "Hello, " + name + "!";
With String Templates, you can write:
String s = STR."Hello, \{name}!";
This makes the code more intuitive and less prone to errors.geeksforgeeks

8. What are Sealed Classes and why are they useful?
Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them. This provides more control over your class hierarchy, which is useful for creating more robust and maintainable API designs. It allows the author of a class to control which classes can be its subtypes.myexamcloud+1

9. How do you declare a sealed class and its permitted subclasses?
You use the sealed modifier in the class declaration and the permits clause to specify the allowed subclasses. For example:
public sealed class Shape permits Circle, Square {}
The permitted subclasses must be in the same package or module and must be declared as final, sealed, or non-sealed.dev

10. What is the difference between a final, sealed, and non-sealed subclass of a sealed class?

  • final: The subclass cannot be extended further.
  • sealed: The subclass can be extended, but only by the classes it permits.
  • non-sealed: The subclass can be extended by any class, reverting to the standard rules of inheritance.

Concurrency

11. What are Virtual Threads (JEP 444) and how do they differ from platform threads?
Virtual threads are lightweight threads managed by the Java runtime, not directly by the operating system. A large number of virtual threads can run on a small number of OS threads. This makes them ideal for high-throughput concurrent applications with many I/O-bound tasks, as they consume significantly less memory than traditional platform threads.codementor+1

12. What problem do virtual threads solve?
They address the “thread-per-request” programming model’s scalability limitations. With platform threads, having a thread for each concurrent task can quickly exhaust system resources. Virtual threads allow for millions of concurrent tasks to be handled efficiently with a small pool of platform threads.theserverside

13. How do you create a virtual thread in Java 21?
You can create a virtual thread using the Thread.ofVirtual() factory method or by using Executors.newVirtualThreadPerTaskExecutor().theserverside
Example:
Thread.ofVirtual().start(() -> System.out.println("Hello from a virtual thread!"));

14. What are some potential challenges or pitfalls when using virtual threads?
One key challenge is dealing with “pinned” threads. If a virtual thread executes native code or a synchronized block, it can become pinned to its carrier OS thread, which can limit scalability. It’s important to be mindful of synchronized blocks and consider using ReentrantLock instead.javainuse

15. As a Tech Lead, when would you advocate for using virtual threads over traditional thread pools or reactive programming?
Virtual threads are an excellent choice for applications that follow the traditional thread-per-request model and are I/O-bound. They simplify the code compared to reactive programming’s callback-heavy style. For CPU-bound tasks, a traditional fixed-size thread pool is still more appropriate. A tech lead should analyze the application’s workload to make an informed decision.datacamp

16. What are Structured Concurrency (JEP 453) and Scoped Values (JEP 446)?
These are incubator features that work well with virtual threads.

  • Structured Concurrency simplifies concurrent programming by treating multiple tasks running in different threads as a single unit of work.
  • Scoped Values provide a way to share data within and across threads without using method arguments, similar to thread-local variables but more efficient and safer, especially with virtual threads.

Collections Framework

17. What are Sequenced Collections (JEP 431)?
Java 21 introduces new interfaces that provide a uniform API for collections with a defined encounter order. These interfaces are SequencedCollection, SequencedSet, and SequencedMap.baeldung

18. What new methods do Sequenced Collections provide?
They offer methods to access the first and last elements (getFirst(), getLast()), and to get a reversed view of the collection (reversed()). This standardizes operations that were previously inconsistent across different collection types like List, Deque, and SortedSet.geeksforgeeks

19. How does SequencedCollection improve upon existing collection interfaces?
It provides a common, predictable API for accessing elements from either end of a collection. Before, you might have to cast to a specific type (like Deque or List) to get this functionality. SequencedCollection makes this ability a standard part of the collection’s contract.baeldung

20. Give an example of where reversed() from a SequencedCollection would be useful.
If you have a List of events in chronological order, you can easily get a view of those events in reverse chronological order without creating a new collection or manually iterating backward:
List<String> events = ...;
for (String event : events.reversed()) { ... }geeksforgeeks

Performance & Garbage Collection

21. What improvements have been made to Garbage Collection in Java 21?
Java 21 includes enhancements to the Z Garbage Collector (ZGC), specifically Generational ZGC (JEP 439). This divides the heap into generations (young and old), allowing the GC to collect young objects more frequently and efficiently, which can lead to lower latency and reduced CPU overhead for many applications.geeksforgeeks

22. Explain the concept of Generational ZGC.
Generational ZGC builds on the concurrent and low-pause-time characteristics of ZGC by adding support for object generations. Most objects in a typical application have a short lifespan. By focusing garbage collection efforts on the young generation, where most objects “die,” the collector can run more quickly and with less overhead than a full heap scan.geeksforgeeks

23. As a Tech Lead, what factors would you consider when choosing a garbage collector for a new service?
The choice depends on the application’s requirements for latency, throughput, and memory footprint.

  • G1GC is a good default for many applications.
  • ZGC or Shenandoah are excellent for applications requiring very low pause times (low latency), such as UI applications or financial trading platforms.
  • The Serial GC is suitable for applications with small heaps and no low-latency requirements.
    With Java 21, Generational ZGC makes ZGC a more compelling option for a wider range of applications.datacamp

APIs & Libraries

24. What is the Foreign Function & Memory API (JEP 442)?
This API provides a way for Java programs to interoperate with code and data outside of the Java runtime. It allows you to call native libraries (like C functions) and safely access memory that is not managed by the JVM. It is a safer and more robust replacement for the Java Native Interface (JNI).javainuse

25. What is the Vector API (JEP 448)?
The Vector API provides a way to express vector computations that can be reliably compiled at runtime to optimal vector instructions on supported CPU architectures. This can lead to significant performance improvements for applications involving complex mathematical or scientific calculations.geeksforgeeks

26. What enhancements were made to StringBuilder and StringBuffer?
Java 21 added the repeat method to StringBuilder and StringBuffer, allowing a character or sequence of characters to be appended multiple times in a more efficient and readable way than using a loop.geeksforgeeks

27. What improvements have been made to the HttpClient?
The HttpClient is now AutoCloseable, which means it can be used in a try-with-resources block for automatic resource management. It also introduces methods like shutdown() and close() for more graceful lifecycle management.geeksforgeeks

28. How does Java 21 support Emojis?
The java.lang.Character class has been updated with methods to work with emoji properties as defined by the Unicode standard, such as isEmoji() and isEmojiModifierBase().geeksforgeeks

Tech Lead and Architectural Questions

The following questions are designed to assess a candidate’s leadership, architectural thinking, and ability to apply new language features in a team context.

29. As a Tech Lead, how would you manage the migration of a large codebase from Java 17 to Java 21?
I would start with a pilot project to identify potential issues. Key steps would include updating the JDK, build tools (Maven/Gradle) and dependencies, and then running all existing tests. I’d encourage the team to start using new features like virtual threads and sequenced collections in new code, and to refactor old code where it makes sense, for example, replacing complex if-else chains with pattern matching for switch.

30. A developer on your team wants to replace all synchronized blocks with ReentrantLock to prepare for virtual threads. How would you advise them?
I would advise caution. While ReentrantLock is generally preferred when using virtual threads to avoid pinning, a blanket replacement is risky. I’d suggest a more targeted approach: first, identify the performance-critical sections of the application that would benefit most from virtual threads. Then, carefully refactor only those sections, ensuring that the change is backed by performance testing.

31. How would you explain the benefits of sealed classes to a junior developer?
I would use an analogy. Think of a sealed class like a club with a strict guest list. The club owner (the author of the sealed class) decides exactly who can come in (which classes can extend it). This prevents unexpected guests from showing up and causing problems, making the whole system more predictable and secure.

32. Your team is building a new high-throughput microservice that handles thousands of concurrent API requests. Would you recommend a reactive framework like Spring WebFlux or a traditional blocking framework with virtual threads? Justify your answer.
For a new service, I would strongly consider using a traditional blocking framework (like Spring MVC) with virtual threads. This approach allows developers to write simple, sequential-style code that is easy to read, write, and debug, while still achieving the high scalability of a non-blocking model. It avoids the learning curve and code complexity of reactive programming’s callback-based style, which can be a significant advantage for team productivity.

33. What are the security benefits of using the Foreign Function & Memory API over JNI?
The FFM API is designed to be safer than JNI. It provides a more structured and robust way to interact with native code, with better memory safety guarantees. This reduces the risk of memory leaks, buffer overflows, and other common vulnerabilities associated with native code integration.

34. When would you use a record vs. a regular class?
Use a record when the primary purpose of the class is to be a simple, immutable data carrier. Records are perfect for DTOs (Data Transfer Objects), messages, or any situation where you just need to hold a group of values. If the class needs to be mutable, have a complex lifecycle, or be part of a complex inheritance hierarchy, a regular class is more appropriate.

35. How can pattern matching for switch lead to more maintainable code?
It makes the code more expressive and less error-prone. By handling different data shapes and conditions in a single, clear construct, it reduces boilerplate and makes the intent of the code more obvious. When a new data shape is added (e.g., a new subclass of a sealed interface), the compiler can often warn you if you’ve forgotten to handle the new case in your switch statements, making refactoring safer.

(Questions 36-50 continue to explore these topics in more depth, with variations and scenario-based problems.)

36. How do record patterns and pattern matching for switch work together with sealed interfaces?
This combination is very powerful. A sealed interface restricts the possible implementations, and pattern matching for switch allows you to handle all of those implementations in an exhaustive and type-safe way. Record patterns can then be used to deconstruct the implementations if they are records. This creates highly readable and maintainable code for modeling and processing structured data.

37. Explain the “ABA problem” in the context of lock-free programming. Is it relevant to any of Java 21’s new features?
The ABA problem occurs in multithreaded environments when using compare-and-swap (CAS) operations. A location’s value could change from A to B and then back to A, leading a CAS operation to incorrectly assume nothing has changed. While not a new problem solved in Java 21, understanding it is crucial for a tech lead. The increased emphasis on concurrency with virtual threads means that a deep understanding of concurrent programming fundamentals, including the challenges of lock-free programming, is more important than ever.datacamp

38. What is the role of a ThreadFactory when creating virtual threads?
A ThreadFactory can be used to customize the creation of virtual threads, for example, by setting their name. The Thread.ofVirtual() method returns a builder that includes a factory() method for this purpose.

39. Can a virtual thread be “recycled”?
The term “recycled” can be misleading. A virtual thread is a lightweight object, and when its task is complete, it is garbage collected. The underlying OS thread (the “carrier” thread) is then free to run another virtual thread. So while the virtual thread itself is not recycled, the underlying carrier thread is.

40. Your application is experiencing performance issues under high load. How would you go about debugging potential thread-related bottlenecks, especially if you are using virtual threads?
I would use a profiler that has support for virtual threads to identify where time is being spent. I would look for signs of thread pinning (e.g., extensive use of synchronized blocks). JDK Flight Recorder (JFR) is an excellent tool for this, as it has been updated to provide detailed information about virtual threads, their state, and where they are mounted on carrier threads.

41. Describe how you could use a SequencedMap in a practical scenario.
A SequencedMap (like LinkedHashMap) would be useful for creating a cache with a defined eviction policy, such as Least Recently Used (LRU). The defined encounter order allows you to easily identify and remove the oldest entry when the cache is full.

42. How does the addFirst() and addLast() method family in SequencedCollection behave?
These methods add an element to the beginning or end of the collection, respectively. They are optional operations and might throw an UnsupportedOperationException if the collection is unmodifiable or has a fixed size.

43. Is it possible to use pattern matching on primitive types in a switch?
Yes, but it works slightly differently. You can use patterns that check for null or match against specific constant values. For more complex conditions on primitives, you would use a guarded pattern.

44. What are the performance implications of using string templates?
String templates are designed to be efficient. The processing of the template happens at compile time, and at runtime, they are generally as performant as, or in some cases more performant than, traditional string concatenation, especially when using template processors that can optimize the concatenation process.

45. How would you ensure that your team writes code that is “virtual-thread-friendly”?
I would establish clear coding guidelines. These would include favoring ReentrantLock over synchronized for locks that could be held over I/O operations, avoiding long-running CPU-bound tasks on virtual threads, and being mindful of thread-local variables, which can be problematic with a very large number of virtual threads. Scoped Values are the intended replacement for thread-locals in the age of virtual threads.

46. Can you have a record implement an interface?
Yes, a record can implement one or more interfaces. This is a common pattern, especially when using records as part of a sealed hierarchy.

47. What happens if you try to extend a sealed class with a class that is not in its permits list?
You will get a compile-time error. The compiler enforces the restriction that a sealed class can only be extended by the classes it explicitly permits.

48. How do virtual threads interact with Thread.sleep()?
When a virtual thread calls Thread.sleep(), it does not block the underlying carrier thread. The Java runtime simply schedules the virtual thread to be unmounted from its carrier and to be remounted after the sleep duration has passed. This is a key part of what makes virtual threads so scalable for I/O-bound workloads.

49. What is the purpose of the Java Enhancement Proposal (JEP) process?
The JEP process is the standard way of proposing and managing significant changes to the Java platform and JDK. It provides a clear, open, and structured process for introducing new features, ensuring that they are well-designed and reviewed by the community before being included in a release.javainuse

50. With the rapid pace of Java releases, how do you, as a Tech Lead, decide when to adopt a new LTS version like Java 21?
The decision is a balance between gaining the benefits of new features and managing the cost and risk of migration. For an LTS version like Java 21, the case for adoption is strong. I would evaluate the new features, particularly virtual threads and pattern matching, to see how they align with our application’s needs and our team’s goals. A successful pilot project and a clear business case (e.g., improved performance, faster development) would be key to making the final decision.

  1. https://www.geeksforgeeks.org/java/java-jdk-21-new-features-of-java-21/
  2. https://www.brilworks.com/blog/Java-21-features/
  3. https://dev.to/myexamcloud/java-21-pattern-matching-interview-questions-dp3
  4. https://javatechonline.com/guarded-pattern-in-java-21-switch-case/
  5. https://www.myexamcloud.com/blog/java-21-interview-questions.article
  6. https://dev.to/adrian_nowosielski_7bd282/sealed-classes-in-java-21-controlling-class-hierarchies-1moo
  7. https://www.codementor.io/@noelkamphoa/java-21-new-features-2k5fhm3vcq
  8. https://www.javainuse.com/interview/javavt
  9. https://www.theserverside.com/tip/A-primer-on-Java-21-virtual-threads-with-examples
  10. https://www.datacamp.com/blog/java-interview-questions
  11. https://www.baeldung.com/java-lts-21-new-features
  12. https://www.javainuse.com/interview/java21
  13. https://www.interviewbit.com/java-interview-questions/
  14. https://www.geeksforgeeks.org/java/java-interview-questions/
  15. https://www.edureka.co/blog/interview-questions/java-interview-questions/
  16. https://www.youtube.com/watch?v=EsBUD8nuVeE
  17. https://codefinity.com/blog/The-80-Top-Java-Interview-Questions-and-Answers
  18. https://www.simplilearn.com/java-interview-questions-article
  19. https://www.fullstackgurupune.com/blogs/top-21-java-interview-questions-with-answers
  20. https://www.youtube.com/watch?v=Z3h6T8-iQxk
  21. https://www.foundit.in/career-advice/java-interview-questions-and-answers-for-2-to-3-years-experience/
  22. https://withoutbook.com/InterviewQuestionList.php?tech=94&dl=Top&s=Java+21+interview+questions+and+answers
  23. https://www.besanttechnologies.com/java-interview-questions-answers
  24. https://www.javaguides.net/2024/06/java-21-interview-questions.html
  25. https://www.youtube.com/watch?v=lw-mlKqpLr0
  26. https://www.java-success.com/04-java-9-to-20-features-interview-qas-records/
  27. https://www.java-success.com/05-java-9-to-20-features-interview-qas-sealed-classes-interfaces/
  28. https://www.digitalocean.com/community/tutorials/java-programming-interview-questions
  29. https://stackoverflow.com/questions/28508361/pattern-matching-interview-q
  30. https://javatechonline.com/sealed-class-in-java/

Leave a comment

Recent posts

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby
Design a site like this with WordPress.com
Get started