Java New Features Overview
Since Java 8, Java's release cycle has accelerated, bringing a wealth of new features designed to improve productivity, code readability, and performance. This chapter provides an overview of important new features from Java 8 to Java 21.
Java 8 (2014)
Java 8 was a milestone update that introduced the concept of functional programming.
1. Lambda Expressions
Lambda expressions provide a concise way to represent anonymous functions, greatly simplifying the writing of code for event listeners, threads, and more.
// Old way
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from old Thread!");
}
}).start();
// Using Lambda
new Thread(() -> System.out.println("Hello from Lambda Thread!")).start();2. Stream API
The Stream API provides a declarative, functional way to process collection data. It allows you to write more concise, readable data processing pipelines and easily implement parallel processing.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Find all names starting with 'A', convert to uppercase, and print
names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);3. Optional Class
Optional is a container object that may or may not contain a non-null value. It is designed to address the NullPointerException (NPE) problem, encouraging developers to explicitly handle potentially null cases.
4. Default and Static Methods in Interfaces
Interfaces can now contain default methods with implementations, making it possible to add new functionality to interfaces without breaking existing implementing classes.
Java 10 (2018)
Local Variable Type Inference (var)
Using the var keyword, you can let the compiler automatically infer the type of local variables, reducing boilerplate code.
// Old way
Map<String, List<Integer>> myMap = new HashMap<>();
// Using var
var myMap = new HashMap<String, List<Integer>>();Java 11 (2018) - Long-Term Support (LTS)
New String Methods
The String class gained useful new methods such as isBlank(), lines(), strip(), repeat().
Standardized HTTP Client
A brand-new, modern java.net.http.HttpClient API was introduced to replace the old HttpURLConnection, supporting HTTP/2 and asynchronous operations.
Java 14 (2020)
switch Expressions
Enhanced switch statements to allow them to return values as expressions, introducing the more concise -> syntax without needing break.
Day day = Day.MONDAY;
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};Records
Record is a special kind of class used to create immutable data carriers. The compiler automatically generates constructors, equals(), hashCode(), toString(), and accessor methods for all fields for a record.
// Just one line of code
public record Point(int x, int y) {}
// Equivalent to a regular class with x, y fields, constructor, getters, equals/hashCode/toString
Point p = new Point(1, 2);
p.x(); // Accessor methodJava 17 (2021) - Long-Term Support (LTS)
Sealed Classes
Sealed classes and interfaces can restrict which other classes or interfaces can extend or implement them. This provides library designers with stronger control and makes pattern matching in switch more powerful.
// Shape class only allows Circle and Rectangle to extend it
public abstract sealed class Shape permits Circle, Rectangle {
// ...
}
public final class Circle extends Shape { /*...*/ }
public final class Rectangle extends Shape { /*...*/ }
// class Triangle extends Shape {} // Compile error!Enhanced Pattern Matching
- Pattern Matching for
instanceof: Ifinstanceofevaluates to true, you can directly declare a binding variable without needing to cast again.javaObject obj = "hello"; if (obj instanceof String s) { // s can be used directly as a String here System.out.println(s.toUpperCase()); } - Pattern Matching for
switch(Preview Feature):switchcan directly match on the type of an object.
Java 21 (2023) - Long-Term Support (LTS)
Virtual Threads
Virtual threads are the core result of Project Loom. They are a lightweight thread implementation designed to significantly simplify the writing, maintenance, and observation of high-throughput concurrent applications. Thousands or even millions of virtual threads can be managed by a small number of platform threads, greatly reducing the complexity and resource consumption of concurrent programming.
Sequenced Collections
A series of new interfaces were introduced to provide collections with a uniform, well-defined traversal order and standard methods for accessing the first and last elements.
String Templates (Preview Feature)
Provides a safer, more powerful way to construct strings containing runtime values, serving as a modern alternative to traditional string concatenation and formatting.