Java has undergone several upgrades and improvements since version 6. Here are some of the major new features that were introduced in later versions of Java:
Java 7 (released in 2011):
- Diamond Operator for Type Inference in Generics
This operator simplifies the creation of generic objects by automatically inferring the type of arguments passed to a generic type.
Example:
1List<Integer> list = new ArrayList<>(); - Improved Type Inference for Generics
- String in switch Statement
With Java 7, you could use strings in the switch case statement, which was previously only possible with int, char or enum values.
Example:
1234567891011String day = "Monday";switch (day) {case "Monday":System.out.println("Today is Monday");break;case "Tuesday":System.out.println("Today is Tuesday");break;default:System.out.println("Today is not Monday or Tuesday");} - Numeric Literals with Underscores
1int number3 = 2_123_456; // break the digits with underscore - Binary Integer Literals with Prefix "0b"
12int number1 = 0b01010000101000101101000010100010;int number2 = 0b0101_0000_1010_0010_1101_0000_1010_0010; - Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
12345try {......} catch(ClassNotFoundException|SQLException ex) {ex.printStackTrace();} - Try-with-resources
This feature allows you to automatically close resources such as files, sockets or database connections.
Example:
12345try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {// read from file} catch (Exception e) {// handle exception}
Java 8 (released in 2014):
- Lambda Expressions
These allow you to write functional code, without creating an anonymous inner class.
Example:
12List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);numbers.forEach(n -> System.out.println(n)); -
Functional Interfaces and default methods
Java 8 introduced functional interfaces, which are interfaces with only one abstract method, and default methods, which allow you to add new methods to existing interfaces without breaking existing code.
Example:12345678@FunctionalInterfaceinterface Converter<F, T> {T convert(F from);default void print(F from) {System.out.println(from);}} - Method and Constructor References
- Stream API
This allows you to perform complex operations on collections in a more concise and efficient way.
Example:12345List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);numbers.stream().filter(n -> n % 2 == 0) // number is even?.map(n -> n * n) // Sqaure the even number.forEach(n -> System.out.println(n)); - Optional Class
Java introduced a new class Optional in Java 8. It is a public final class which is used to deal with NullPointerException in Java application. We must import java.util package to use this class. It provides methods to check the presence of value for particular variable. One could treat it as the wrapper class fornull
. - Date and Time API
Java has introduced a new Date and Time API since Java 8. The java.time package contains Java 8 Date and Time classes. - forEach()
Java provides a new method forEach() to iterate the elements. It is defined in Iterable and Stream interfaces.
It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach() method to iterate elements.
This method takes a single parameter which is a functional interface. So, you can pass lambda expression as an argument. - Nashorn JavaScript Engine
Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code.
You can execute JavaScript code by two ways:- Using jjs command-line tool, and
- By embedding into Java source code.
Java 9 (released in 2017):
- Factory Methods for Immutable List, Set, Map and Map.Entry
123List immutableList = List.of();List immutableList = List.of("one","two","three");Map nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three") - Module System
- JShell – The REPL for Java
JShell is an interactive command line tool that allows you to quickly test and run Java code snippets.
1234jshell> int x = 10x ==> 10jshell> System.out.println(x * x)100 - HTTP/2 Client
-
Private Interface Methods
Java 9 introduced the ability to add private methods to interfaces, which can be used to share common code between default methods.
Example:123456789interface Shape {default double area() {return calculateArea();}private double calculateArea() {// calculate area}} - Reactive Streams
Java SE 9 has introduced the following API to develop Reactive Streams in Java-based applications. - java.util.concurrent.Flow
- java.util.concurrent.Flow.Publisher
- java.util.concurrent.Flow.Subscriber
- java.util.concurrent.Flow.Processor
Java 10 (released in 2018):
- Local Variable Type Inference
- Parallel Full GC for G1
G1 garbage collector was made default in JDK 9. G1 Garbage collector avoids any full garbage collection, but when concurrent threads for collection cannot revive the memory fast enough users experience is impacted. This change improves the G1 worst-case latency by making the full GC parallel. The mark-sweep-compact algorithm from G1 collector is parallelized as part of this change and will be triggered when concurrent threads for collection can’t revive the memory fast enough. - Application Class-Data Sharing
Allows multiple Java applications running on the same machine to share a common archive of class metadata, improving the startup time and reducing the memory footprint of each application. This is achieved by creating a shared archive of the classes used by an application, which can then be loaded into the JVM at runtime using the -Xshare:on option. The shared archive can be created using the jlink tool, which collects the classes and resources used by the application and packages them into a single file. The result is a faster and more efficient startup time for Java applications and lower memory usage, as the JVM only needs to load the shared classes once, rather than multiple times for each application.
Java 11 (released in 2018):
- Launch Single-File Source-Code Programs
One major change is that you don’t need to compile the java source file with javac tool first. You can directly run the file with java command and it implicitly compiles. - HTTP Client (Standard)
Java 11 standardizes the Http CLient API. The new API supports both HTTP/1.1 and HTTP/2. It is designed to improve the overall performance of sending requests by a client and receiving responses from the server. It also natively supports WebSockets. - Enhanced Deprecation
- Raw String Literals
Java 12 (released in 2019):
-
Switch Expressions
-
Improved Out-Of-Memory Error Handling
-
JVM Constants API
Provides an API for creating, manipulating, and accessing various constant pool entities in class files, such as classes, methods, fields, strings, and others. The API is designed to support constant pool operations in both compiled and running code, and can be used to perform tasks such as bytecode instrumentation, dynamic class loading, and runtime constant pool access. The JVM Constants API is part of the java.lang.constant package, and provides a type-safe and efficient way to access constant pool information.
Here is an example of how you can use the JVM Constants API to access a constant value:123456//Accessing the constant pool of a classClass clazz = MyClass.class;ConstantPool constantPool = clazz.getConstantPool();//Accessing a constant value from the constant poolObject value = constantPool.getValue(3);System.out.println("Value at index 3: " + value); -
Epsilon: A No-Op Garbage Collector
Java 13 (released in 2019):
- Text Blocks
allows developers to write multi-line string literals in a more convenient and readable way. With Text Blocks, you can define string literals that span multiple lines of text, without the need to escape newline characters or concatenate separate strings. The feature is particularly useful for large string literals, such as JSON payloads or HTML templates, that can become difficult to read and maintain in a single-line format.
For example, consider the following code that defines a multi-line string literal in Java 12 and earlier:
1 2 3 4 5 |
String html = "<html>\n" + " <body>\n" + " <h1>Hello, World!</h1>\n" + " </body>\n" + "</html>"; |
With the Text Blocks feature in Java 13, you can simplify the definition of the string literal as follows:
1 2 3 4 5 6 7 |
String html = """ <html> <body> <h1>Hello, World!</h1> </body> </html> """; |
As you can see, Text Blocks make it easier to read and write multi-line string literals in Java, while preserving the original line breaks and indentation.
- Dynamic CDS Archives
- ZGC: A Scalable Low-Latency Garbage Collector
- Reimplement the Legacy Socket API
Java 14 (released in 2020):
- Pattern Matching for instanceof
- Records (Preview language feature)
They are a compact and concise way to define an immutable data structure in Java. A record can contain fields, methods, and constructors like a class, but they are automatically generated based on the record’s state. Records are intended to replace traditional data classes that only contain private fields, getters, and constructors. The key advantage of records is that they simplify the code by removing boilerplate code and promoting code reusability. An example of a record in Java 14 could be:
1record Person(String name, int age) {}This record defines a person with a name and an age. The record automatically generates a constructor, getters for the fields, and a toString method that represents the state of the record.
- Switch Expressions Enhancements
- NUMA-Aware Memory Allocation for G1