Java_9_Notes
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
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
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
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
/List -all
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
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:
To drop the method in this case you can use /drop snippet id in case when u have multiple
methods with same name
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%
JSHELL> /types
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
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
The try() automatically calls the close method (close method is present
Output is :
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.
If you execute the above code, you can get the details of current running
process.
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."
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.
• 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:
➢ 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.
➢ Aggregator Module
Here in the above code we were able to provide the diamond operator with
generics for anonymous inner class.
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.
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.
ofNullable()
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.
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.