0% found this document useful (0 votes)
4 views44 pages

Java 9 Features

Java 9 introduces several new features including private methods in interfaces, enhancements to try-with-resources, and factory methods for unmodifiable collections. It allows for improved code reusability with private methods, simplifies resource management in exception handling, and provides new ways to create immutable collections. Additionally, JSHELL is introduced as an interactive tool for instant code evaluation.

Uploaded by

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

Java 9 Features

Java 9 introduces several new features including private methods in interfaces, enhancements to try-with-resources, and factory methods for unmodifiable collections. It allows for improved code reusability with private methods, simplifies resource management in exception handling, and provides new ways to create immutable collections. Additionally, JSHELL is introduced as an interactive tool for instant code evaluation.

Uploaded by

Rakesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA 9 Version Features:

—------------------------
1. Private Methods in Interfaces
2. try-with-resources Enhancements
3. Diamond Operator Enhancement in JAVA.
4. Factory Methods for Unmodifiable Collections.
5. JSHELL
6. JPMS
7. Enhancements in Stream API
8. Process API Updations
9. JLinker
—----
—----

Private Methods in Interfaces


—------------------------------
Before the JAVA 8 version , interfaces were able to allow only
abstract methods, from JAVA 8 version onwards interfaces are able to
allow static methods, default methods along with abstract methods.

Default method is a method with “default” access modifier inside the


interfaces, it will provide initial implementation for any method that
implementation classes can override or reuse.

public interface I{
public default void meth(){
—----
}
}

In Java applications, if we want to add a new functionality to an


interface without affecting implementation classes then we have to use
“Default Methods”.

EX:
public interface Calculator{
public int add(int i, int j);
public default int sub(int i, int j){
—----
}
}
public class CalculatorImpl implements Calculator{
public int add(int i, int j){
—-----
}
}

In the JAVA 9 version we are able to declare private methods inside


the interfaces along with static methods , default methods and
abstract methods.

The main intention of the private methods inside the interfaces is to


improve code reusability in the default methods and to utilize up to
interface only, not to utilize in the implementation classes.

EX:
interface Transaction{
private void preTransaction(){
[Link]("Open Account Database.....");
[Link]("Begin Transaction.....");
}
private void postTransaction(){
[Link]("Commit / Rollback
Transation.....");
[Link]("End Transaction......");
[Link]("Close Account
Database......");
}
public default void deposit(){
preTransaction();
[Link]("*****Deposit Logic******");
postTransaction();
}
public default void withdraw(){
preTransaction();
[Link]("*****Withdraw Logic******");
postTransaction();
}
public default void transferFunds(){
preTransaction();
[Link]("*****Transafer Funds
Logic******");
postTransaction();
}
}
class TransactionImpl implements Transaction{

}
public class Main {
public static void main(String[] args) {
Transaction transaction = new TransactionImpl();
[Link]();
[Link]();

[Link]();
[Link]();

[Link]();
}
}

Open Account Database.....


Begin Transaction.....
*****Deposit Logic******
Commit / Rollback Transation.....
End Transaction......
Close Account Database......

Open Account Database.....


Begin Transaction.....
*****Withdraw Logic******
Commit / Rollback Transation.....
End Transaction......
Close Account Database......
Open Account Database.....
Begin Transaction.....
*****Transafer Funds Logic******
Commit / Rollback Transation.....
End Transaction......
Close Account Database......

try-with-resources Enhancements:
—-------------------------------
In general, in Java applications, we may use resources like Streams,
Sockets, Database Connections,.... When we perform operations with
these resources we may get exceptions, to handle these exceptions if
we use try-catch-finally then we have to use the following
conventions.

1. Declare the resources before try block.


2. Create the resources inside the try block.
3. Close the resources inside the finally block.

public class Test{


public static void main(String[] args){
BufferedReader br = null;
Socket s = null;
Connection con = null;
try{
br = new BufferedReader(new
InputStreamReader([Link]));
S = new Socket(“localhost”,4444);
con = [Link](----);
—-----
}catch(Exception e){
[Link]();
}finally{
try{
[Link]();
[Link]();
[Link]();
}catch(Exception e){
[Link]();
}
}
}
}
The above conventions are providing the following two problems
1. Developers must close the resources explicitly, it is not
guaranteed.
2. It will increase confusion when we write try-catch-finally inside
the finally block in order to write close() methods inside the
finally block.

To overcome these problems, JAVA 7 version has provided a new


enhancement in try-catch-finally syntax that is try-with-resources or
Auto-closeable resources.

In try-with-resources, JVM will close all the resources automatically


when JVM is coming out from try block.

Syntax:
try(Resource-1; Resource-2;....Resource-n;){
—----
}catch(Exception e){
—----
}

If we want to use Resources along with try-with-resources syntax then


that resources must implement [Link] marker interface
either directly or indirectly.

If we provide the resources along with try in try-with-resources


syntax then the resources reference variables are converted to final
variables internally.

public class Test{


public static void main(String[] args){
try(
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
Socket s = new Socket(“localhost”,4444);
Connection con = [Link](----);

){
—-----
}catch(Exception e){
[Link]();
}
}
}
Up to JAVA 8 version , it is not possible to declare and create
resources before try block, we must declare and create resources along
with try keyword.

IN JAVA 9 version, there is an enhancement in try-with-resources like


to declare and create the resources before try-with-resources syntax
and we can pass the resources reference variables as parameters to the
try.

Syntax:
Resource1 r1 = new Resource1();
Resource1 r2 = new Resource1();
—----
—----
Resource1 rn = new Resource1();

try(r1;r2;....rn;){
}catch(Exception e){
[Link]();
}

EX:
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
Connection con = [Link](--);
Socket s = new Socket(---);
try(
br;con;s;
){
—-----
}catch(Exception e){
[Link]();
}

EX:
import [Link].*;

public class Main {


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

BufferedReader bufferedReader = new BufferedReader(new


InputStreamReader([Link]));
FileOutputStream fileOutputStream = new
FileOutputStream("E:/abc/xyz/[Link]");
FileInputStream fileInputStream = new
FileInputStream("E:/abc/xyz/[Link]");

try (bufferedReader;fileOutputStream;fileInputStream) {
[Link]("Enter Data : ");
String data = [Link]();
[Link]([Link]());
byte[] btArray = new
byte[[Link]()];
[Link](btArray);
[Link](new String(btArray));
}catch (Exception e){
[Link]();
}
}
}

Enter Data : Welcome To Durgasoft


Welcome To Durgasoft

Diamond Operator in JAVA:


—-------------------------
IN Java applications, arrays are able to allow only homogeneous
elements of fixed size in nature, it is not flexible for the
developers.

In Java applications, if we want to represent different types of


elements or heterogeneous elements in a dynamically growable manner we
have to use Collections.

In Collections, we are able to represent heterogeneous elements , it


will reduce typed ness in java applications and it is able to provide
type unsafe operations.

In Collections, to improve typed ness and to perform type safe


operations we have to use generics.

In the case of Generics, we will provide Type Parameters along with


Collection classes in order to fix the type of elements which we want
to add to the collection objects.
CollectionName<T> refVar = new CollectionName<T>();
EX:
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<Integer> al2 = new ArrayList<Integer>();

In the above Generic Type Parameter declaration, we must use the same
type at both left side Type Parameter and Right side Type Parameter,
in this case JAVA7 version has provided a flexibility to remove Type
Parameter at right side of the expression in <>, here empty <> is
called diamond operator.

CollectionName<T> refVar = new CollectionName<>();


EX:
ArrayList<String> al1 = new ArrayList<>();
ArrayList<Integer> al2 = new ArrayList<>();

Up to JAVA 8 version, we are able to use <> for the Collection classes
in the generic classes declaration and in the Collection classes
objects creation, but it is not possible to use <> operator to the
anonymous inner classes.

In the above context, JAVA 9 version has provided an enhancement on


diamond operator like to apply <> operator for Anonymous inner classes
also.

Comparator<String> comp = new Comparator<>(){


—----
};

EX:
import [Link];
import [Link];

public class Main {


public static void main(String[] args) throws Exception {
Comparator<String> comparator = new Comparator<>() {
@Override
public int compare(String str1, String str2) {
return -[Link](str2);
}
};
TreeSet<String> treeSet = new TreeSet<>(comparator);
[Link]("FFF");
[Link]("AAA");
[Link]("EEE");
[Link]("BBB");
[Link]("DDD");
[Link]("CCC");
[Link](treeSet);

}
}

Factory Methods for Unmodifiable Collections:


—----------------------------------------------
Before JAVA 1.2 version we are able to create Collection object and we
are able to perform modifications over the Collection elements as per
the requirement, here there is no mechanism to fix the number of
elements in the Collection objects and there is no mechanism to
protect the collection elements, here protecting COllection elements
in the sense not to allow modifications like updations , remove,...
operation over the Collection elements.

To overcome the above problems JAVA 1.2 version has provided the
following methods in Collections class to make immutable Collection or
Unmodifiable Collections.

public static List unmodifiableList(List l)


public static Set unmodifiableSet(Set l)
public static Map unmodifiableMap(Map m)

After creating Immutable Collections, if we perform modifications over


the elements then JVM will raise an exception like
[Link]

import [Link];
import [Link];
import [Link];

public class Main {


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

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


[Link]("AAA");
[Link]("BBB");
[Link]("CCC");
[Link]("DDD");
[Link](list);

list = [Link](list);
[Link](list);
//[Link]("EEE"); --->
[Link]
[Link](list);

}
}

[AAA, BBB, CCC, DDD]


[AAA, BBB, CCC, DDD]
Exception in thread "main" [Link]
at
[Link]/[Link]$[Link](Collections
.java:1056)
at [Link]([Link])

EX:
import [Link];
import [Link];
import [Link];

public class Main {


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

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


[Link]("AAA");
[Link]("BBB");
[Link]("CCC");
[Link]("DDD");
[Link](set);
set = [Link](set);
[Link](set);
//[Link]("EEE"); --->
[Link]
}
}

EX:
import [Link];
import [Link];
import [Link];

public class Main {


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

Map<Integer, String> map = new HashMap<>();


[Link](1, "AAA");
[Link](2, "BBB");
[Link](3, "CCC");
[Link](4, "DDD");
[Link](map);

map = [Link](map);
[Link](map);
//[Link](3, "XXX"); --->
[Link]

}
}

In the JAVA 9 version, Java has provided the following factory methods
to make immutable List, Immutable Set and Immutable Map.

public static List<T> of(T … t)


public static Set<T> of(T … t)
public static Map<K, V> of(k1, v1, K2, V2,..... K_n, V_n)

EX:
import [Link];
import [Link];
import [Link];

public class Main {


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

List<Integer> list = [Link](10,20,30,40);


[Link](list);

Set<Integer> set = [Link](20,30,40,50);


[Link](set);

Map<Integer, String> map =


[Link](1,"AAA",2,"BBB",3,"CCC",4,"DDD");
[Link](map);

}
}

import [Link];
import [Link];
import [Link];

public class Main {


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

List<Integer> list = [Link](10,20,30,40);


[Link](list);
//[Link](50);--> [Link]

Set<Integer> set = [Link](20,30,40,50);


[Link](set);
//[Link](60);--> [Link]

Map<Integer, String> map =


[Link](1,"AAA",2,"BBB",3,"CCC",4,"DDD");
[Link](map);
//[Link](5,"EEE"); --->
[Link]

}
}
JSHELL
—-------
JSHELL is an interactive Mode to check code blocks instantly.
JSHELL is also called REPL tool

R : Read
E : Evaluate
P : Program
L : Loop

Note: JSHELL is mainly for checking the code instantly, it is not for
the development of the applications.

Before JAVA 9 version, if we want to display a simple message on


command prompt then we have to provide main class , main() and
[Link]() statements, but in JSHELL we are able to display
the message directly by using [Link]() .

To Open JSHELL we have to use the following command in the command


prompt.

JSHELL
EX:
C:\Users\Administrator>JSHELL
| Welcome to JShell -- Version 17.0.6
| For an introduction type: /help intro

jshell>

To get Introduction to JSHELL we have to use the following command on


command prompt.

/help intro

EX:
jshell> /help intro
|
| intro
| =====
|
| The jshell tool allows you to execute Java code, getting immediate
results.
| You can enter a Java definition (variable, method, class, etc),
like: int x = 8
| or a Java expression, like: x + x
| or a Java statement or import.
| These little chunks of Java code are called 'snippets'.
|
| There are also the jshell tool commands that allow you to
understand and
| control what you are doing, like: /list
|
| For a list of commands: /help

jshell>

If we want to get all the commands which are supported by JSHELL we


have to use the following command.

/help

EX:
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
| /drop <name or id>
| delete a source entry
| /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 type declarations
| /imports
| list the imported items
| /exit [<integer-expression-snippet>]
| exit the jshell tool
| /env [-class-path <path>] [-module-path <path>] [-add-modules
<modules>] ...
| view or change the evaluation context
| /reset [-class-path <path>] [-module-path <path>] [-add-modules
<modules>]...
| reset the jshell tool
| /reload [-restore] [-quiet] [-class-path <path>] [-module-path
<path>]...
| reset and replay relevant history -- current or previous (-
restore)
| /history [-all]
| history of what you have typed
| /help [<command>|<subject>]
| get information about using the jshell tool
| /set editor|start|feedback|mode|prompt|truncation|format ...
| set configuration information
| /? [<command>|<subject>]
| get information about using the jshell tool
| /!
| rerun last snippet -- see /help rerun
| /<id>
| rerun snippets by ID or ID range -- see /help rerun
| /-<n>
| rerun n-th previous snippet -- see /help rerun
|
| For more information type '/help' followed by the name of a
| command or a subject.
| For example '/help /list' or '/help intro'.
|
| Subjects:
|
| intro
| an introduction to the jshell tool
| keys
| a description of readline-like input editing
| id
| a description of snippet IDs and how use them
| shortcuts
| a description of keystrokes for snippet and command
completion,
| information access, and automatic code generation
| context
| a description of the evaluation context options for /env
/reload and /reset
| rerun
| a description of ways to re-evaluate previously entered
snippets

jshell>

IN JSHELL, we are able to display messages directly, we are able to


evaluate the expressions directly.
EX:
jshell> "Welcome to JSHELL";
$1 ==> "Welcome to JSHELL"

jshell> $1
$1 ==> "Welcome to JSHELL"

jshell> String str = "Welcome To JSHELL";


str ==> "Welcome To JSHELL"

jshell> str
str ==> "Welcome To JSHELL"

jshell> [Link]("Welcome To Durgasoft");


Welcome To Durgasoft

jshell> [Link](str);
| Error:
| package SYstem does not exist
| [Link](str);
| ^--------^

jshell> [Link](str);
Welcome To JSHELL

jshell> 10+20
$7 ==> 30

jshell> int a = 10;


a ==> 10

jshell> int b = 20;


b ==> 20
jshell> a*b
$10 ==> 200

jshell> [Link](a-b);
-10

jshell>

JSHELL has some default packages internally, no need to import these


packages explicitly, directly we can use classes and interfaces of
those packages.

If we want to know the default packages which are available in JSHELL


we have to use the following command.

/imports

EX:
jshell> /imports
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*
| import [Link].*

jshell>

EX:
jshell> List<String> list = [Link]("AAA", "BBB","CCC","DDD");
list ==> [AAA, BBB, CCC, DDD]

jshell> list
list ==> [AAA, BBB, CCC, DDD]

jshell> List<String> list1 = [Link]().map(str-


>[Link]()).collect([Link]
ist());
| Error:
| cannot find symbol
| symbol: method tolowerCase()
| List<String> list1 = [Link]().map(str-
>[Link]()).collect([Link]());
| ^-------------^
| Error:
| incompatible types: inference variable T has incompatible bounds
| equality constraints: [Link]
| lower bounds: [Link]
| List<String> list1 = [Link]().map(str-
>[Link]()).collect([Link]());
|
^--------------------------------------------------------------------^

jshell> List<String> list1 = [Link]().map(str-


>[Link]()).collect([Link]
i t());
list1 ==> [aaa, bbb, ccc, ddd]

jshell> list
list ==> [AAA, BBB, CCC, DDD]

jshell> list1
list1 ==> [aaa, bbb, ccc, ddd]

jshell>

In JSHELL we are able to import the packages explicitly as per the


requirement.

EX:
jshell> import [Link].*;

jshell> NumberFormat nf = [Link](new


Locale("it","IT"));
nf ==> [Link]@674dc

jshell> [Link](123456789.4567890);
$24 ==> "123.456.789,457"

jshell> Locale l = new Locale("it","IT");


l ==> it_IT
jshell> DateFormat df = [Link](0,l);
df ==> [Link]@96b32db5

jshell> [Link](new [Link]());


$27 ==> "sabato 5 agosto 2023"

jshell>

IN JSHELL, if we want to list out all the code snippets which we have
provided up to now we have to use the following command on JSHELL.

/list

EX:
jshell> /list

1 : "Welcome to JSHELL";
2 : $1
3 : String str = "Welcome To JSHELL";
4 : str
5 : [Link]("Welcome To Durgasoft");
6 : [Link](str);
7 : 10+20
8 : int a = 10;
9 : int b = 20;
10 : a*b
11 : [Link](a-b);
13 : List<String> list = [Link]("AAA", "BBB","CCC","DDD");
14 : list
15 : List<String> list1 = [Link]().map(str-
>[Link]()).collect([Link]());
16 : list
17 : list1
19 : drop d;
20 : import [Link].*;
21 : Connection con =
[Link]("jdbc:odbc:nag","system","durga");
22 : import [Link].*;
23 : NumberFormat nf = [Link](new
Locale("it","IT"));
24 : [Link](123456789.4567890);
25 : Locale l = new Locale("it","IT");
26 : DateFormat df = [Link](0,l);
27 : [Link](new [Link]());
In JSHELL, we are able to get the complete history of the JSHELL by
using the following command.

/history

EX:
jshell> /history

/help intro
/help
"Welcome to JSHELL";
$1
String str = "Welcome To JSHELL";
str
[Link]("Welcome To Durgasoft");
[Link](str);
[Link](str);
10+20
int a = 10;
int b = 20;
a*b
[Link](a-b);
Date d = new Date();
/imports
List<String> list = [Link]("AAA", "BBB","CCC","DDD");
list
List<String> list1 = [Link]().map(str-
>[Link]()).collect([Link]());
List<String> list1 = [Link]().map(str-
>[Link]()).collect([Link]());
list
list1
/help
import [Link].*;
drop d;
import [Link].*;
Connection con =
[Link]("jdbc:odbc:nag","system","durga");
import [Link].*;
NumberFormat nf = [Link](new Locale("it","IT"));
[Link](123456789.4567890);
Locale l = new Locale("it","IT");
DateFormat df = [Link](0,l);
[Link](new Date());
[Link](new [Link]());
/list
/history

jshell>

Variables in JSHELL:
In JSHELL , there are two types of variables.
1. Implicit variables or Scratch variables
2. Explicit Variables

Implicit variables / Scratch variables: These variables are provided


by the JSHELL internally when we declare data or when we perform
operations.

IN JSHELL, implicit Variables are provided in the following pattern.

$num

We are able to access the data from Implicit variables by using


variable names.

EX:
jshell> "abc"
$1 ==> "abc"

jshell> 10+20
$2 ==> 30

jshell> "abc"+"xyz"
$3 ==> "abcxyz"

jshell> $1
$1 ==> "abc"

jshell> $2
$2 ==> 30

jshell> $3
$3 ==> "abcxyz"
Explicit Variables:These variables must be declared by the developers
explicitly.

We can access explicit variables by using variable names directly.

EX:
jshell> String firstName = "Durga";
firstName ==> "Durga"

jshell> String lastName = "N";


lastName ==> "N"

jshell> int age = 22;


age ==> 22

jshell> String qual = "BTech";


qual ==> "BTech"

jshell> [Link](firstName+","+lastName+","+age+","+qual);
Durga,N,22,BTech

jshell> firstName
firstName ==> "Durga"

jshell> lastName
lastName ==> "N"

jshell> age
age ==> 22

jshell> qual
qual ==> "BTech"

jshell>

If we want to display all variables which are used in JSHELL up to now


we have to use the following command.

/vars

jshell> /vars
| String $1 = "abc"
| int $2 = 30
| String $3 = "abcxyz"
| String firstName = "Durga"
| String lastName = "N"
| int age = 22
| String qual = "BTech"

jshell>

If we want to get an individual variable name in JSHELL we have to use


the following command.

/vars varName

jshell> /vars firstName


| String firstName = "Durga"

jshell> /vars qual


| String qual = "BTech"

jshell>

If we want to drop a particular variable from JSHELL we have to use


the following command.

drop varName

jshell> drop firstName


| replaced variable firstName, however, it cannot be referenced until
class drop is declared

jshell> /vars
| String $1 = "abc"
| int $2 = 30
| String $3 = "abcxyz"
| String lastName = "N"
| int age = 22
| String qual = "BTech"
| drop firstName = (not-active)

jshell>
Methods in JSHELL:
It is a set of instructions as a single unit representing a particular
action.

In JSHELL we can declare methods without having any class declaration.

We can access the methods directly by using method names like local
methods.

EX:
jshell> void sayHello(){
...> [Link]("Hello User!");
...> }
| created method sayHello()

jshell> sayHello();
Hello User!

jshell> void welcome(String name){


...> [Link]("Hello "+name);
...> [Link]("Welcome To JSHELL");
...> }
| created method welcome(String)

jshell> welcome("Durga");
Hello Durga
Welcome To JSHELL

jshell> int add(int fval, int sval){


...> return fval + sval;
...> }
| created method add(int,int)

jshell> add(20,5);
$22 ==> 25

jshell> int sub(int fval, int sval){


...> return fval-sval;
...> }
| created method sub(int,int)

jshell> sub(10,5);
$24 ==> 5
If we want to get all the declared methods from JSHELL then we have to
use the following command.

/methods

jshell> /methods
| void sayHello()
| void welcome(String)
| int add(int,int)
| int sub(int,int)

jshell>

If we want to get a particular method details we have to use the


following command.

/methods methodName

jshell> /methods sayHello


| void sayHello()

jshell> /methods welcome


| void welcome(String)

jshell> /methods add


| int add(int,int)

If we want to drop a particular method from JSHELL we have to use the


following command.

/drop methodName

jshell> /drop sayHello


| dropped method sayHello()
| dropped variable sayHello

jshell> /methods
| void welcome(String)
| int add(int,int)
| int sub(int,int)
IN JSHELL, we are able to prepare methods with the same name and with
the different parameters list.

jshell> int mul(int i, int j){


...> return i*j;
...> }
| created method mul(int,int)

jshell> int mul(int i, int j, int k){


...> return i*j*k;
...> }
| created method mul(int,int,int)

jshell> mul(10,20);
$28 ==> 200

jshell> mul(10,20,30);
$29 ==> 6000

Classes, Abstract classes, interfaces and enums in JSHELL:


In JSHELL , it is possible to declare classes, abstract classes,
interfaces and enums.

EX:

jshell> class Employee{


...> int eno;
...> String ename;
...> float esal;
...> String eaddr;
...> Employee(int eno, String ename, float esal, String eaddr){
...> [Link] = eno;
...> [Link] = ename;
...> [Link] = esal;
...> [Link] = eaddr;
...> }
...> public void getEmployeeDetails(){
...> [Link]("Employee Number : "+eno);
...> [Link]("Employee Name :
"+ename);
...> [Link]("Employee Salary : "+esal);
...> [Link]("Employee Address :
"+eaddr);
...> }
...>
}

...> }
...>

| created class Employee

jshell> Employee emp = new Employee(111,"AAA",5000,"Hyd");


emp ==> Employee@2530c12

jshell> [Link]();
Employee Number : 111
Employee Name : AAA

jshell> [Link]();
Employee Number : 111
Employee Name : AAA

jshell> [Link]();
Employee Number : 111
Employee Name : AAA

jshell>

IN general, JSHELL is suggestible for simple code snippets only, not


suggestible for lengthy programs. If we want to prepare java
applications then we have to use Editors or IDEs.

JSHELL has its own editor internally , it is the same as notepad, to


open an editor in JSHELL we have to use the following command.

/edit

If we use the above command then JSHELL Editor will open with the list
of data that we provided , where we can modify, delete,... finally we
have to click on the “Accept” button to reflect all modifications to
JSHELL.

In JSHELL, JSHELL provided editor is not good for development, it is


possible to set our own editors in place of JSHELL default editor.
IN JSHELL, to set our own editor we have to use the following command.

/set editor “[Link] file location”.

EX:
jshell> /set editor "C:/Program Files/EditPlus/[Link]"
| Editor set to: C:/Program Files/EditPlus/[Link]

jshell> /edit

EX:

jshell> /set editor "C:/IntelliJ IDEA Community Edition


2023.1.2/bin/[Link]"
| Editor set to: C:/IntelliJ IDEA Community Edition
2023.1.2/bin/[Link]

jshell> /edit
| created class ToyotoCar

jshell> Car car = new ToyotoCar();


car ==> ToyotoCar@4cdf35a9

jshell> [Link]();
Innova Crysta.......

jshell> [Link]([Link]);
AVAILABLE

jshell> [Link]([Link]);
BUSY

jshell> [Link]([Link]);
IDLE

IN JSHELL, we can save the current content in a file by using the


following command.

/save fileNameAndLocation

jshell> /save E:/abc/xyz/[Link]


In JSHELL, we can get data from a particular file to JSHELL by using
the following command.

/open fileNameLocation

jshell> /open E:/abc/xyz/[Link]

jshell> getStudentDetails();
STudent Details.....

Jar Files in JSHELL:


IN JSHELL code if we want to use some third party libraries which are
available in JAR files then we have to set classpath environment
variable to jar file, to set classpath environment variable to jar
file we have to use the following command.

/env -class-path jarFileNameAndLocation

/env -class-path E:/abc/xyz/[Link]

EX:
E:/abc/xyz/[Link]
import [Link].*;
class EmployeeDao{
public void getEmployeeDetails(){
Connection con = null;
try{
[Link]("[Link]");
con =
[Link]("jdbc:mysql://localhost:3306/durgadb","roo
t","root");
Statement st = [Link]();
ResultSet rs = [Link]("select * from emp1");
[Link]("ENO\tENAME\tESAL\tEADDR");
[Link]("-----------------------------");
while([Link]()){
[Link]([Link]("ENO")+"\t");
[Link]([Link]("ENAME")+"\t");
[Link]([Link]("ESAL")+"\t");
[Link]([Link]("EADDR")+"\n");
}
}catch(Exception e){
[Link]();
}finally{
try{
[Link]();
}catch(Exception e){
[Link]();
}
}
}
}

jshell> /open E:/abc/xyz/[Link]


jshell>/env -class-path E:/abc/xyz/[Link]
jshell> [Link]();
ENO ENAME ESAL EADDR
-----------------------------
111 AAA 5000.0 Hyd
222 BBB 6000.0 Hyd
333 CCC 7000.0 Hyd
444 DDD 8000.0 Hyd
555 EEE 9000.0 Hyd

IN JSHELL, we can provide our own messages as startup messages by


using the following command.

jshell -v –startup FileNameLocation

EX:
[Link]
String wishMessage = "Good Evening Nagoor";
[Link](wishMessage);

C:\Users\Administrator>jshell -v --startup E:/abc/xyz/[Link]


Good Evening Nagoor
| Welcome to JShell -- Version 17.0.6
| For an introduction type: /help intro
JPMS:
—-----
JPMS: Java Platform Module System

In general, in Java applications, we are able to write programs by


using classes and interfaces, these classes and interfaces are
combined in the form of packages, these packages combined in the form
of JAR files, here we will use these jar files to execute the
applications.

In the above context, JAR files are providing modularization in the


applications .

The above approach is able to provide the following problems.

1. Unexpected NoClassFoundError Exception.


2. Version Conflict.
3. Security Problems
4. Monolithic Arch and Larger in Size
—----
—----
Unexpected NoClassFoundError Exception:
—--------------------------------------
In general, we are able to create more number of jar files as per the
application requirement, where all these jar files are interdependent,
where to execute the application we must keep all the jar files in the
“classpath”, in this context, if any jar file is missing in the
classpath environment variable then JVM will provide
[Link] Exception.

[Link]
package p1;
import p2.*;
public class Employee{
public void getEmpDetails(){
[Link]("Employee Details......");
Account account = new Account();
[Link]();
}
}

[Link]
package p2;
import p3.*;
public class Account{
public void getAccountDetails(){
[Link]("Account Details.....");
Bank bank = new Bank();
[Link]();
}
}

[Link]
package p3;
public class Bank{
public void getBankDetails(){
[Link]("Bank Details.....");
}
}

D:\java6\jpms\app01>javac -d . *.java
D:\java6\jpms\app01>jar -cvf [Link] p1
D:\java6\jpms\app01>jar -cvf [Link] p2
D:\java6\jpms\app01>jar -cvf [Link] p3

Delete [Link], [Link], [Link] , p1, p2, p3 from the


current location.

[Link]
import p1.*;
class Test{
public static void main(String[] args){
Employee employee = new Employee();
[Link]();
}
}

D:\java6\jpms\app01>javac [Link]
[Link]: error: package p1 does not exist
import p1.*;
^
[Link]: error: cannot find symbol
Employee employee = new Employee();
^
symbol: class Employee
location: class Test
[Link]: error: cannot find symbol
Employee employee = new Employee();
^
symbol: class Employee
location: class Test
3 errors

D:\java6\jpms\app01>set classpath=[Link];

D:\java6\jpms\app01>javac [Link]

D:\java6\jpms\app01>java Test
Employee Details......
Exception in thread "main" [Link]: p2/Account

D:\java6\jpms\app01>set classpath=[Link];[Link];

D:\java6\jpms\app01>javac [Link]

D:\java6\jpms\app01>java Test
Employee Details......
Account Details.....
Exception in thread "main" [Link]: p3/Bank

D:\java6\jpms\app01>set classpath=[Link];[Link];[Link];

D:\java6\jpms\app01>javac [Link]

D:\java6\jpms\app01>java Test
Employee Details......
Account Details.....
Bank Details.....

To overcome the above NoClassDeFoundError exception in java


applications, we have to use JPMS , in the case of JPMS all
dependencies are checked at starting point application execution only.
If any dependency does not exist then JPMS will not start application
execution.
Version Conflict:
—------------------
In Java applications, we may prepare a number of jar files which are
depending on each other. If we want to use these jar files in our
present application then we have to keep all these jar files in
“classpath”.

When we set classpath to multiple jar files, there is no guarantee


whether all the jar files are prepared in the same current Java
version that we are using for the present java application , there we
will get the “Version Conflict” problem at runtime of the application.

EX:
[Link]
package p1;
import p2.*;
public class Employee{
public void getEmpDetails(){
[Link]("Employee Details......");
Account account = new Account();
[Link]();
}
}

[Link]
package p2;
import p3.*;
public class Account{
public void getAccountDetails(){
[Link]("Account Details.....");
Bank bank = new Bank();
[Link]();
}
}

[Link]
package p3;
public class Bank{
public void getBankDetails(){
[Link]("Bank Details.....");
}
}

[Link]
import p1.*;
class Test{
public static void main(String[] args){
Employee employee = new Employee();
[Link]();
}
}

D:\java6\jpms\app01>javac -d . [Link]

D:\java6\jpms\app01>jar -cvf [Link] p3


added manifest
adding: p3/(in = 0) (out= 0)(stored 0%)
adding: p3/[Link](in = 407) (out= 280)(deflated 31%)

D:\java6\jpms\app01>set path=C:\java\jdk1.7.0_80\bin;

D:\java6\jpms\app01>javac -d . [Link]

D:\java6\jpms\app01>jar -cvf [Link] p2


added manifest
adding: p2/(in = 0) (out= 0)(stored 0%)
adding: p2/[Link](in = 484) (out= 328)(deflated 32%)

D:\java6\jpms\app01>set path=C:\java\jdk-17\bin;

D:\java6\jpms\app01>javac -d . [Link]

D:\java6\jpms\app01>jar -cvf [Link] p1


added manifest
adding: p1/(in = 0) (out= 0)(stored 0%)
adding: p1/[Link](in = 490) (out= 333)(deflated 32%)

D:\java6\jpms\app01>set path=C:\java\jdk1.8.0_202\bin;

D:\java6\jpms\app01>set classpath=[Link];[Link];[Link];

D:\java6\jpms\app01>javac [Link]
[Link]: error: cannot access Employee
Employee employee = new Employee();
^
bad class file: [Link](p1/[Link])
class file has wrong version 61.0, should be 52.0
Please remove or make sure it appears in the correct subdirectory
of the classpath.
1 error

D:\java6\jpms\app01>

Security Problems:
In Java applications, we are able to use multiple jar files, we are
able to set them in the “classpath” environment variable, in this
context, if we set any JAR file in the classpath environment variable
then we are able to use all packages which are available in jar file,
there is no chance to hide some of the package, here JAR files are not
providing Security to the packages.

JPMS is able to provide security to the packages, because JPMS is able


to export the required packages to the other modules and it is able to
hide some other packages to the other modules. So JPMS is able to
provide security for the applications.

Monolithic Arch and Larger in Size


—----------------------------------
IN general, Java is following Monolithic Arch, that is all the
packages are available in a single jar file , to execute any simple
java program and if we set the jar file in the classpath environment
variable then all the packages which are available in the jar file are
loaded with or without the requirement, it will increase more loading
time, it will reduce application performance.

In the above context, JPMS is able to provide a solution , it is able


to load only the required packages, it is unable to load unnecessary
packages.

In JPMS , we will create and use Modules in place of JAR files.

Module: Module is a folder or a package with the module configuration


file, where module configuration file is [Link] , it is able
to provide module information like the packages names which we are
using from other modules and the packages names which we want to
expose to the other modules.
Steps to prepare First JPMS application:
—------------------------------------------
1. Create application directory Structure.
2. Create the Java files as per the application requirement.
3. Create Module Configuration file.
4. Compile the module.
5. Execute the module.

Create application directory Structure:


D:\java6\jpms
app01
|------src
| |-----moduleA
| | |------pack1
| | | |----[Link]
| | |------[Link]

Create the Java files as per the application requirement.


[Link]
package pack1;
public class Test{
public static void main(String[] args){
[Link]("Welcome To JPMS Programming.....");
}
}

Create Module Configuration file:


[Link]
module moduleA{
}

Compile the module:


To compile a module we have to use the following javac command.

javac –module-source-path srcFolder -d OutputFolder -m moduleName

EX:

D:\java6\jpms\app01>javac --module-source-path src -d out -m moduleA

If we compile the module by using the above command then the Compiler
will create the output folder like below.

D:\java6\app01
Out
|------moduleA
|------pack1
| |------[Link]
|------[Link]

Execute the application:


To execute a Java application which has a module we have to use the
following command.

java —-module-path outputFolder -m


moduleName/[Link]
EX: java —-module-path out -m moduleA/[Link]

Note: In JPMS applications, [Link] is mandatory, if we


prepare a module without [Link] file then the compiler will
raise an error like “error: module moduleA not found in module source
path”.

Note: IN JPMS , it is not suggestible to provide digits/numbers in the


moduleNames as suffixes. If we provide digits as suffix for module
name then we are able to get the following warning message.

src\module1\[Link]: warning: [module] module name


component module1 should avoid terminal digits
module module1{

In general, in JPMS applications we are able to prepare more than one


module and we are able to access the packages from one module to
another module.

If we want to access one module package in another module then we have


to use the following attributes in the module configuration file.

1. exports
2. requires

Where ‘exports’ attribute will be used in the module configuration


file of a module whose packages are exposed to the other modules in
order to use.
[Link]
module moduleA{
exports pack1, pack2, pakc3;
}

Where ‘requires’ attribute will be used in the module configuration


file of a module which we want to access the packages of some other
module that exports the packages.

[Link]
module moduleB{
requires moduleA;
}

EX:
D:\java6\jpms
app02
|-----src
| —------moduleEmp
| |-------com
| | |---durgasoft
| | | |-------emp
| | | | |------[Link]
| |-------[Link]
|
|--------moduleTest
|--------com
| |-----durgasoft
| | |------test
| | | |-----[Link]
|---------[Link]

appo2/src/moduleEmp/com/durgasoft/emp/[Link]
package [Link];
public class Employee{

private int eno;


private String ename;
private float esal;
private String eaddr;
public Employee(int eno, String ename, float esal, String eaddr){
[Link] = eno;
[Link] = ename;
[Link] = esal;
[Link] = eaddr;
}

public void getEmpDetails(){


[Link]("Employee Details");
[Link]("-------------------------");
[Link]("Employee Number : "+eno);
[Link]("Employee Name : "+ename);
[Link]("Employee Salary : "+esal);
[Link]("Employee Address : "+eaddr);
}
}

app02/src/moduleEmp/[Link]
module moduleEmp{
exports [Link];
}

app02/src/moduleTest/com/durgasoft/test/[Link]
package [Link];
import [Link].*;
public class Test{
public static void main(String[] args){
Employee emp = new Employee(111, "Durga", 5000, "Hyd");
[Link]();
}
}

[Link]
module moduleTest{
requires moduleEmp;
}

D:\java6\jpms\app02>javac --module-source-path src -d out -m


moduleEmp,moduleTest

D:\java6\jpms\app02>java --module-path out -m


moduleTest/[Link]
Employee Details
-------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 5000.0
Employee Address : Hyd

D:\java6\jpms\app02>

EX:

moduleEmp Elements:
[Link]
package [Link];
public class Employee{

private int eno;


private String ename;
private float esal;
private String eaddr;

public Employee(int eno, String ename, float esal, String eaddr){


[Link] = eno;
[Link] = ename;
[Link] = esal;
[Link] = eaddr;
}

public void getEmpDetails(){


[Link]("Employee Details");
[Link]("-------------------------");
[Link]("Employee Number : "+eno);
[Link]("Employee Name : "+ename);
[Link]("Employee Salary : "+esal);
[Link]("Employee Address : "+eaddr);
}
}

[Link]
module moduleEmp{
exports [Link];
}

moduleStd Elements:
[Link]
package [Link];
public class Student{

private String sid;


private String sname;
private String saddr;

public Student(String sid, String sname, String saddr){


[Link] = sid;
[Link] = sname;
[Link] = saddr;
}

public void getStudentDetails(){


[Link]("Student Details");
[Link]("------------------------");
[Link]("Student Id : "+sid);
[Link]("Student Name : "+sname);
[Link]("Student Address : "+saddr);
}
}

[Link]
module moduleStd{
exports [Link];
}

moduleTest elements:
[Link]
package [Link];
import [Link].*;
import [Link].*;
public class Test{
public static void main(String[] args){
Student std = new Student("S-111", "Durga", "Hyd");
[Link]();
[Link]();

Employee emp = new Employee(111,"Durga", 50000, "Hyd");


[Link]();

}
}

[Link]
module moduleTest{
requires moduleEmp;
requires moduleStd;
}

D:\java6\jpms\app03>javac --module-source-path src -d out -m


moduleEmp,moduleStd,moduleTest

D:\java6\jpms\app03>java --module-path out -m


moduleTest/[Link]
Student Details
------------------------
Student Id : S-111
Student Name : Durga
Student Address : Hyd

Employee Details
-------------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd

D:\java6\jpms\app03>

Note: IN JPMS, a module exports its packages but another module is


trying to use the exported packages without providing ‘requires
moduleName’ attribute then the compiler will raise an error like
“package packageName is not visible”.

Note: In JPMS, module does not exports its packages and if we use that
packages in other modules through requires then the compiler will not
raise any error, but JVM will raise an exception like “
[Link]”.

10. Enhancements in Stream API


11. Process API Updations
12. JLinker

You might also like