Here’s a list of key features from Java 8 to Java 17 along with code examples for each feature.
Java 8 (March 2014)
- Lambda Expressions
Lambda expressions enable you to pass behavior as parameters and implement functional interfaces concisely.
// Lambda expression for a functional interface
interface MathOperation {
int operate(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
MathOperation add = (a, b) -> a + b;
System.out.println(add.operate(5, 3)); // Output: 8
}
}
- Streams API
The Streams API enables functional-style operations on collections.
import java.util.*;
import java.util.stream.*;
public class StreamsExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Tom", "Jack");
names.stream().filter(name -> name.startsWith("J")).forEach(System.out::println);
// Output: John, Jane, Jack
}
}
- Default Methods in Interfaces
Interfaces can have default methods with implementation.
interface Greeting {
default void sayHello() {
System.out.println("Hello!");
}
}
public class DefaultMethodExample implements Greeting {
public static void main(String[] args) {
new DefaultMethodExample().sayHello(); // Output: Hello!
}
}
- New Date and Time API (
java.time
)
The new Date-Time API provides immutable and thread-safe classes.
import java.time.*;
public class DateTimeExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(today); // Output: current date
}
}
- Optional Class
A container object to avoidNullPointerException
.
import java.util.*;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Unknown")); // Output: Unknown
}
}
Java 9 (September 2017)
- Module System (Project Jigsaw)
Introduced modules for better code organization and dependency management.
// In module-info.java
module com.example {
requires java.base;
}
- JShell (Java REPL)
A REPL for Java that allows you to execute code interactively.
jshell> System.out.println("Hello, JShell!");
Hello, JShell!
- Private Methods in Interfaces
Interfaces can have private methods for internal use.
interface MyInterface {
private void helper() {
System.out.println("Helper Method");
}
default void execute() {
helper();
}
}
public class PrivateMethodExample implements MyInterface {
public static void main(String[] args) {
new PrivateMethodExample().execute(); // Output: Helper Method
}
}
Java 10 (March 2018)
- Local Variable Type Inference (
var
)
Thevar
keyword allows type inference for local variables.
public class VarExample {
public static void main(String[] args) {
var name = "Java 10"; // Type inferred as String
System.out.println(name); // Output: Java 10
}
}
- ZGC (Low-Latency Garbage Collector)
ZGC is a low-latency garbage collector, experimental in Java 10.
java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC MyApp
- Application Class-Data Sharing
Speeds up the startup time by sharing class metadata across Java processes.
java -Xshare:off MyApp
Java 11 (September 2018)
- Long-Term Support (LTS)
Java 11 is an LTS release, meaning it receives extended support. - Removed Java EE and CORBA Modules
Deprecated Java EE and CORBA modules were removed. - HTTP Client API
A new standardHTTP Client
API for synchronous and asynchronous HTTP requests.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://www.example.com"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
- New String Methods
New methods likeisBlank()
,lines()
,strip()
, etc.
public class StringMethodsExample {
public static void main(String[] args) {
String text = " Java 11 ";
System.out.println(text.isBlank()); // Output: false
System.out.println(text.strip()); // Output: "Java 11"
}
}
Java 12 (March 2019)
- Shenandoah Garbage Collector (Production)
A low-latency garbage collector in production mode.
java -XX:+UseShenandoahGC MyApp
- JVM Constants API
A new API for managing JVM constants.
// Example with JVM Constants API (requires deeper understanding of the JEP)
Java 13 (September 2019)
- Text Blocks (Preview)
Multi-line string literals for easier handling of structured data.
public class TextBlocksExample {
public static void main(String[] args) {
String json = """
{
"name": "John",
"age": 30
}
""";
System.out.println(json);
}
}
- ZGC (Production)
Z Garbage Collector made production-ready.
Java 14 (March 2020)
- Helpful NullPointerExceptions
Provides detailedNullPointerException
messages.
public class NPEExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Detailed message: Cannot invoke "String.length()" because "str" is null
}
}
- Text Blocks (Standard)
Text blocks became a fully standard feature. - Pattern Matching for
instanceof
(Preview)
Simplifies theinstanceof
check.
public class PatternMatchingExample {
public static void main(String[] args) {
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.toUpperCase()); // Output: HELLO
}
}
}
Java 15 (September 2020)
- Sealed Classes (Preview)
Allows you to restrict which other classes or interfaces can extend or implement them.
public sealed class Shape permits Circle, Square { }
public final class Circle extends Shape { }
public final class Square extends Shape { }
- Hidden Classes
Classes that are not discoverable via reflection.
// Example for Hidden Classes requires JVM bytecode manipulation, often used in frameworks like Hibernate
Java 16 (March 2021)
- Records (Preview)
Simplifies the creation of immutable data-carrying classes.
public record Person(String name, int age) { }
public class RecordExample {
public static void main(String[] args) {
Person p = new Person("John", 25);
System.out.println(p.name()); // Output: John
}
}
- Pattern Matching (Preview)
Expanded pattern matching capabilities.
public class PatternMatchingExample {
public static void main(String[] args) {
Object obj = 100;
if (obj instanceof Integer i) {
System.out.println(i * 2); // Output: 200
}
}
}
Java 17 (September 2021)
- Long-Term Support (LTS)
Java 17 is an LTS release with extended support. - Sealed Classes (Standard)
Sealed classes were finalized as a standard feature. - Enhanced Pseudo-Random Number Generators
Introduced new interfaces for random number generation.
import java.util.random.*;
public class RandomExample {
public static void main(String[] args) {
RandomGenerator generator = RandomGenerator.of("L64X128MixRandom");
System.out.println(generator.nextInt());
// Output: Random integer
}
}
This gives a concise overview of key features from Java 8 to Java 17 with corresponding code examples. Each version brought significant improvements, focusing on functional programming, performance, and modernizing Java for newer use cases.