0% found this document useful (0 votes)
3 views

Java_9_Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java_9_Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Java 9 Notes

➢ Jshell
 Jshell is nothing but Java REPL tool.
 REPL : Read, Evaluate, print, Loop (Repeat the same like Read,
Evaluate and print)
 Jshell is known as Interactive console
What is Jshell ?
 The Java Shell tool (JShell) is an interactive tool for learning the Java
programming language and prototyping Java code. JShell is a Read-
Evaluate-Print Loop (REPL), which evaluates declarations, statements,
and expressions as they are entered and immediately shows the
results. The tool is run from the command line
 For Beginners -> Learning and syntax
 For Developers: -> Execute part of program in simple way
 Jshell is not meant for main coding
 It is helpful for testing part of program snippets

How to open Jshell ?


 To open Jshell go to command prompt and type jshell.
If you don't have the Java 9 installed on your machine system will
throw the error
SO install the Java 9 and change the class path and JAVA_HOME
variable paths in environment variables to point to java9
 Now close the previous cmd window and open new cmd window and
type Jshell now you can see the Jshell window
Commands of Jshell
Jshell - To Open Jshell from commad prompt
Jshell -v : Open Jshell in verbose mode
/exit : To exit from the Jshell

Advantages of Jshell

 Jshell has reduced all the efforts that are required to run a Java
program and test a business logic. If we don’t use Jshell, creating of
Java program involves the following steps.
 Open editor and write program
 Save the program
 Compile the program
 Edit if any compile time error
 Run the program
 Edit if any runtime error
 Repeat the process
 Jshell does not require above steps. We can evaluate statements,
methods and classes, even can write hello program without creating
class.
 JShell helps you try out code and easily explore options as you
develop your program
C:\Users\DELL>jshell --help : Help command on JSHELL from your location in cmd
jshell --help from command promt will let you all the features
C:\Users\DELL>jshell --version : To know the version of Jshell

What is Snippet in Jshell


Any valid java statement is called as Snippet in Jshell expect package

Java 8^J9 and 11 Page 1


 Any valid java statement is called as Snippet in Jshell expect package
statement
 It can be a variable or method or class or interface
 /list -> Will provide all active snippets
 /list -start -> will provide the start up snippets
 /list -all -> will give you all snippets (pre defined and user defined,
active and non active). A Snippet becomes non active when you use
the same variable name and modify the value then Jshell considers
the latest value as the value for that variable and old variable is
inactive
 Ex: int x=10 -> Currently this is active snippet
Inactive Variable
 When I write one more variable with same name like below
 String x="Abc"; then when I enter the /list command system Jshell
will show the value for x as "Abc" and previous x=10 becomes
inactive so this inactive variable can be listed when you use the
command /list -all
 Each snippet has snippet id
 If I enter some value like below op is 30
Example:
 ->jshell>10+20
 Op: $1 =>30
 Scratch Variable: To hold some temporary values Jshell uses some
variables those are called scratch variables
 Variables created by Jshell is called as Scratch variable
 On top of this scratch variables you can do the operations on this
scratch variables
 Jshell>$1>5
 Op is : $2=>true (because $1 is nothing but scratch variable and it is
holding the value of 30 and after comparing this $1>5 again it creates
new variable that is $2 which is true)
 You can also print the scratch variable
 Jshell> System.out.println($1) => output is 30
 Jshell> System.out.println($2)=> output is true

If you want to list the snippet based on Id


 Jshell>/list 1 => list only 1 snippet
 Jshell>/list 1 5 => list only 1 and 5 snippet
 Jshell> /list x => list out x variable
 Jshell> /list add => if add is variable it displays that if it is method
then it displays method

 Package declarations is not allowed in Jshell

To Drop the Snippet (How to Drop a Snippet)


 Jshell> /drop snippetid/name
 Jshell> /drop x or /

To execute the snippet again without typing use below command


 Jshell> /snippet id

What is Explicit Variables: Variables which are created by the


programmer
 Jshell> int x=10;
 Jshell> String y="karthik"

Java 8^J9 and 11 Page 2


What is Implicit Variables or Scratch Variables
 These variables are the one which are created by the JSHELL (To store
the temporary values)
 Jshell> 10+20
 $3=>30 (Here $3 is the scratch variable )

In JSHELL Two variables with same name is not allowed. If you declare
the variable will hold the latest value
 JSHELL-> overrides the previous value if you try to create the variable
with same name:
Example:
 Jshell> int x=10;
Jshell>System.out.println(x)
 Op: 10
 Jshell> String x="ABC"
 Jshell>System.out.println(x)
 Op : ABC
 Here x=10 is int variable it is replaced by String x and value is ABC

To see all the variables in jshell

 Jshell>/var or /vars will provide all the available variables


 Jshell> /vars -all => List out all variables (Active and inactive)

To drop particular variable use /drop variable name


 Jshell> List<String> l== List.of("saas","kasd","sdds");
 Jshell> /drop l; or /drop snippet id

What is the difference between System.out.println and


System.out.printf in JSHELL

 Jshell>System.out.println("Hello")
 Op: is Hello (Here no Scratch variable will be created because return
type of println method is void)
 Jshell>System.out.printf("Hello")
 Op is:
 Hello$21 ==> java.io.PrintStream@eec5a4a
 | created scratch variable $21 : PrintStream
 Here printf method return type is not void hence it is creating scratch
variable

Working with Methods in Jshell:


Writing method in Jshell:

Calling the method using Jshell:

/List -all

Java 8^J9 and 11 Page 3


E3: is nothing but error while calling the method I didn't pass the
bracehence error

Method overload is possible in JSHELL

To list all methods /methods

 Look at here .methods is giving main() and main(int x) -> that means
method overload is possible

 If .you write the new method with same signature then old copy will
be overridden with new code

 Here void main(int x) is overridden with int main(int x)

 Any method you can declare in JSHELL

The above shows I created method and used variable but I haven't declared
variable so JSHELL doesn't throw compilation error. That means we can use
Undeclared variable in JSHELL

But when u want to call this method m4 until you declare the un declared
variable

To drop method
/drop method name:

Java 8^J9 and 11 Page 4


If multiple method with same name is present then which method will be dropped ?
Answer:
JSHELL will provide the error:

To drop the method in this case you can use /drop snippet id in case when u have multiple
methods with same name

We can Use the JSHELL in built editor to write method


Jshell>/edit => this command will open the jshell in built command

Java 8^J9 and 11 Page 5


In this editor you can write the methods or any java code and click on accept and click on
exit. So that JSHELL is closed.
Then this method or java code is available for JSELL
JSHELL>

See here I have written the method in JSHELL editor and executed from JSHELL

If you want to modify the existing method using JSHELL it is easy if you open the JSHELL
editor and modify and then click on Accept. Immediately it gets reflected in JSHELL

To change the editor to notepad or notepad++ then follow the below command
Jshell> /set editor %Editor installed path. If you want notepad then get notepad installed
path and give it here%

We can create interface, classes also in JSHELL

If you want to know all classes and interfaces available in JSHELL

JSHELL> /types

To open the existing JSHELL file.


First you need to create snippets and save as name.jsh (jsh is not mandatory it is
recommended)

Jshell> /open test.jsh

Java 8^J9 and 11 Page 6


Jshell> /open test.jsh

To see all commands whether it is loaded from file or not you can use /list command

What ever the commands you have entered in JSHELL to store those commands to a file
you have to use the below command

JSHELL> save test1.jsh

➢ Interface changes in Java 9: Private methods in Java 9


Java 9 allow us to define private methods in interface. It means now
encapsulation is possible in interface also. But we should know what the
need of private methods in interface is and when we should use it. Let’s
take an example:
 Constant variables
 Abstract methods
 Default methods
 Static methods
 Private methods
 Private Static methods
 Advantage of having the private methods in Java 9 is code reusability
with in the interface.
➢ Rules for using the private method in interface
 We can’t make the Private method as an abstract method. It means
we can’t use abstract keyword with a private method.
 The private method can be a static method as well. It means a
private method can be static and non-static.
 We should use private modifier to define these methods and no
lesser accessibility than private modifiers.
 Private method can be used or accessed only inside interface.
 Private static method can be used inside other static and non-static
interface methods.
 Private non-static methods cannot be used inside private static
methods

➢ Try With Resources:


 This try with resource is introduce in Java 1.7
 Generally we use try, catch and finally to do the exception handling we
use finally block is used to write the clean up code and finally block gets
executed every time irrespective of exception or not
 Before 1.7 we should close the resources using finally block, it is the
programmer responsibility and if the programmer forgets then it
creates the blocking operations. To overcome try with resource came
into picture
What is try with resource ?
 In 1.7 this Tr with resource is introduced. Execute the below code even
though the finally block is not present the JVM will execute the finally
block or closing the connection code etc.
Advantages of Try With Resource is
 Better Readable code
No need to add null checks
Java 8^J9 and 11 Page 7
 No need to add null checks
Rules for Try with resource in Java 1.7 is
 In Java SE 7 or 8 versions, we should follow these rules to use Try-With-
Resources statement for Automatic Resource Management(ARM)
 Any Resource (which Pre-defined Java API class or User Defined class)
must implement java.lang.AutoCloseable.
 Resource object must refer either final or effectively final variable
 If Resource is already declared outside the Try-With-Resources
Statement, we should re-refer with local variable (As shown in the
below example)
 That newly created local variable is valid to use within Try-With-
Resources Statement.
Issue with 1.7 Try with resource is
 We cannot use any Resource (which is declared outside the Try-With-
Resources) within try() block of Try-With-Resources statement.
Example:

Enhance made in Java 9 for try with resource is that try() can take multiple
resource and there is no need to create the resource inside try(); we can
declare the resource anywhere and we can use that resource in try();
In Java SE 9, if we have a resource which is already declared outside
the Try-With-Resource Statement as final or effectively final, then we
do NOT need to declare a local variable. We can use previously
created variable within Try-With-Resource

Syntax: try(R){ --//Here R is nothing but resource. Generally we don’t have


try with brackets. It is introduced in java 1.7
}catch(Exception e){
}

The try() automatically calls the close method (close method is present

Java 8^J9 and 11 Page 8


The try() automatically calls the close method (close method is present
in Autoclosable interface.)so we can create the user defined class and
implement the autoclosable interface and override the close method.
Try multiple resources and use the try with resource automatically close
method will be called for all the resources.

Output is :

➢ Process API Improvements


Java 9 has made some changes to the Process API, through which
working with operating system becomes easy.
For Example: If we would like to know the details of specific process or
kill the process or current running process or create new process then
this API is useful.

 Java 9 Process API Updates: –

 Some new methods are added to the Process class present in java.lang
package.
 The process class is an old class in Process API, only some methods like,
pid(), info() etc are added in java 9.
 Methods like startPipeline() are added to ProcessBuilder class which is
already present in old java versions.
 ProcessHandle(I) : This is a new interface added in java 9. It is used to
handle a process.
 ProcessHandle.Info(I): It is an inner interface, it provides all the
information related to a Process
 To get the information on current running process we have to call the
static method called current() present in the ProcessHandle Interface.

Java 8^J9 and 11 Page 9


static method called current() present in the ProcessHandle Interface.

 If you execute the above code, you can get the details of current running
process.

 If we want to know the details of some process based on process id then


we can use the of static method of ProcessHandle interface.
 If we want to destroy the process which is same as clicking the end
process button on Task manager then we have to call the destroy method
of ProcessHandle.
 If we would like to know all the process information then below code will
work. We have to call ethe allProcesses method. This is same as opening
the task manager and looking at details tab.

 To create new process, like opening a notepad or eclipse then we have to


go to start command and search for the process and start it. But using the
java program u can open the process. Look at the below example.
 To start the process we should use the class called as ProcessBuilder and
provide the .exe path of the application which you want to start.
 When you execute the below code it starts the notepad process and
eclipse process.

Java 8^J9 and 11 Page 10


➢ Java Platform Module System


 What is Module ? Module is nothing but group of packages
A Module is a group of closely related packages and resources
along with a new module descriptor file.

 With new Java 9 modules, we will have better capability to write well-
structured applications. This enhancement is divided into two areas:
 Modularize the JDK itself.
 Offer a module system for other applications to use
 Java 9 Module System has a “java.base” module. It’s known as Base
Module. It’s an Independent module and does NOT dependent on any
other modules. By default, all other modules are dependent on
“java.base“.
 In Java 9, modules help us in encapsulating packages and managing
dependencies. So typically,
 a class is a container of fields and methods
 a package is a container of classes and interfaces
 a module is a container of packages
 From Java 9 onwards, public means public only to all other packages
inside that module. Only when the package containing the public type is
exported, can it be used by other modules
 Package statement is mandatory in module based program
 The main goal of the Java 9 module system is to support modular
programming in Java.
 Currently, the Java 9 module system has about 98 modules, but it is
continuing to evolve. Oracle has categorized JDK jars and Java SE
specifications into two sets of modules.
 The default module for all JDK and user-defined modules is the base
module java.base. It is an independent module and doesn't depend on
any other modules. java.base is known as the "mother of Java 9 modules."

Java 8^J9 and 11 Page 11


Module Descriptor
When we create a module, we include a descriptor file that defines
several aspects of our new module:
 Each module has a unique name
 Each module has some description in a source file
 The module descriptor file is placed in the top-level directory
 Each module can have any number of packages and types
 One module can depend on any number of modules
• Name – the name of our module
• Dependencies – a list of other modules that this module depends on
• Public Packages – a list of all packages we want accessible from
outside the module
• Services Offered – we can provide service implementations that can
be consumed by other modules
• Services Consumed – allows the current module to be a consumer
of a service
• Reflection Permissions – explicitly allows other classes to use
reflection to access the private members of a package
The module naming rules are similar to how we name packages (dots
are allowed, dashes are not).
We need to list all packages we want to be public because by
default all packages are module private.

Module Types
There are four types of modules in the new module system:
• System Modules – These are the modules listed when we run
the list-modules command above. They include the Java SE and
JDK modules.
• Application Modules – These modules are what we usually want to
build when we decide to use Modules. They are named and defined in
the compiled module-info.class file included in the assembled JAR.
• Automatic Modules – We can include unofficial modules by adding
existing JAR files to the module path. The name of the module will be
derived from the name of the JAR. Automatic modules will have full
read access to every other module loaded by the path.
• Unnamed Module – When a class or JAR is loaded onto the classpath,
but not the module path, it's automatically added to the unnamed
module. It's a catch-all module to maintain backward compatibility with
previously-written Java code.

To set up a module, we need to put a special file at the root of our


packages named module-info.java.
This file is known as the module descriptor and contains all of the data
needed to build and use our new module.
Advantages of Module over jar:
Reliable configuration—Modularity provides mechanisms for explicitly declaring
dependencies between modules in a manner that’s recognized both at compile time
and execution time. The system can walk through these dependencies to determine
the subset of all modules required to support your app.
Example: Whenever you are working with multiple projects (Project A and Project B)
and if one project (Project B) would like to access the file from another project(Project
A) then we have to place the jar file of Project A in project B class path, then we can
access all the files of Project A.
Strong Encapsulation and Security: Other modules can access only exported packages
and not all packages.
Scalable Java platform: Compared to Jar module occupies less space as all the class will

Java 8^J9 and 11 Page 12


Scalable Java platform: Compared to Jar module occupies less space as all the class will
not be included in jar only exported packages will be part of the Jar

➢ An exports clause in Module-info.java


• Export can only be used for packages
• A module can export its packages to the outside world so that other
modules can use them. In the module descriptor, you use
the exports clause to export packages to the outside world or to
other modules:

• In the below image, you can see that EmpModelJ9 project has 2
packages but out of those 2 packages we are exporting only one
package so that this package com.model can be accessed by any
other module.
• Since we are not exporting com.test so other module can make use if
the classes present in this package.
• That means in Java 9 even though I mention the class as Public, it
means that until we mention that package as exports in module-
info.java other module cannot be able to access. Public class access is
limited to for that specific module if we don’t specify export in
module-info.java
• In Java 9 Module, there is a mechanism to control the access to
packages whereas this kind of option is not present in jar mechanism

➢ Qualified Export:

• Whenever we use Export keyword followed by Package name that


package will be available to all other modules. But if my requirement
is to make this package available for specific module then such type
of dependency is called as Qualified export.
Example:
• Syntax: Export package Name to Module Name.
• Export Pack1 to ModuleB
• Here we can even mention multiple modules also
• Export Pack1 to ModuleB, Module C

Java 8^J9 and 11 Page 13


➢ A requires clause
▪ A module can import or use other modules packages. In the
module descriptor, you use the requires clause to import other
modules in order to use their packages:
▪ Requires directive can only be used for Modules
▪ Requires keyword followed by one module only . If we want to
include multiple modules then for each module we should
specify requires keyword
▪ Requires ModuleA;
▪ Requires ModuleB;
▪ We cannot mention moduleA, Module B -> This is wrong
▪ If one module requires another module then you need to
mention that using requires attribute
▪ In the below example, EmpServiceJ9 module is dependent on
EmpCommonJ9 module hence in EmpServiceJ9 project module-
info.java file I have to mention that requires EmpCommonJ9
▪ requires <ModuleName>

➢ Requires Static Module Name:


▪ This dependency can be used only when at we need the
specified module to be available at compile time and not on run
time that means at run time module name is optional.
▪ Static key word is used to provide optional dependencies.
Anything specified with requires static then that corresponding
module is available at compile time but at run time is not
needed
▪ Cyclic Dependencies:
▪ B extends A and A extends B -> This is called cyclic inheritance
and it is not allowed in Java.
▪ Similarly -> Module A requires Module B and Module B requires
Moule A -> This is cyclic dependency. This is not allowed Java
Modules.
▪ EmpModelJ9 and EMPBusinessServiceJ9 are 2 java 9 modules. If
I am mentioning the cyclic dependency then below error that
compiler shows.
▪ Module dependency can occur among more than 2 modules that
means Module A-> Module B
▪ Module B-> Module C
▪ Module C- Module A

Java 8^J9 and 11 Page 14


Module Graph is nothing but dependency between the module is
represented using module graph.

➢ Uses
• Using uses keyword we can specify that our module needs or
consumes some service. Service is a interface or abstract class. It
should not be an implementation class.
• Syntax
• uses <service-required>;
Example
module com.module.util{
uses com.util.PersonDataService;
}
• Note: The most important thing to note here is that 'requires' adds a
module dependency, whereas 'uses' specifies required service class.

➢ Provides … With
• We can specify that our module provides some services that other
modules can use.
Syntax
• provides <service-provided> with <service-implementation-class> ;
Example
• module com.module.util{
provides com.util.PersonDataService with
com.util.DbPersonServiceImpl;
}

➢ Open
• Since java 9 encapsulation and security is improved for the
reflection apis. Using reflection we were able to access even the
private members of the objects.
• From java 9 this is not open by default. We can although grant
reflection permission to other modules explicitly.
• open module com.module.util{
}
• In this case all the packages from util module are accessible using
reflection.
➢ Opens
• If we do not want to open all the packages for reflection we can
specify packages manually using 'opens' keyword.

Java 8^J9 and 11 Page 15


specify packages manually using 'opens' keyword.
• module com.module.util{
opens com.module.package1;
}
• In this case only classes from package1 are accessible using
reflection.
➢ Opens … To
• Using 'opens ...to' keyword we can open reflection permission for
specific packages to specific modules only.
• module com.module.util{
opens com.module.package1 to module.a, module.b,
org.test.integration;
}
• In this case only module.a, module.b, org.test.integration modules
can access classes from package1 using reflection.
• Note: If we need reflection access to the module, we can gain the
access using command line option '–add-opens', even if we are not
the owner of the module

➢ Aggregator Module

• This is nothing but a module which is going to club multiple modules


and make it available for next module is called as aggregator module.

• The transitive keyword is important in this aggregator module. This


provides the reusability
• First of all, this is not a technical concept. It is just a convenience
concept for developers to make there life easier.
• Sometimes multiple modules require other multiple modules. Instead
of adding these in every module descriptor, we can create one
module that will add all the required dependency using 'transitive'.
Then we just need to add dependency of this module wherever
needed, this will add all the required modules transitive dependency.
This common module is the 'Aggregator module'.
• For example, we have 10 modules, modA to modJ. modP, modQ,
modR needs all 10 modules, then we can create one common
module as below,
module modulePQR{
requires transitive modA;
....
...
requires transitive modJ;
}
Then modules P, Q and R just need to add require for modulePQR
module modP{
requires transitive modulePQR;
}
The module modulePQR is the Aggregator module.
➢ Package Naming conflicts

Java 8^J9 and 11 Page 16


• 2 Jar files can contain the same package name which cause the
problem of version control and abnormal execution of the program
where as
• 2 modules cannot contain the same package name, if it is there
compiler will throw compilation error. Assume that Module A,
Module B and Module c are 3 modules and Module A and B has same
package that is pack1. Execute the below example
Module ModuleA{
Exports pack1;
}
Module ModuleB{
Exports pack1;
}
Module C{
Requires ModuleA;
Requires ModuleB;
}
• JVM is going to evaluate whether all the dependent modules are
available or not at beginning only
• Module Resolution Process: In case of traditional class path, JVM
wont check for required .class files at the beginning. While
execution of the program if JVM requires any .class file then JVM
will search in classpath and if it is available then it will load
• But in Module programming, JVM will search for required modules
in the module-path before it starts execution. If any module is
missing at the beginning only JVM will identify and won't start the
execution. That’s the reason there is no chance of getting
noclassDef found error in the middle of program execution

➢ Collection API Enhancements:


 If we want to create immutable collection using java 8 then we have
to follow the below steps.

 Here UnModifiableList or UnModifiableCollection will provide the


Immutable Collection object
 After line Collections.UnModifiableList() if we perform the l.add() or
l.remove() then below exception is thrown.

Java 8^J9 and 11 Page 17


 In Java 9, you can create immutable collections such as


immutable list, immutable set and immutable map using new
factory methods, no need to write the code like above
 The List.of() static factory methods provide a convenient way to
create immutable lists. The List instances created by these
methods have the following characteristics:
 This Of() method is overloaded method and it is present in List
interface.
 They are structurally immutable. Elements cannot be added,
removed, or replaced. Calling any mutator method will always
cause UnsupportedOperationException to be thrown
 They disallow null elements. Attempts to create them with null
elements result in NullPointerException.
 They are serializable if all elements are serializable.
 The order of elements in the list is the same as the order of the
provided arguments, or of the elements in the provided array.

➢ Diamond Operator for Anonymous Inner Class


 Before 1.5 If we want to create the collection object, we may create
like below
 List l= new ArrayList();
 Problem with this statement is that we can add any type of objects to this
list. Example: we can add String, Integer and Employee. When we add the
different objects like this the problem is that when you want to retrieve the
value we need to explicitly type cast the value. Apart from the type cast, we
also don't know what kind of object is present at which position that is type
safety.
 To resolve the type safety and type cast problem in 1.5 generics came into
picture so the above statement became like below.

Java 8^J9 and 11 Page 18


picture so the above statement became like below.
List<Integer> l= new ArrayList<Integer>();
 In the above statement <> is called as diamond operator so here when we
create the array list object we are specifying the Object type, so that we can
add only Integer objects and we cannot add any other objects. In this way
type safety is achieved. By mentioning like this when you have to get the
value we don't need to cast it to specific type.
 We can use like this Integer i=l.get(3), but the point is here we need to
specify the diamond operator with generic type for both the sides
 Change happened in 1.7 is that we don't need to specify the generic type
towards right side.
In 1.9 the change is introduced is we can use the diamond operator for
anonymous inner classes. See the code below

 Here in the above code we were able to provide the diamond operator with
generics for anonymous inner class.

➢ Stream API Enhancements


 JDK 9 adds four methods to the Stream interface.

Java 8^J9 and 11 Page 19


 First, there are two related
methods: takeWhile(Predicate) and dropWhile(Predicate). These
methods are complementary to the
existing limit() and skip() methods, but they use a Predicate rather
than a fixed integer value
takeWhile(Predicate)

 The takeWhile() method continues to take elements from the input


stream and pass them to the output stream until the test() method of
the Predicate returns true. It is also a short-circuiting intermediate
operation.
 Takes values while the filter is true, then stops
 takeWhile is similar to Limit() method.
Difference between filter and takeWhile():
 filter will remove all items from the stream that do not satisfy the
condition.
Example:

 The Output will be all the element which satisfy the condition. Output
for 1st program is : 123321
 The Output for 1st program is : 246810
 takeWhile will abort the stream on the first occurrence of an item which
does not satisfy the condition.
 Takewhile is similar to limit method. Limit method takes long as
argument. So what ever the long variable that is mentioned in limit
method, stream will limit the stream up to that argument
 Similarly takeWhile() method will take predicate interface. Once the
predicate condition false, it won't check the remaining elements.

Java 8^J9 and 11 Page 20


predicate condition false, it won't check the remaining elements.
Example:

 Output of this statement is 1,10,100,1000


 When 10000 is occurred, 10000<5000 is false so it will stop the logic
and the out put is 1,10,100,1000

 In the same example if I use filter then it will iterate all over the stream
and displays the output

 The difference between filter and take while is, when we use filter
it evaluate the condition over entire stream. In Takewhile when
the condition fails then will not check for remaining elements. As
the name suggests the stream will iterate while the condition is
true
 Other takeWhile Examples are :

dropWhile(Predicate)

 The dropWhile() method does the opposite; it drops elements from the
input stream until the test() method of the Predicate returns true. All
remaining elements of the input stream are then passed to the output
stream.It is also a short-circuiting intermediate operation.
 It is same as skip methid. Skip method takes long parameter. Till this
parameter the elements are skipped. Similarly dropWhile method skips
the elements until the condition is satisfied.
 We want to drop all elements till we encounter an element that
satisfies the predicate. From that element onwards, all the remaining
elements in the stream should be processed.
 Knowing the difference between an ordered and unordered stream is
important before getting into the takeWhile and dropWhile methods as
they operate differently for them.
 An ordered stream is one that is created out of a collection that
produces a stream with encounter order – example, List and array. Since
a list or an array is ordered, the stream created out of them is ordered.

Java 8^J9 and 11 Page 21


 For other collection sources like a HashSet or a HashMap, which
doesn’t have a guaranteed order, the stream created with them as the
source results in an unordered stream.

ofNullable()

 ofNullable() is a static method which takes one element as an


argument and returns a Stream containing that single element if the
passed element is non-null. If the passed element is null, it returns an
empty Stream

iterate()

 iterate() method is already there in Stream interface from Java 8. But, Java
9 provides another version of iterate() method which takes an extra
argument hasNext of type Predicate which decides when to terminate the
operation.
 iterate() method is also a static method.

The above condition is same as below without streams

 Here the above iterate method is taking 3 arguments, till the second
condition is satisfied the stream will iterate and does the work mentioned
in 3rd parameter.

Java 8^J9 and 11 Page 22


Java 8^J9 and 11 Page 23

You might also like