Java 9 tutorial for beginners

Java 9 programming development tutorial for beginners

 

 

Java 9 also known as JDK 1.9 is a major release of java programming language development. The initial release was out on the 21st of September 2017. As a java developer, whether beginner, intermediate or professional, it is expedient that you come to understand the four main goals of Java 9 release.

java 9 tutorials

The following is an outline of the four main goals of Java 9 release.

  1. To make JDK and java standard edition platform modular to be based in the sense that it can be integrated and scaled down to smaller devices well. As you should be well aware that over one billion devices in the world run on java. So scaling down to smaller devices with excellent integration is one of the most important goals for the java 9 release.
  2. Every platform needs to be secure. Imagine building a house without any security implementation. Another main goal of java 9 release that we can’t overlook, is the provision of the overall security of the JDK and Java implementations.
  3. To make build process and maintenance of java code libraries applications easy for both java SE and Java SE platforms.
  4. To design and implement a quality module system for the java platform which can be applied on both platform and JDK.

 

 

New features of JAVA 9 programming language development

There are a lot of enhancements that were added to Java 9, we are only going to pay attention to the most significant ones as highlighted below −

  • Module − A new kind of Java programing component introduced as a 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.
  • Multi release 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.

 

 

How to set up a development environment for java 9

Local Environment Setup

If you want to set up your own environment for Java programming language, then this section would teach you all you need to know. Please endeavour to follow the following steps so that you can know more about what it takes, and what you need to set up your java environment.

Java SE is can be downloaded online for free. Please click here, to download a version compatible with your operating system.

Follow the instructions below so that you can be able to download Java, and run the .exe for installation of afore downloaded Java on your machine. Once you have installed Java on your machine, you would need now need to set environment variables to point to correct installation directories.

 

Setting Up the Path for Windows 2018/19

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Right-click on ‘My Computer’ and select ‘Properties’.
  • Click on the ‘Environment variables’ button under the ‘Advanced’ tab.
  • Now, edit the ‘Path’ variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, or  C:\Windows\System64 then edit it the following way

C:\Windows\System32;c:\Program Files\java\jdk\bin

 

How to set up the Path for Linux, UNIX, Solaris, FreeBSD java development

Environment variable PATH should be set to point to where your Java binaries have been installed. For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −

 

Best  Editors for writing java code

To be able to write a java application, you need to have a text editor.  We know that there are more sophisticated IDEs available in the market., but we have the popular ones are briefly described below −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
  • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/.

IDE or Integrated Development Environment provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

Java 9 – Module System

Java 9, there is a  new kind of programming component known as a module which java 9 has introduced. A module is a self-describing collection of code and data and has a name that can be used to identify it.

Features of Java 9 – module system

With the Modules component, the following enhancements have been added in Java 9 −

  • A new optional phase, link time, was introduced. This phase is in-between compile time and run time. In this phase, a set of modules can be assembled and optimized, making a custom runtime image using the jlink tool.
  • javac, jlink, and java have more available options that are used 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.

How to create a module in java 9

Following the steps to create a module say com.nairaguide.com.greetings.

Step 1

Create a folder C:\>JAVA\src. Now create a folder com.nairaguide.com.greetings which is same as the name of module we’re creating.

Step 2

Create module-info.java in C:\>JAVA\src\com.tutorialspoint.greetings folder with following code.

 

module-info.java

module com.nairaguide.greetings { }

module-info.java would be the file which is used to create a module. In this step, we’ve created a module named com.tutorialspoint.greetings. By convention, this file should reside in the folder whose name is same as a module name.

Step 3

Add the source code in the module. Create Java9Tester.java in C:\>JAVA\src\com.nairaguide.greetings\com\nairaguide\greetings folder with following code.

 

Java9Tester.java

package com.nairaguide.greetings;

 

public class Java9Tester {

public static void main(String[] args) {

System.out.println(“Hello World!”);

}

}

 

In a very conventional approach, the source code of a module should be in the same directory as is the name of the module.

Step 4

Create a folder C:\>JAVA\mods. Now create a folder com.nairaguide.greetings which is same as the name of the module we’ve created. Now compile the module to mods directory.

C:/ > JAVA > javac -d mods/com.tutorialspoint.greetings

 

src/com.nairaguide.greetings/module-info.java

 

src/com.tutorialspoint.greetings/com/nairaguide/greetings/Java9Tester.java

 

step 5

let us run the module to see the result. So if you have done the above-specified instruction, run the following command to see what your output would give you.

 output

the following output would be printed on your console if have followed all instructions correctly.

Hello World!

 

 

Java 9 – REPL (JShell)

 

With JShell, java has REPL capability. Using REPL, we can code and test java-based logic without compiling using javac and see the result of calculations directly.

REPL stands for Read-Eval-Print Loop.

 

Running JShell

Open command prompt and type jshell.

$ jshell

|  Welcome to JShell — Version 9-ea

|  For an introduction type: /help intro

jshell>

Viewing JShell commands

Type /help once jshell command starts running.

jshell> /help

|  Type a Java language expression, statement, or declaration.

|  Or type one of the following commands:

|  /list [<name or id>|-all|-start]

|  list the source you have typed

|  /edit <name or id>

|  edit a source entry referenced by name or id

|  /drop <name or id>

|  delete a source entry referenced by name or id

|  /save [-all|-history|-start] <file>

|  Save snippet source to a file.

|  /open <file>

|  open a file as source input

|  /vars [<name or id>|-all|-start]

|  list the declared variables and their values

|  /methods [<name or id>|-all|-start]

|  list the declared methods and their signatures

|  /types [<name or id>|-all|-start]

|  list the declared types

|  /imports

|  list the imported items

Running JShell command

Type /imports once jshell command starts running and see the used imports.

jshell> /imports

|    import java.io.*

|    import java.math.*

|    import java.net.*

|    import java.nio.file.*

|    import java.util.*

|    import java.util.concurrent.*

|    import java.util.function.*

|    import java.util.prefs.*

|    import java.util.regex.*

|    import java.util.stream.*

jshell>

Running Calculations in JShell.

Try running simple calculations in JShell.

jshell> 3+1

$1 ==> 4

jshell> 13%7

$2 ==> 6

jshell> $2

$2 ==> 6

jshell>

Creating and using functions in JShell

Create a function doubled() to take int and return its doubled value.

jshell> int doubled(int i){ return i*2;}

|  created method doubled(int)

jshell> doubled(6)

$3 ==> 12

jshell>

Exiting JShell

Type /exit.

jshell> /exit

| Goodbye

 

 

 

Java 9 – Improved JavaDocs

As a java developer, you can generate Java documentation using the Javadoc tool. It currently generates documentation in HTML 4.0 format. In java 9, we can generate documentation in HTML 5 formats by using -html5 option in command line arguments.

Old style java documentation

Consider the following code in C:/JAVA folder.

Tester.java

 

/**

* @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”);

}

}

Now run the javadoc tool of jdk 7 to generate documentation.

C:\JAVA>javadoc -d C:/JAVA Tester.java

Loading source file tester.java…

Constructing Javadoc information…

Standard Doclet version 1.7.0_21

Building tree for all the packages and classes…

Generating C:\JAVA\Tester.html…

Generating C:\JAVA\package-frame.html…

Generating C:\JAVA\package-summary.html…

Generating C:\JAVA\package-tree.html…

Generating C:\JAVA\constant-values.html…

Building index for all the packages and classes…

Generating C:\JAVA\overview-tree.html…

Generating C:\JAVA\index-all.html…

Generating C:\JAVA\deprecated-list.html…

Building index for all classes…

Generating C:\JAVA\allclasses-frame.html…

Generating C:\JAVA\allclasses-noframe.html…

Generating C:\JAVA\index.html…

Generating C:\JAVA\help-doc.html…

It will create the java documentation page in C:/JAVA directory and you will see the following output.

New java documentation with Search and HTML5 support

Run the Javadoc tool of jdk 9 with -html5 flag to generate new type of documentation.

C:\JAVA> javadoc -d C:/JAVA -html5 Tester.java

Loading source file Tester.java…

Constructing Javadoc information…

Standard Doclet version 9.0.1

Building tree for all the packages and classes…

Generating C:\JAVA\Tester.html…

Generating C:\JAVA\package-frame.html…

Generating C:\JAVA\package-summary.html…

Generating C:\JAVA\package-tree.html…

Generating C:\JAVA\constant-values.html…

Building index for all the packages and classes…

Generating C:\JAVA\overview-tree.html…

Generating C:\JAVA\index-all.html…

Generating C:\JAVA\deprecated-list.html…

Building index for all classes…

Generating C:\JAVA\allclasses-frame.html…

Generating C:\JAVA\allclasses-frame.html…

Generating C:\JAVA\allclasses-noframe.html…

Generating C:\JAVA\allclasses-noframe.html…

Generating C:\JAVA\index.html…

Generating C:\JAVA\help-doc.html…

It will create the updated java documentation page in D:/test directory and you will see the following output.

 

 

Java 9 – Multirelease JAR

 

In java 9, a new feature was introduced where a jar format can be enhanced to have different versions of java class or resources can be maintained and used on the same platform. In JAR, a file MANIFEST.MF file has an entry Multi-Release: true in its main section. META-INF directory would contain the versions subdirectory whose subdirectories (starting with 9 for Java 9 ) store version-specific classes and resource files.

In this example, we’ll be using a multi-release jar to have two versions of Tester.java file, one for JDK 7 and one for JDK 9 and run it on different JDK versions.

Steps

Step 1 − Create a folder c:/test/java7/com/nairaguide. Create Test.java with the following content −

Tester.java

 

package com.nairaguide; public class Tester {   public static void main(String[] args) {      System.out.println(“Inside java 7”);   }}

Step 2 − Create a folder c:/test/java9/com/tutorialspoint. Create Test.java with following content −

Tester.java

 

package com.nairaguide; public class Tester {   public static void main(String[] args) {      System.out.println(“Inside java 9”);   }}

Compile the source codes.

C:\test > javac –release 9 java9/com/nairaguide/Tester.java C:\JAVA > javac –release 7 java7/com/nairaguide/Tester.java

Create the multi-release jar

C:\JAVA > jar -c -f test.jar -C java7 . –release 9 -C java9.Warning: entry META-INF/versions/9/com/nairaguide/Tester.java,    multiple resources with same name

Run with JDK 7

C:\JAVA > java -cp test.jar com.nairaguide.TesterInside Java 7

Run with JDK 9

C:\JAVA > java -cp test.jar com.nairaguide.TesterInside Java 9

 

Java 9 – Collection Factory Methods

With Java 9, new factory methods are added to List, Set and Map interfaces to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in a concise way.

Old way to create collections

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;

 

public class Tester {

 

public static void main(String []args) {

Set<String> set = new HashSet<>();

set.add(“A”);

set.add(“B”);

set.add(“C”);

set = Collections.unmodifiableSet(set);

System.out.println(set);

List<String> list = new ArrayList<>();

 

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 the Map interface, of(…) method is overloaded to have 0 to 10 parameters.
  • In case of more than 10 parameters for Map interface, ofEntries(…) method can be used accepting var args parameter.

New way to create collections

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.AbstractMap;

import java.util.Map;

import java.util.Set;

 

public class Tester {

 

public static void main(String []args) {

Set<String> set = Set.of(“A”, “B”, “C”);

System.out.println(set);

List<String> list = List.of(“A”, “B”, “C”);

System.out.println(list);

Map<String, String> map = Map.of(“A”,”Apple”,”B”,”Boy”,”C”,”Cat”);

System.out.println(map);

 

Map<String, String> map1 = Map.ofEntries (

new AbstractMap.SimpleEntry<>(“A”,”Apple”),

new AbstractMap.SimpleEntry<>(“B”,”Boy”),

new AbstractMap.SimpleEntry<>(“C”,”Cat”));

System.out.println(map1);

}

}

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.

 

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(“”);

}

}

 

final class LogOracle implements Logging {

@Override

public void logInfo(String message) {

getConnection();

System.out.println(“Log Message : ” + “INFO”);

closeConnection();

}

 

@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”);

}

}

 

final class LogMySql implements Logging {

@Override

public void logInfo(String message) {

getConnection();

System.out.println(“Log Message : ” + “INFO”);

closeConnection();

}

 

@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 logInfo(String message);

void logWarn(String message);

void logError(String message);

void logFatal(String message);

 

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(“”);

}

}

 

final class LogOracle implements Logging {

}

 

final class LogMySql implements Logging {

}

 

interface Logging {

String ORACLE = “Oracle_Database”;

String MYSQL = “MySql_Database”;

 

default void logInfo(String message) {

getConnection();

System.out.println(“Log Message : ” + “INFO”);

closeConnection();

}

 

default void logWarn(String message) {

getConnection();

System.out.println(“Log Message : ” + “WARN”);

closeConnection();

}

 

default void logError(String message) {

getConnection();

System.out.println(“Log Message : ” + “ERROR”);

closeConnection();

}

 

default void logFatal(String message) {

getConnection();

System.out.println(“Log Message : ” + “FATAL”);

closeConnection();

}

 

static void getConnection() {

System.out.println(“Open Database connection”);

}

static void closeConnection() {

System.out.println(“Close Database connection”);

}

}

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(“”);

}

}

 

final class LogOracle implements Logging {

}

 

final class LogMySql implements Logging {

}

 

interface Logging {

String ORACLE = “Oracle_Database”;

String MYSQL = “MySql_Database”;

 

private void log(String message, String prefix) {

getConnection();

System.out.println(“Log Message : ” + prefix);

closeConnection();

}

 

default void logInfo(String message) {

log(message, “INFO”);

}

 

default void logWarn(String message) {

log(message, “WARN”);

}

 

default void logError(String message) {

log(message, “ERROR”);

}

 

default void logFatal(String message) {

log(message, “FATAL”);

}

 

private static void getConnection() {

System.out.println(“Open Database connection”);

}

 

private static void closeConnection() {

System.out.println(“Close Database connection”);

}

}

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

Java 9 – Process API Improvements

In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process’s native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes’ liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits.

Tester.java

import java.time.ZoneId;

import java.util.stream.Stream;

import java.util.stream.Collectors;

import java.io.IOException;

 

public class Tester {

public static void main(String[] args) throws IOException {

ProcessBuilder pb = new ProcessBuilder(“notepad.exe”);

String np = “Not Present”;

Process p = pb.start();

ProcessHandle.Info info = p.info();

System.out.printf(“Process ID : %s%n”, p.pid());

System.out.printf(“Command name : %s%n”, info.command().orElse(np));

System.out.printf(“Command line : %s%n”, info.commandLine().orElse(np));

 

System.out.printf(“Start time: %s%n”,

info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())

.toLocalDateTime().toString()).orElse(np));

 

System.out.printf(“Arguments : %s%n”,

info.arguments().map(a -> Stream.of(a).collect(

Collectors.joining(” “))).orElse(np));

 

System.out.printf(“User : %s%n”, info.user().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

Java 9 – Stream API Improvements

Streams were introduced in Java to help developers perform aggregate operations from a sequence of objects. With Java 9, few more methods are added to make streams better.

takeWhile(Predicate Interface)

Syntax

default Stream<T> takeWhile(Predicate<? super T> predicate)

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;

 

public class Tester {

public static void main(String[] args) {

Stream.of(“a”,”b”,”c”,””,”e”,”f”).takeWhile(s->!s.isEmpty())

.forEach(System.out::print);

}

}

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;

 

public class Tester {

public static void main(String[] args) {

Stream.of(“a”,”b”,”c”,””,”e”,”f”).dropWhile(s-> !s.isEmpty())

.forEach(System.out::print);

System.out.println();

Stream.of(“a”,”b”,”c”,””,”e”,””,”f”).dropWhile(s-> !s.isEmpty())

.forEach(System.out::print);

}

}

Output

dropWhile method drops a,b and c values, then once string is empty, it takes all the values.

ef

ef

iterate

Syntax

static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)

iterate method now has hasNext predicate as parameter which stops the loop once hasNext predicate returns false.

Example

import java.util.stream.IntStream;

 

public class Tester {

public static void main(String[] args) {

IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println);

}

}

Output

3

6

9

ofNullable

Syntax

static <T> Stream<T> ofNullable(T t)

ofNullable method is introduced to prevent NullPointerExceptions and to avoid null checks for streams. This method returns a sequential Stream containing single element, if non-null, otherwise returns an empty Stream.

Example

import java.util.stream.Stream;

 

public class Tester {

public static void main(String[] args) {

long count = Stream.ofNullable(100).count();

System.out.println(count);

 

count = Stream.ofNullable(null).count();

System.out.println(count);

}

}

Output

1

0

 

 

Java 9 tutorial for beginners

Java 9 programming development tutorial for beginners     Java 9 also known as JDK 1.9 is a major release of java programming language developmen

Product In-Stock: 1

Editor's Rating:
0

Leave a Reply

Your email address will not be published. Required fields are marked *