Java 8 vs Java 21
1. What is the difference between Java 8 and Java 21 regarding the feature set and performance?
Java 8 (released in March 2014) introduced several fundamental features that revolutionized Java programming, including:
- Lambda Expressions: Introduced functional programming features that allowed you to treat functions as first-class citizens and pass them as parameters.
- Streams API: Enabled declarative processing of sequences of elements, making it easier to work with collections.
- Default Methods in Interfaces: Allowed interfaces to have methods with implementations.
- New Date and Time API (java.time): Replaced the old
java.util.Dateandjava.util.Calendarclasses with a more comprehensive and modern date-time API.
Java 21 (released in September 2023) builds on the foundation laid by Java 8 and introduces significant new features to improve language expressiveness, performance, and developer productivity. Some of the key advancements in Java 21 include:
- Virtual Threads (JEP 433): Lightweight threads that significantly improve concurrency by allowing the handling of millions of threads efficiently, reducing the overhead of traditional platform threads.
- Pattern Matching (JEP 405): Enhances the language’s ability to work with patterns in conditionals, making code more concise and readable.
- Record Patterns (JEP 405): Introduces pattern matching specifically for records, making it easier to work with immutable data types.
- Foreign Function & Memory API (JEP 424): Provides a safer and more efficient way to interact with non-Java code and native memory.
- String Templates (JEP 427): Simplifies string concatenation by embedding expressions directly within string literals.
- Structured Concurrency (JEP 442): Helps manage multi-threaded programming in a simpler and more structured way, reducing errors related to thread management.
In terms of performance, Java 21 also brings improvements:
- JIT Optimizations: Enhanced Just-In-Time compilation for better runtime performance.
- Garbage Collection (GC): Improved garbage collection algorithms for better memory management and lower latency.
- Virtual Threads: Because virtual threads are lightweight, they improve the scalability of multi-threaded applications without significantly increasing memory usage.
2. How does pattern matching in Java 21 differ from earlier versions, and what are its advantages?
Pattern Matching in Java was introduced in Java 16 and evolved further in Java 21. Here’s how it differs and improves in Java 21:
- Java 16 and Java 17: Introduced basic pattern matching for the
instanceofoperator, allowing you to match types and automatically cast the object to the desired type in a single expression:
if (obj instanceof String s) { // s is automatically cast to String }- Java 21 (JEP 405): Expanded pattern matching to include more complex patterns, particularly for records, and support for switch expressions. It introduces record patterns, which allow deconstructing records more easily:
record Person(String name, int age) {}
// Pattern matching with records
if (obj instanceof Person(String name, int age)) {
System.out.println(name + " is " + age + " years old");
}Advantages of Pattern Matching:
- Concise Code: Eliminates boilerplate code related to type casting and matching.
- Improved Readability: Makes your code easier to read and understand by reducing the need for explicit type checks and casts.
- Error Reduction: Reduces the chance of
ClassCastExceptionsince type casting is handled automatically when the pattern matches.
3. What is Sealed Classes in Java 21, and how are they used to enhance type safety?
Sealed Classes (introduced in Java 15 and further enhanced in Java 21) allow you to define a restricted class hierarchy. This means that you can control which other classes or interfaces can extend or implement a particular class or interface.
- Sealed Classes: The class is marked with the
sealedkeyword and only allows certain classes to extend it. - Permitted Subclasses: You specify which classes can extend a sealed class by using the
permitskeyword.
Example:
public sealed class Shape permits Circle, Square { }
public final class Circle extends Shape { }
public final class Square extends Shape { }How Sealed Classes Enhance Type Safety:
- Controlled Inheritance: By restricting which classes can extend a base class, you can ensure that only certain, trusted subclasses can be used. This makes the class hierarchy easier to reason about.
- Exhaustive Pattern Matching: With sealed classes, you can be sure that all subclasses are known and handled. This enables safer and more exhaustive pattern matching, ensuring that you don’t accidentally miss handling any subclass.
Example of pattern matching with sealed classes:
public void processShape(Shape shape) {
switch (shape) {
case Circle c -> System.out.println("Circle: " + c);
case Square s -> System.out.println("Square: " + s);
}
}4. Can you explain JEP 433: Virtual Threads (Preview) introduced in Java 21?
JEP 433 introduces virtual threads as a preview feature in Java 21. Virtual threads are lightweight, user-mode threads that enable handling millions of concurrent threads without the performance overhead of traditional platform threads (which are typically managed by the operating system).
Get Alice Dai’s stories in your inbox
Join Medium for free to get updates from this writer.
Key features of virtual threads:
- Lightweight: Virtual threads are much cheaper to create and manage compared to traditional threads, allowing you to scale applications that need to handle thousands or even millions of concurrent tasks.
- Simplified Concurrency: Virtual threads allow you to use a more natural thread-based programming model while maintaining high concurrency, avoiding the complexities of other concurrency models (like callbacks or event loops).
- Integration with Existing APIs: Virtual threads integrate seamlessly with existing Java concurrency APIs like
ExecutorService, so you don't need to change much of your existing code to benefit from them.
Example of creating virtual threads:
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
executor.submit(() -> {
// Task code here
});5. How has garbage collection improved in Java 21 compared to previous versions?
Java 21 introduces improvements to garbage collection (GC) that focus on enhancing memory management and reducing latency. Some key improvements include:
- Improved Low-Latency Garbage Collection: Java 21 continues to enhance the ZGC (Z Garbage Collector) and Shenandoah GC, both of which are designed to minimize pause times for large heap sizes. This is beneficial for low-latency applications.
- Memory Management Efficiency: Java 21 includes optimizations to GC algorithms that result in better memory utilization and reduced overhead. This is especially important for applications with large amounts of data or high concurrency.
- G1 Garbage Collector Enhancements: The G1 GC, which balances throughput and pause-time goals, has also received tuning for more predictable and faster performance in Java 21.
In general, Java 21’s GC improvements reduce pauses and improve the performance of long-running applications by efficiently reclaiming memory.





