Power of Java 21! 🚀

Ankit Dabhi
3 min readMay 29, 2023

Prepare for some incredible changes, Java 20 has laid the groundwork for revolutionary improvements, and now it’s time to unveil what Java 21 has in store for us. Let’s explore the key updates to look forward to:

Faster Startup Times: Java 21 introduces enhanced startup optimizations, enabling quicker application launches and delivering a seamless user experience. Bid farewell to long waiting times and welcome improved efficiency!

Pattern Matching Enhancements: Pattern matching, a feature introduced in Java 14, takes another leap forward in Java 21. It now includes additional syntax improvements, making code more concise and readable. This enhancement undoubtedly boosts developer productivity and code quality. For example:

System.out.println("Marks: " + ((obj instanceof Student s) ? s.getMarks() : ""));

Enhanced Switch Expressions: Building upon the success of switch expressions in Java 14, Java 21 expands its capabilities further. The new update allows for more flexible and expressive patterns within switch expressions, simplifying complex conditional logic. For example:

int result = 
switch (day)
{
case "Monday" -> 1;
case "Tuesday" -> 2;
case "Wednesday", "Thursday" -> 3;
case "Friday" -> 4;
default -> throw new IllegalArgumentException("Invalid day");
};

Records and Immutability: Records, introduced in Java 16, provide a concise way to define immutable data classes. In Java 21, records become even better! This update enhances the existing records feature, making it easier to work with immutable data and improving overall code maintainability. For example:

public record Person(String name, int age) 
{
// Record fields and constructor automatically generated // Additional methods like equals(), hashCode(), and toString() are also provided
}

Sealed Classes Enhancements: Sealed classes, introduced in Java 15, offer more control over class hierarchies. Java 21 refines this feature by introducing additional flexibility, allowing developers to customize and fine-tune their sealed class hierarchies to meet specific application requirements. For example:

public sealed class Shape permits Circle, Rectangle, Triangle 
{
// Sealed class definition // Subclasses Circle, Rectangle, and Triangle are explicitly mentioned with 'permits'
}

Improved Garbage Collection: Java 21 brings forth enhanced garbage collection algorithms, resulting in improved performance and reduced memory footprint for applications. Developers can expect better overall efficiency and resource management, leading to optimized application behaviour.

Virtual Threads: Lightweight threads that dramatically reduce the effort of writing, maintaining, and observing high-throughput concurrent applications on the Java platform.

Virtual threads offer a more efficient alternative to platform threads, allowing developers to handle numerous tasks with significantly lower overhead. These threads offer compatibility with existing Java code and a seamless migration path to benefit from enhanced performance and resource utilization. Consider the following example:

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
}

Unnamed Classes and Instance Main Methods (Preview): Consider the classic Hello, World! The program that is often used as the first program for Java students:

public class HelloWorld { 
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

So, there is too much clutter here — too much code, too many concepts, too many constructs. But now allow instance main methods. Such methods are not static, need not be public, and need not have a String[] parameter. Then we can simplify the Hello, World! program to:

class HelloWorld { 
void main() {
System.out.println("Hello, World!");
}
}

Second, introduce unnamed classes to make the class declaration implicit:

void main() {
System.out.println("Hello, World!");
}

For more details

Follow me for more updates related to Java, AWS, Spring boot, Microservices, and System Design.

“Love my work? Buy me a coffee and keep the creativity flowing!” ☕️🎉

Follow me on LinkedIn: https://bit.ly/43bq2Vv

--

--

Ankit Dabhi

Sr. SE with MS in Computer Science. Writing about Java, Spring, SE in emerging tech. I write code for fun!. Connect with me : https://tinyurl.com/2nfsyy26