

This article contains Java 9 features with examples. After 2014 we are waiting for Java 9, Now Java 9 comes with so many important and interesting features with us. Java 9 features are described in bellow with examples. Some of important Java 9 features modules system, Jshell, very useful features with Stream, private methods in the interface, try-cache resource handling, provide so many important tools which make our development easy and fast.
Another thing I like to share with you is that, Java 9 features will change the way of Java application development using its Jigsaw module system. Java 9 also provide some important and useful features for application development.
Table of Contents
- Java 9 Features
- 1. Project Jigsaw (Module System)
- 2. “public” no longer means “accessible”
- 3. JShell (Real Eval Print Loop)
- 4. Private methods in Interface
- 5. Process API Improvements
- 6. Immutable Static Factory Methods for Set, List and Map
- 7. Effectively final variables in try-with-resource
- 8. Logging API
- 9. Javac with –version option
- 10. New methods on @Deprecation
- 11. Tool to check deprecated resources.
- 12. No longer allowed underscore as an identifier.
- 13. HTML 5 Docs
- 14. Javadoc Search
- 15. Version String Format
- 16. Linker Tool
- 17. Stream Enhancements
- 18. UTF-8 properties files
- 19. New Static method in Thread: Thread.onSpinWait()
- 20. SHA 3 hash algorithm
- 21. Java.util.Objects Static method requireNonNullElse
- Was this post helpful?
Java 9 Features
1. Project Jigsaw (Module System)
Project Jigsaw is design for module system of Java development. Now Java divided into multiple modules and module may depends on another modules using module system. Here is Java 9 feature module system example:
module-info.java
module javadeveloperzone.base{ }
Student.java
package com.javadeveloperzone; public class Student{ public int no; public String name; public Student(int no,String name){ this.no=no; this.name=name; } public String getName(){ return this.name; } }
Demo.java
package com.javadeveloperzone; import com.javadeveloperzone.Student; public class Demo{ public static void main(String ... args){ System.out.println("Niceee... weldone... welcome to your first module program.."); Student student= new Student(1,"JavaDeveloperZone"); System.out.println(student.getName()); } }
Command To Run module
echo "Compiling Class files of module" javac -d output/classes base/com/javadeveloperzone/*.java javac -d output/classes base/Module-info.java echo "Creating Jar of module" jar -c -f output/mlib/javadeveloperzone.base.jar -C output/classes . echo "Running javadeveloperzone.base module..." java --module-path output/mlib -m javadeveloperzone.base/com.javadeveloperzone.Demo
2. “public” no longer means “accessible”
Java 9 scope of public access specifier has been changed. Now onward public access specifier has following three possibilities:
- public only within a module
- public to everyone
- public but only to the specific module
Here is more information public access specifier.
3. JShell (Real Eval Print Loop)
- The Java Shell (Read Eval Print Loop). The JShell tool will provide a way to interactively evaluate declarations, statements, and expressions of the Java programming language. (Java 9 Jshell Example)
- Following features provided by jshell:
- Import Declaration
- Class Declaration
- Interface Declaration
- Method Declaration
- Field Declaration
- Statement
- Primary
4. Private methods in Interface
- Java 9 interface support private methods to enable code sharing between non-abstract methods.
public interface ISearchEngine { private void printCommonFeatures(){ System.out.println("Http Rest Api"); System.out.println("ID field for updates and deduplication"); } default void printSolrFeatures(){ printCommonFeatures(); System.out.println("Query-time synonyms"); } }
5. Process API Improvements
- For native process, more information can be accessible like process id, arguments, start time, CPU Usage, name.
- Control for security manager permission. Here is more information about it.
6. Immutable Static Factory Methods for Set, List and Map
- Java 9 immutable list
- The
List.of()
static factory methods provide a convenient way to create immutable lists. java.util.List<String> language= java.util.List.of("Java", "C", "C++");
- The
- Java 9 immutable Set
- The
Set.of()
static factory methods provide a convenient way to create immutable sets. java.util.Set<String> language = java.util.Set.of("Java", "C", "C++");
- The
- Java 9 immutable Map
- The
Map.of()
andMap.ofEntries()
static factory methods provide a convenient way to create immutable maps java.util.Map<String,String> employeeDetails = java.util.Map.of("EmployeeName", "Jone","EmployeeRole","JavaDeveloper");
- The
7. Effectively final variables in try-with-resource
In Java 9 we can pass final or effectively final variable inside try block.
InputStream inputStream = new ByteArrayInputStream("JavaDeveloperZone".getBytes()); try (inputStream) { // do some operation } catch (Exception e) { // do some operation } finally { // do some operation }
8. Logging API
- Platform classes can use the API to log messages, together with a service interface for consumers of those messages so now no need of third partly logger (Java 9 Logger configuration with example)
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("FirstModule"); logger.info("JavaDeveloperZone first log.");
9. Javac with –version option
- Compile for Older Platform Versions. Javac can compile Java programs to run on selected older versions of the platform. (Java 9 compile java code older version java)
10. New methods on @Deprecation
- Provide better information about the status and intended disposition of APIs in the specification.
- A method
forRemoval()
returning aboolean
. Iftrue
, it means that this API element is earmarked for removal in a future release. Iffalse
, the API element is deprecated, but there is currently no intention to remove it in a future release. The default value of this element isfalse
.
- A method
A method named since()
returning String
. This string should contain the release or version number at which this API became deprecated. It has free-form syntax, but the release numbering should follow the same scheme as the @since
Javadoc tag for the project containing the deprecated API.
11. Tool to check deprecated resources.
- A static analysis tool
jdeprscan
will be provided that scans a jar file (or some other aggregation of class files) for uses of deprecated API elements. By default, the deprecated APIs will be the deprecations from Java SE itself.jdeprscan -l
Output :
@Deprecated(since="9") java.lang.Boolean(boolean) @Deprecated(since="9") java.lang.Boolean(java.lang.String) @Deprecated(since="9") java.lang.Byte(byte) @Deprecated(since="9") java.lang.Byte(java.lang.String) @Deprecated(since="1.5") java.lang.Character.UnicodeBlock.SURROGATES_AREA @Deprecated(since="9") java.lang.Character(char) @Deprecated(since="1.1") boolean java.lang.Character.isJavaLetter(char)
12. No longer allowed underscore as an identifier.
- using an underscore (
"_"
) as an identifier, which generates a warning as of Java SE 8, should be turned into an error in Java SE 9. - It will throws Error like:
Error:(23, 14) java: as of release 9, '_' is a keyword, and may not be used as an identifier
13. HTML 5 Docs
- Provide an option to
javadoc
to request either HTML 4 or HTML5 output. The HTML5 markup should be semantic, i.e., clearly separate meaning from style and content. The pages generated using HTML5 markup should satisfy accessibility requirements.Java 9 Features – HTML5 Document
- i.e. javadoc -html5
14. Javadoc Search
- Java provides document search so now we can easily find declared names of modules, packages, types and members will be indexed and searchable. Since methods can be overloaded, the simple name of method parameter types are also indexed and can be searched for. The method parameter names will not be indexed.
Java 9 Features – Doc Search
15. Version String Format
Java 9 version now will be $MAJOR.$MINOR.$SECURITY.$PATCH . So it will be easy to understand by humans and apps.
16. Linker Tool
A tool that can assemble and optimize a set of modules and their dependencies into a custom run-time image.
jlink --module-path <modulepath> --add-modules <modules> --limit-modules <modules> --output <path>
--module-path
is the path where observable modules will be discovered by the linker; these can be modular JAR files, JMOD files, or exploded modules--add-modules
names the modules to add to the run-time image; these modules can, via transitive dependencies, cause additional modules to be added--limit-modules
limits the universe of observable modules--output
is the directory that will contain the resulting run-time image
17. Stream Enhancements
- Stream iterator like as for loop.
Stream<Integer> integerStream = Stream.iterate(0, (Integer i) -> (i < 10), (Integer i) -> i + 1); integerStream.forEach(System.out::println);
Output:
0 1 2 3 4
- Stream for Files
Stream<String> fileLineStream = Files.lines(Paths.get("Demo.java")); fileLineStream.filter(line->(line.startsWith("T"))).forEach(System.out::println);
Output:
This file is reading using Files.lines function. Thank you Java 9 :)
- Stream for Optional
18. UTF-8 properties files
- Now Java can load properties files in UTF-8 format. By doing so, applications no longer need to convert the properties files using the escape mechanism.
19. New Static method in Thread: Thread.onSpinWait()
Thread.onSpinWait()
method Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. By invoking this method within each iteration of a spin-wait loop construct, the calling thread indicates to the runtime that it is busy-waiting. The runtime may take action to improve the performance of invoking spin-wait loop constructions.
20. SHA 3 hash algorithm
21. Java.util.Objects Static method requireNonNullElse
requireNonNullElse
Static method in java.util.Objects
return default value if object is null.
Employee employeeNull=null; Employee defaultEmployee=new Employee(); defaultEmployee.setName("Default Employee"); Employee newEmployee=java.util.Objects.requireNonNullElse(employeeNull,defaultEmployee); System.out.println(newEmployee.getName());
References:
https://docs.oracle.com/javase/9/docs/api/index.html?overview-summary.html
http://openjdk.java.net/jeps/201