Java 9 Features with Examples

Java 9 Features with Examples

February 27, 2017 by Rambabu Posa

As per latest news by Dec 2016, JDK 9 release date is postponed to July 2017

Java 9 is about to be released in March 2017. So it’s right time to look for java 9 features. We will look into java 9 features with example programs.

Java 9 Features

java 9 features
Some of the important java 9 features are;

Java 9 REPL (JShell)
Factory Methods for Immutable List, Set, Map and Map.Entry
Private methods in Interfaces
Java 9 Module System
Process API Improvements
Try With Resources Improvement
CompletableFuture API Improvements
Reactive Streams
Diamond Operator for Anonymous Inner Class
Optional Class Improvements
Stream API Improvements
Enhanced @Deprecated annotation
HTTP 2 Client
Мulti-Resolution Image API
Miscellaneous Java 9 Features
Oracle Corporation is going to release Java SE 9 around end of March 2017. In this post, I’m going to discuss about “Java 9 Features” briefly with some examples.

Java 9 REPL (JShell)

Oracle Corp has introduced a new tool called “jshell”. It stands for Java Shell and also known as REPL (Read Evaluate Print Loop). It is used to execute and test any Java Constructs like class, interface, enum, object, statements etc. very easily.

We can download JDK 9 EA (Early Access) software from https://jdk9.java.net/download/

G:>jshell
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro

jshell> int a = 10
a ==> 10

jshell> System.out.println("a value = " + a )
a value = 10
If you want to know more about REPL tool, Please go through Java 9 REPL Basics (Part-1) and Java 9 REPL Features (Part-2).

Factory Methods for Immutable List, Set, Map and Map.Entry

Oracle Corp has introduced some convenient factory methods to create Immutable List, Set, Map and Map.Entry objects. These utility methods are used to create empty or non-empty Collection objects.

In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects. For instance, if we want to create an Immutable List, then we can use Collections.unmodifiableList method.

However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map interfaces.

List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:

Empty List Example

List immutableList = List.of();
Non-Empty List Example

List immutableList = List.of("one","two","three");
Map has two set of methods: of() methods and ofEntries() methods to create an Immutable Map object and an Immutable Map.Entry object respectively.

Empty Map Example

jshell> Map emptyImmutableMap = Map.of()
emptyImmutableMap ==> {}
Non-Empty Map Example

jshell> Map nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three")
nonemptyImmutableMap ==> {2=two, 3=three, 1=one}
If you want to read more about these utility methods, please go through the following links:

Java 9 Factory Methods for Immutable List
Java 9 Factory Methods for Immutable Set
Java 9 Factory Methods for Immutable Map and Map.Entry

Private methods in Interfaces

In Java 8, we can provide method implementation in Interfaces using Default and Static methods. However we cannot create private methods in Interfaces.

To avoid redundant code and more re-usability, Oracle Corp is going to introduce private methods in Java SE 9 Interfaces. From Java SE 9 on-wards, we can write private and private static methods too in an interface using ‘private’ keyword.

These private methods are like other class private methods only, there is no difference between them.

public interface Card{

private Long createCardID(){
// Method implementation goes here.
}

private static void displayCardDetails(){
// Method implementation goes here.
}

}
If you want to read more about this new feature, please go through this link: Java 9 Private methods in Interface.

Java 9 Module System

One of the big changes or java 9 feature is the Module System. Oracle Corp is going to introduce the following features as part of Jigsaw Project.

Modular JDK
Modular Java Source Code
Modular Run-time Images
Encapsulate Java Internal APIs
Java Platform Module System
Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications. This architecture has lot of limitations and drawbacks. To avoid all these shortcomings, Java SE 9 is coming with Module System.

JDK 9 is coming with 92 modules (may change in final release). We can use JDK Modules and also we can create our own modules as shown below:

Simple Module Example

module com.foo.bar { }
Here We are using ‘module’ to create a simple module. Each module has a name, related code and other resources.

To read more details about this new architecture and hands-on experience, please go through my original tutorials here:

Java 9 Module System Basics
Java 9 Module System Examples

Process API Improvements

Java SE 9 is coming with some improvements in Process API. They have added couple new classes and methods to ease the controlling and managing of OS processes.

Two new interfcase in Process API:

java.lang.ProcessHandle
java.lang.ProcessHandle.Info
Process API example

ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("Current Process Id: = " + currentProcess.getPid());
If you want to read more about this new API, please go through my original tutorial at: Java SE 9: Process API Improvements.

Try With Resources Improvement

We know, Java SE 7 has introduced a new exception handling construct: Try-With-Resources to manage resources automatically. The main goal of this new statement is “Automatic Better Resource Management”.

Java SE 9 is going to provide some improvements to this statement to avoid some more verbosity and improve some Readability.

Java SE 7 example

void testARM_Before_Java9() throws IOException{
BufferedReader reader1 = new BufferedReader(new FileReader("journaldev.txt"));
try (BufferedReader reader2 = reader1) {
System.out.println(reader2.readLine());
}
}
Java 9 example

void testARM_Java9() throws IOException{
BufferedReader reader1 = new BufferedReader(new FileReader("journaldev.txt"));
try (reader1) {
System.out.println(reader1.readLine());
}
}
To read more about this new feature, please go through my original tutorial at: Java 9 Try-With-Resources Improvements

CompletableFuture API Improvements

In Java SE 9, Oracle Corp is going to improve CompletableFuture API to solve some problems raised in Java SE 8. They are going add to support some delays and timeouts, some utility methods and better sub-classing.

Executor exe = CompletableFuture.delayedExecutor(50L, TimeUnit.SECONDS);
Here delayedExecutor() is static utility method used to return a new Executor that submits a task to the default executor after the given delay.

To read more about this feature, please go through my original tutorial at: Java SE 9: CompletableFuture API Improvements

Reactive Streams

Now-a-days, Reactive Programming has become very popular in developing applications to get some beautiful benefits. Scala, Play, Akka etc. Frameworks has already integrated Reactive Streams and getting many benefits. Oracle Corps is also introducing new Reactive Streams API in Java SE 9.

Java SE 9 Reactive Streams API is a Publish/Subscribe Framework to implement Asynchronous, Scalable and Parallel applications very easily using Java language.

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
If you want to read more about this new API, please go through my original tutorials at: Introduction to Reactive Programming and Java SE 9: Reactive Streams.

Diamond Operator for Anonymous Inner Class

We know, Java SE 7 has introduced one new feature: Diamond Operator to avoid redundant code and verbosity, to improve readability. However in Java SE 8, Oracle Corp (Java Library Developer) has found that some limitation in the use of Diamond operator with Anonymous Inner Class. They have fixed that issues and going to release as part of Java 9.

public List getEmployee(String empid){
// Code to get Employee details from Data Store
return new List(emp){ };
}
Here we are using just “List” without specifying the type parameter. To read more details about this improvement, please go through my original tutorial at: Java SE 9: Diamond Operator improvements for Anonymous Inner Class

Optional Class Improvements

In Java SE 9, Oracle Corp has added some useful new methods to java.util.Optional class. Here I’m going to discuss about one of those methods with some simple example: stream method

If a value present in the given Optional object, this stream() method returns a sequential Stream with that value. Otherwise, it returns an Empty Stream.

They have added “stream()” method to work on Optional objects lazily as shown below:

Stream<Optional> emp = getEmployee(id)
Stream empStream = emp.flatMap(Optional::stream)
Here Optional.stream() method is used convert a Stream of Optional of Employee object into a Stream of Employee so that we can work on this result lazily in the result code.

To understand more about this feature with more examples and to read more new methods added to Optional class, please go through my original tutorial at: Java SE 9: Optional Class Improvements

Stream API Improvements

In Java SE 9, Oracle Corp has added four useful new methods to java.util.Stream interface. As Stream is an interface, all those new implemented methods are default methods. Two of them are very important: dropWhile and takeWhile methods

If you are familiar with Scala Language or any Functions programming language, you will definitely know about these methods. These are very useful methods in writing some functional style code. Let us discuss about takeWhile utility method here.

This takeWhile() takes a predicate as an argument and returns a Stream of subset of the given Stream values until that Predicate returns false for first time. If first value does NOT satisfy that Predicate, it just returns an empty Stream.

jshell> Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i < 5 )
.forEach(System.out::println);
1
2
3
4
To read more about takeWhile and dropWhile methods and other new methods, please go through my original tutorial at: Java SE 9: Stream API Improvements

Enhanced @Deprecated annotation

In Java SE 8 and earlier versions, @Deprecated annotation is just a Marker interface without any methods. It is used to mark a Java API that is a class, field, method, interface, constructor, enum etc.

In Java SE 9, Oracle Corp has enhanced @Deprecated annotation to provide more information about deprecated API and also provide a Tool to analyse an application’s static usage of deprecated APIs. They have add two methods to this Deprecated interface: forRemoval and since to serve this information.

Read my original tutorial at: Java SE 9: Enhanced @Deprecated annotation to see some useful examples.

HTTP 2 Client

In Java SE 9, Oracle Corp is going to release New HTTP 2 Client API to support HTTP/2 protocol and WebSocket features. As existing or Legacy HTTP Client API has numerous issues (like supports HTTP/1.1 protocol and does not support HTTP/2 protocol and WebSocket, works only in Blocking mode and lot of performance issues.), they are replacing this HttpURLConnection API with new HTTP client.

They are going to introduce new HTTP 2 Client API under “java.net.http” package. It supports both HTTP/1.1 and HTTP/2 protocols. It supports both Synchronous (Blocking Mode) and Asynchronous Modes. It supports Asynchronous Mode using WebSocket API.

We can see this new API at: http://download.java.net/java/jdk9/docs/api/java/net/http/package-summary.html

HTTP 2 Client Example

jshell> import java.net.http.*

jshell> import static java.net.http.HttpRequest.*

jshell> import static java.net.http.HttpResponse.*

jshell> URI uri = new URI("http://rams4java.blogspot.co.uk/2016/05/java-news.html")
uri ==> http://rams4java.blogspot.co.uk/2016/05/java-news.html

jshell> HttpResponse response = HttpRequest.create(uri).body(noBody()).GET().response()
response ==> java.net.http.HttpResponseImpl@79efed2d

jshell> System.out.println("Response was " + response.body(asString()))
Please go through my original tutorial at: Java SE 9: HTTP 2 Client to understand HTTP/2 protocol & WebSocket, Benefits of new API and Drawbacks of OLD API with some useful examples.

Мulti-Resolution Image API

In Java SE 9, Oracle Corp is going to introduce a new Мulti-Resolution Image API. Important interface in this API is MultiResolutionImage . It is available in java.awt.image package.

MultiResolutionImage encapsulates a set of images with different Height and Widths (that is different resolutions) and allows us to query them with our requirements.

Please go through my original tutorial at: Java SE 9: Мulti-Resolution Image API to understand this new API more with some examples.

Miscellaneous Java 9 Features

In this section, I will just list out some miscellaneous Java SE 9 New Features. I’m NOT saying these are less important features. They are also important and useful to understand them very well with some useful examples.

As of now, I did not get enough information about these features. That’s why I am going list them here for brief understanding. I will pickup these Features one by one and add to above section with a brief discussion and example. And final write a separate tutorial later.

GC (Garbage Collector) Improvements
Stack-Walking API
Filter Incoming Serialization Data
Deprecate the Applet API
Indify String Concatenation
Enhanced Method Handles
Java Platform Logging API and Service
Compact Strings
Parser API for Nashorn
Javadoc Search
HTML5 Javadoc
I will pickup these java 9 features one by one and update them with enough description and examples.

That’s all about java 9 features in brief with examples.

Filed Under: Java

About Rambabu Posa

Rambabu Posa have 12+ years of RICH experience as Sr Agile Lead Java/Scala/BigData/NoSQL Developer. Apart from Java, he is good at Spring4, Hibernate4, MEAN Stack, RESTful WebServices, NoSQL, BigData Hadoop Stack, Cloud, Scala, Groovy Grails, Play Framework, TDD, BDD,Agile,DevOps and much more. His hobbies are Developing software, Learning new technologies, Love Walking, Reading Books, Watching TV and obviously sharing his knowledge through writing articles on JournalDev.

? jQuery keypress event
Java SE 9: Stream API Improvements ?
Recommended Tutorials

Java Tutorials: Java IO Tutorial, Java Regular Expressions Tutorial, Multithreading in Java, Java Logging API Tutorial, Java Annotations,Java XML Tutorial, Collections in Java, Java Generics, Exception Handling in Java, Java Reflection, Java Design Patterns, JDBC Tutorial
Java EE: Servlet JSP Tutorial, Struts2 Tutorial, Spring Tutorial, Hibernate Tutorial, Primefaces Tutorial
Web Services: Apache Axis 2 Tutorial, JAX-RS Web Services Tutorial
Misc: Memcached Tutorial

Resources: Free eBooks, My Favorite Web Hosting
Important Interview Questions

Java String Interview Questions, Java Multithreading Interview Questions, Java Programming Interview Questions, Java Interview Questions, Java Collections Interview Questions, Java Exception Interview Questions

Servlet Interview Questions, JSP Interview Questions, Struts2 Interview Questions, JDBC Interview Questions, Spring Interview Questions, Hibernate Interview Questions
? 2017 · Privacy Policy · Don't copy, it's Bad Karma · Powered by WordPress

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,002評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,400評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,136評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,714評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,452評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,818評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,812評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,997評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,552評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,292評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,510評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,721評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,121評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,429評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,235評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,480評論 2 379

推薦閱讀更多精彩內容