Java 9
Java 9
New Features
There are 90+ enhancements added to Java 8, the most significant ones are
mentioned below −
Module − A new kind of Java programing component introduced as module, which is a
named, self-describing collection of code and data.
REPL (JShell) − Read-Eval-Print Loop (REPL) capability added to the Java platform.
HTTP 2 Client − new HTTPClient API supporting websockets and HTTP 2 streams and
server push features.
Improved JavaDocs − Supports HTML5 output generation. Provides a search box to
generated API documentation.
Multirelease JAR − Enhances the JAR format so that multiple, Java release-specific
versions of class files can coexist in a single archive.
Collection Factory Methods − New static factory methods for List, Set, and Map
interfaces to create immutable instances of those collections.
Private Interface Methods − Enhanced interfaces with private and private static
methods.
Process API Improvements − Improved API to control and manage operating system
processes.
Stream API Improvements − Enhanced security and robustness by allowing incoming
streams of object-serialization data to be filtered.
Try With Resources improvement − Now final variables can be used as resources in
the try-with-resources statement.
Enhanced @Deprecated Annotation − @Deprecated annotation revamped to provide
more information about the status and intended disposition of an API.
Inner Class Diamond Operator − Allow the diamond operator to be used with
anonymous classes if the argument type of the inferred type can be denoted.
Optional Class Improvements − New useful methods are added to java.util.Optional
class.
Multiresolution Image API − Supports encapsulation of a set of images with different
resolutions into a single multiresolution image.
CompletableFuture API improvements − The asynchronous mechanisms of the
CompletableFuture class can perform an action when the process exits with
ProcessHandle.onExit method.
Lightweight JSON − A lightweight API introduced to consume and generating
documents and data streams via json in java 9.
Reactive Streams API − A new Reactive Streams API in Java SE 9 has been
introduced to support reactive programming in java 9.
Environment variable PATH should be set to point to where the Java binaries have
been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at
the end of your .bashrc −
export PATH = /path/to/java:$PATH'
Features
With the Modules component, following enhancements has been added in Java 9 −
A new optional phase,link time, is introduced. This phase is in-between compile time and
run time. During this phase, a set of modules can be assembled and optimized, making
a custom runtime image using jlink tool.
javac, jlink, and java have additional options to specify module paths, which further
locate definitions of modules.
JAR format updated as modular JAR, which contains module-info.class file in its root
directory.
JMOD format introduced, a packaging format (similar to JAR) which can include native
code and configuration files.
Creating Module
Following the steps to create a module say com.tutorialspoint.greetings.
Step 1
Step 3
By convention, the source code of a module to lie in same directory which is the
name of the module.
Step 4
src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/Jav
a9Tester.java
Step 5
Let's run the module to see the result. Run the following command.
C:/ > JAVA > java --module-path mods -m
com.tutorialspoint.greetings/com.tutorialspoint.greetings.Java9Te
ster
Here module-path provides the module location as mods and -m signifies the main
module.
Output
It will print the following output on console.
Hello World!
Running JShell
Open command prompt and type jshell.
$ jshell
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell>
Exiting JShell
Type /exit.
jshell> /exit
| Goodbye
Tester.java
Live Demo
/**
* @author MahKumar
* @version 0.1
*/
public class Tester {
/**
* Default method to be run to print
* <p>Hello world</p>
* @param args command line arguments
*/
public static void main(String []args) {
System.out.println("Hello World");
}
}
Steps
Step 1 − Create a folder c:/test/java7/com/tutorialspoint. Create Test.java with
following content −
Tester.java
Live Demo
package com.tutorialspoint;
Tester.java
Live Demo
package com.tutorialspoint;
list.add("A");
list.add("B");
list.add("C");
list = Collections.unmodifiableList(list);
System.out.println(list);
Map<String, String> map = new HashMap<>();
map.put("A","Apple");
map.put("B","Boy");
map.put("C","Cat");
map = Collections.unmodifiableMap(map);
System.out.println(map);
}
}
Output
It will print the following output.
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
New Methods
With java 9, following methods are added to List, Set and Map interfaces along with
their overloaded counterparts.
static <E> List<E> of(E e1, E e2, E e3);
static <E> Set<E> of(E e1, E e2, E e3);
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3);
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends
V>... entries)
Points to Note
For List and Set interfaces, of(...) method is overloaded to have 0 to 10 parameters and
one with var args parameter.
For Map interface, of(...) method is overloaded to have 0 to 10 parameters.
In case of more than 10 paramters for Map interface, ofEntries(...) method can be used
accepting var args parameter.
Output
It will print the following output.
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
{A=Apple, B=Boy, C=Cat}
Java 9 - Private Interface Methods
Prior to java 8, interfaces can have following type of variables/methods.
Constant variables
Abstract methods
So we cannot have method implementation in interfaces or more precisely a default
implementation prior to Java 8. See the example.
Live Demo
public class Tester {
public static void main(String []args) {
LogOracle log = new LogOracle();
log.logInfo("");
log.logWarn("");
log.logError("");
log.logFatal("");
LogMySql log1 = new LogMySql();
log1.logInfo("");
log1.logWarn("");
log1.logError("");
log1.logFatal("");
}
}
@Override
public void logWarn(String message) {
getConnection();
System.out.println("Log Message : " + "WARN");
closeConnection();
}
@Override
public void logError(String message) {
getConnection();
System.out.println("Log Message : " + "ERROR");
closeConnection();
}
@Override
public void logFatal(String message) {
getConnection();
System.out.println("Log Message : " + "FATAL");
closeConnection();
}
@Override
public void getConnection() {
System.out.println("Open Database connection");
}
@Override
public void closeConnection() {
System.out.println("Close Database connection");
}
}
@Override
public void logWarn(String message) {
getConnection();
System.out.println("Log Message : " + "WARN");
closeConnection();
}
@Override
public void logError(String message) {
getConnection();
System.out.println("Log Message : " + "ERROR");
closeConnection();
}
@Override
public void logFatal(String message) {
getConnection();
System.out.println("Log Message : " + "FATAL");
closeConnection();
}
@Override
public void getConnection() {
System.out.println("Open Database connection");
}
@Override
public void closeConnection() {
System.out.println("Close Database connection");
}
}
interface Logging {
String ORACLE = "Oracle_Database";
String MYSQL = "MySql_Database";
void getConnection();
void closeConnection();
}
Output
You will see the following output.
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
In above example, each log method has its own implementation. With Java 8
interfaces can have following type of variables/methods.
Constant variables
Abstract methods
Default methods
Static methods
Let's have default implementation and static methods in interface itself using Java
8.
Live Demo
public class Tester {
public static void main(String []args) {
LogOracle log = new LogOracle();
log.logInfo("");
log.logWarn("");
log.logError("");
log.logFatal("");
LogMySql log1 = new LogMySql();
log1.logInfo("");
log1.logWarn("");
log1.logError("");
log1.logFatal("");
}
}
interface Logging {
String ORACLE = "Oracle_Database";
String MYSQL = "MySql_Database";
Output
You will see the following output.
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
In above example, we're having repeation again. With Java 9 interfaces can have
following type of variables/methods.
Constant variables
Abstract methods
Default methods
Static methods
Private methods
Private Static methods
Let's have private methods and use them in Java 9.
public class Tester {
public static void main(String []args) {
LogOracle log = new LogOracle();
log.logInfo("");
log.logWarn("");
log.logError("");
log.logFatal("");
LogMySql log1 = new LogMySql();
log1.logInfo("");
log1.logWarn("");
log1.logError("");
log1.logFatal("");
}
}
interface Logging {
String ORACLE = "Oracle_Database";
String MYSQL = "MySql_Database";
Output
You will see the following output.
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
Tester.java
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;
System.out.printf("Arguments : %s%n",
info.arguments().map(a -> Stream.of(a).collect(
Collectors.joining(" "))).orElse(np));
Output
You will see the following output.
Process ID : 5800
Command name : C:\Windows\System32\notepad.exe
Command line : Not Present
Start time: 2017-11-04T21:35:03.626
Arguments : Not Present
User: administrator
takeWhile method takes all the values until the predicate returns false. It returns, in
case of ordered stream, a stream consisting of the longest prefix of elements taken
from this stream matching the given predicate.
Example
import java.util.stream.Stream;
Output
takeWhile method takes all a, b, and c values, then once string is empty, it stopped
executing.
abc
dropWhile(Predicate Interface)
Syntax
default Stream<T> dropWhile(Predicate<? super T> predicate)
dropWhile method throw away all the values at the start until the predicate returns
true. It returns, in case of ordered stream, a stream consisting of the remaining
elements of this stream after dropping the longest prefix of elements matching the
given predicate.
Example
import java.util.stream.Stream;
Output
dropWhile method drops a,b and c values, then once string is empty, it takes all the
values.
ef
ef
iterate
Syntax
iterate method now has hasNext predicate as parameter which stops the loop once
hasNext predicate returns false.
Example
import java.util.stream.IntStream;
Output
3
6
9
ofNullable
Syntax
import java.util.stream.Stream;
count = Stream.ofNullable(null).count();
System.out.println(count);
}
}
Output
1
0
Tester.java
Live Demo
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
Output
test
Here we need to declare a resource br1 within try statment and then use it. In
Java9, we don't need to declare br1 anymore and following program will give the
same result.
Tester.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
Output
test
Tester.java
Live Demo
public class Tester {
public static void main(String[] args) {
Handler<Integer> intHandler = new Handler<Integer>(1) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler.handle();
Handler<? extends Number> intHandler1 = new
Handler<Number>(2) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler1.handle();
Handler<?> handler = new Handler<Object>("test") {
@Override
public void handle() {
System.out.println(content);
}
};
handler.handle();
}
}
Output
1
2
Test
With Java 9, we can use <> operator with anonymous class as well as shown
below.
Tester.java
public class Tester {
public static void main(String[] args) {
Handler<Integer> intHandler = new Handler<>(1) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler.handle();
Handler<? extends Number> intHandler1 = new Handler<>(2) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler1.handle();
Handler<?> handler = new Handler<>("test") {
@Override
public void handle() {
System.out.println(content);
}
};
handler.handle();
}
}
Output
1
2
Test
stream()
ifPresentOrElse()
or()
stream() method
Syntax
public Stream<T> stream()
If a value is present, it returns a sequential Stream containing only that value,
otherwise returns an empty Stream.
Example
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
System.out.println(filteredList);
System.out.println(filteredListJava9);
}
}
Output
[A, B]
[A, B]
ifPresentOrElse() method
Syntax
public void ifPresentOrElse(Consumer<? super T> action, Runnable
emptyAction)
If a value is present, performs the given action with the value, otherwise performs
the given empty-based action.
Example
import java.util.Optional;
optional = Optional.empty();
Output
Value: 1
Not Present.
or() method
Syntax
public Optional<T> or(Supplier<? extends Optional<? extends T>>
supplier)
If a value is present, returns an Optional describing the value, otherwise returns an
Optional produced by the supplying function.
Example
import java.util.Optional;
import java.util.function.Supplier;
optional1 = Optional.empty();
Output
Value: Mahesh
Value: Not Present
Example
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.awt.Image;
import java.awt.image.MultiResolutionImage;
import java.awt.image.BaseMultiResolutionImage;
import javax.imageio.ImageIO;
List<String> imgUrls =
List.of("http://www.tutorialspoint.com/java9/images/logo.png",
"http://www.tutorialspoint.com/java9/images/mini_logo.png",
"http://www.tutorialspoint.com/java9/images/large_logo.png");
Image variant3 =
multiResolutionImage.getResolutionVariant(622, 178);
System.out.printf("\nImage for destination[%d,%d]: [%d,
%d]", 622, 178,
variant3.getWidth(null), variant3.getHeight(null));
Image variant4 =
multiResolutionImage.getResolutionVariant(300, 300);
System.out.printf("\nImage for destination[%d,%d]: [%d,
%d]", 300, 300,
variant4.getWidth(null), variant4.getHeight(null));
}
}
Output
Total number of images: 3
BufferedImage@7ce6a65d: type = 6 ColorModel: #pixelBits = 32
numComponents = 4
color space =java.awt.color.ICC_ColorSpace@548ad73b transparency
= 3
has alpha = true isAlphaPre = false ByteInterleavedRaster: width
=311
height = 89 #numDataElements 4 dataOff[0] = 3
This method completes this CompletableFuture with the given value if not otherwise
completed before the given timeout.
public CompletableFuture<T> orTimeout(long timeout, TimeUnit
unit)
It returns the default Executor used for async methods that do not specify an
Executor. This method may be overridden in subclasses to return an Executor to
provide one independent thread as minimum.
public <U> CompletableFuture<U> newIncompleteFuture()