Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
288 views

Corejava Paid Notes

Uploaded by

sanket gadakh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
288 views

Corejava Paid Notes

Uploaded by

sanket gadakh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 755

CORE JAVA MATERIAL

BY
NAGOOR BABU
FROM
DURGA SOFT

1
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java History

Java Details

Home :SUN Mc Systems.[ Oracle Corporation]


Author :James Gosling.
Objective :To prepare simple electronic consumer goods.
Project :Green
First Version :JDK1.0 [1996,Jan-23rd]
Used version :some org JDK5.0, some other JAVA6, JAVA7
Latest Version : JAVA7,JAVA8, This April- JAVA9
Type of Software :open source software.
Strong Features :Object-oriented, Platform Independent,Robust, Portable, Dynamic,
Secure.......

Version Code Name Enhancements


--------------------------------------------------------------------------------------------------------------------
1.JDK1.0[Jan,23,1996] OAK Language Introduction

2.JDK1.1[Feb,19,1997] ---- RMI,JDBC,Reflection API ,Java


Beans,Inner classes

3.JDK1.2[Dec,8,1998] Playground Strictfp,Swing,CORBA,Collection Framework

4.JDK1.3[May,8,2000] Kestrel Updations on RMI,JNDI

5.JDK1.4[Feb,6,2002] Merlin Regular Expression, NIO, asser Keyword,JAXP,...

6.JDK5.0[Sep,30,2004] Tiger Autoboxing, var-arg method,static import,


Annotations ,..

7.JAVA SE6[Dec,11,2006] Mustang JDBC4.0,GUI updations, Console

8.JAVA SE7[Jul,28,2011] Dolphin Strings in switch,'_' symbol in literals,try-with-


resources
9.JAVA SE8[Mar,18,2014] spider Interface improvements,Lambda Expression, Date-
Time API, Updations on Collections
2
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Differences between Java and others[C ande C++]?

1.C and C++ are static programming languages but JAVA is dynamic programming language:

If any programming language allows memory allocation for primitive data types at compilation time
[Static Time] then that programming language is called as Static Programming language.
EX: C and C++.

In C and C++ applications, memory will be allocated for primitive data types at compilation time only,
not at runtime.

If any programming language allows memory allocation for primitive data types at runtime, not at
compilation time then that programming language is called as Dynamic Programming Language.
EX: JAVA

In java applications, memory will be allocated for primitive data types at runtime only, not at
compilation time.

Note: In Java applications, memory will be allocated for primitive data types at the time of creating
objects only, in java applications, objects are created at runtime only.

2.Pre-Processor is required in C and C++ , but, Pre-Processor is not required in Java:

In case of C and C++, the complete predefined library is provided in the form of header files

EX:
stdio.h
conio.h
math.h
---
----

If we want to use predefined library in C and C++ applications, we have to include header files in C
and C++ applications, for this, we have to use #include<> statement.

EX:
#include<stdio.h>
#include<conio.h>
#include<math.h>
3
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we compile C and C++ applications then Pre-Processor will perform the following actions.

1.Pre-Processor will recognize all #include<> statement.


2.Pre-Processor will take all the specified header files from #include<> statements.
3.Pre-Processor will check whether the specified header files are existed or not in C and C++
softwares.
4.If the specified header files are not existed the Pre-Processor will generate some error messages.
5.If the specified header files are existed then Pre-Processor will load the specified header files to the
memory, this type of loading predefined library at compilation time is called as "Static Loading".

In C and C++ applications, Pre-Processor is required to recognize #include<> statements inorder to


load header files to the memory.

--- Diagram-1-----

In java , the complete predefined library is provided in the form of classes and interfaces in packages

EX:
java.io
java.util
java.sql

If we want to use predefined library in java applications then we have to include packages in java
application, for this we have to use "import" statements

EX:
import java.io.*;
import java.util.*;
import java.sql.*;

If we compile java program then compiler will perform the following actions.

1.Compiler will recognize all the import statements.


2.Compiler will take the specified package names from import statements.
3.Compiler will check whether the specified packages are existed or not in java software.
4.If the specified packages are not existed in java predefined library then compiler will rise an error
"package xxx does not exist".
5.If the specified packages are existed in java predefined library then Compielr will not rise any error
and compiler will not load any package content to the memory.
4
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


While executing java program, when JVM[Java Virtual Machine] encounter any class or interface
from the specified package then only JVM will load the required classes and interfaces to the memory
at runtime, loading predefined library at runtime is called as "Dynamic Loading".

Pre-Processor is not required in JAVA , because, java does not include header files and #include<>
statements, alternativily, JAVA has clases and interfaces in the form of packages and import
statements.

--- Diagram-2----

Q)What are the differences between #include<> statement and import statement?

Ans:

1. #include<> statement is available upto C and C++.


import statement is available upto JAVA.

2. #include<> statements are used to include the predefined library which is available in the form of
header files.
import statements are used to include the predefined library which are available in the form of
packages.

3. #include<> statement is providing static loading.


import statement is providing dynamic loading.

4. #include<> statements are recognized by Pre-Processor.


import statements are recognized by both Compiler and JVM.

5. By using Single #include<> statement we are able to include only one header file.

EX:
#include<stdio.h>
#include<conio.h>
#include<math.h>

By using single import statement we are able to include more than one class or more than one
interface of the same package.

EX:
5

import java.io.*;
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.C and C++ are platform dependent programming languages, but, JAVA is platform Independent
programming language:

Q)What are the differences between .exe file and .class file?

Ans:

1. .exe file is available upto C and C++ only.


.class file is available upto Java.

2. .exe file contains directly executable code.


.class file contains bytecode, it is not executable code directly, it is an intermediate code.

3. .exe file is platform dependent file.


.class file is platform independent file.

4. .exe file is less secured file.


.class file is more secured file.

********** Completed Upto This*********

4.Pointers are existed in C and C++, but, Pointers are not existed in Java:

Q)What are the differences between pointer variables and referece variables?

Ans:
1. Pointer variables are available upto C and C++.
Reference variables are available upto JAVA mainly.

2. Pointer variables are able to refer a block of memory by storing its address locations.

Reference variables are able to refer a block of memory[Object] by storing object reference values,
where Object reference value is hexa decimal form of hashcode, where hashcode is an unique
identity provided by Heap manager.

3. Pointer variables are recognized and initialized at compilation time.

4. Reference variables are recognized and initialized at runtime.

5.Multiple inheritance is not possible in Java:


6

1.Single Inheritance
Page

2.Multiple Inheritance

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6.Destructors are required in C++, but, Destructors are not required in JAVA:

Create Objects----> Constructors


Destroy object----> Destructors

C++: To destroy objects developers must use destructors.

Java: Garbage Collector

Note: Developers are able to destro objects explicitly also

7.Operator Overloading is not supported in Java:

Object Oriented Features

1.Class
2.Object
3.Encapsulation
4.Abstraction
5.Inheritance
6.Polymorphism
7.Message Passing

Polymorphism:

If one thing is existed in more than one form then it is called as Polymorphism.

Polymorphism is a Greak word, where Poly means many and morphism means structers or forms.

1.Static Polymorphism
2.Dynamic Polymorphism

1.Static Polymorphism:
If polymorphism is existed at compilation time then it is called as Static Polymorhism.

EX: Overloading.

2.Dynamic Polymorphism:
If the polymorphism is existed at runtime then that polymorphismn is called as Dynamic
Polymorphism.
7
Page

EX: Overriding

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Overloading:
1.Method Overloading
2.Operator Overloading

1.Method Overloading:
If we declare more than one method with the same name and with the different parameter list
then it is called as Method Overloading

EX:
class A{
void add(int i, int j){

}
void add(float f1, float f2){

}
void add(String str1, String str2){

}
}

2.Operator Overloading:
If we define more than one functionality for any single operator then it is called as Operator
Overloding.

EX:
int a=10;
int b=20;
int c=a+b;// + is for Arithmetic Addition.
System.out.println(c);// 30

String str1="abc";
String str2="def";
String str3=str1+str2;// + is for String concatination.
System.out.println(str3);// abcdef

1.Operator overloading is very rarely used feature in application development.


2.Operator overloading is a bit confusion oriented feature.
Note:
In java programming language, some of the few predefiend operators are declared as overloaded
8

operators with fixed functionalities implicitly as per JAVA requirement, but, JAVA has not provided
Page

any environment explicitly to perform operator overloading at developers level.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: +, *, %,....

8.C and C++ are following Call By Value and Call by reference parameter passing mechanisms, but,
JAVA is following only call by value parameter passing mechanism:

primitive data: byte, short, int, long, float, double, boolean, char

Address locations

Pointer variable: Call by reference

JAVA: ref var call by value only,--->

9.In C and C++ , integers will take only 2 bytes of memory and characters will take 1 byte of memory,
but, in JAVA integers will take 4 bytes of memory and characters will take 2 bytes of memory:

C and C++:
Memory allocation for primitive data types is variable depending on the OS which we used.

JAVA:
Memory allocation for primitive data types is fixed irrespective of the operating system which we
used.

Primitives Sizes
---------- ------
byte ------> 1 byte
short------> 2 bytes
int--------> 4 bytes
long-------> 8 bytes
float------> 4 bytes
double-----> 8 bytes
char-------> 2 bytes
boolean----> 1 bit

Q)In case of C and C++, characters will take only 1 byte of memory then what is the required for
JAVA to assign two bytes of memory for characters?

Ans:
In case of C and C++, all the characters are represented in the form of ASCII values, here to store
ASCII values one byte of memory is sufficient.
9

In case of JAVA, all the characters are represented in the form UNICODE values, to store UNICODE
Page

value 2 bytes of memory is required.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)What is UNICODE and What is the purpose of UNICODE?

Ans:
UNICODE is one of the character representation, it is universally accepted code and it able to
represent all the alphabet from all the natural languages like English, Hindi, Marati, chinees,
italian,...... and it will provide very good Internationalization[I18N] support.

Note: Designing java applications w.r.t the local conventions is called as Internationalization[I18N].

Java Features:
To show the nature of java programming language, JAVA has provided the following features.

1.Simple
2.Object Oriented
3.Platform independent
4.Arch Nuetral
5.Portable
6.Robust
7.Secure
8.Dynamic
9.Distributed
10.Multi Threadded
11.Interpretive
12.High Performance

1. Simple:
Java is simple programming language, because,
1.Java applications will take less memory and less execution time.
2.Java has removed all most all the confusion oriented features like pointers, multiple
inheritance,.....
3.Java is using all the simplified syntaxes from C and C++.

2. Object Oriented:
Java is an object oriented programming language, because, JAVA is able to store data in the
form of Objects only.

3. Platform Independent:
Java is platform independent programming Language, because, Java allows its applications to
10

compile on one operating system and to execute on another operating system.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4. Arch Nuetral:
Java is an Arch Nuetral Programming language, because, Java allows its applications to compile
on one H/W Arch and to execute on another H/W Arch.

5. Portable:
Java is a portable programming language, because, JAVA is able to run its applications under all
the operating systems and under all the H/W Systems.

6. Robust:
Java is Robust programming language, because,

1.Java is having very good memory management system in the form of heap memory
Management SYstem, it is a dynamic memory management system, it allocates and deallocates
memory for the objects at runtime.

2.JAVA is having very good Exception Handling mechanisms, because, Java has provided very
good predefined library to represent and handle almost all the frequently generated exceptions in
java applications.

7. Secure:
Java is very good Secure programming language, because,

1.JAVA has provided an implicit component inside JVM in the form of "Security Manager" to
provide implicit security.

2.JAVA has provided a seperate middleware service in the form of JAAS [Java Authetication
And Autherization Service] inorder to provide web security.

3.Java has provided very good predefined implementations for almost all well known network
security alg.

8. Dynamic:
If any programming language allows memory allocation for primitive data types at RUNTIME
then that programming language is called as Dynamic Programming Language.

JAVA is a dynamic programming language, because, JAVA allows memory allocation for
primitive data types at RUNTIME.
11
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


9. Distributed:
By using JAVA we are able to prepare two types of applications

a)Standalone Applications
b)Distributed Applications

a)Standalone Applications:
If we design any java application with out using client-Server arch then that java application is
called as Standalone application.

b)Distributed Applications:
If we design any java application on the basis of client-server arch then that java application is
called as Distributed application.

To prepare Distributed applications, JAVA has provided a seperate module that is "J2EE/JAVA EE".

10. Multi Threadded:


Thread is a flow of execution to perform a particular task.

There are two thread models


a)Single Thread Model
b)Multi Thread Model

a)Single Thread Model:


It able to allow only one thread to execute the complete application,it follows sequential execution,
it will take more execution time, it will reduce application performance.

b)Multi Thread Model:


It able to allow more than one thread to execute application, It follows parallel execution, it will
reduce execution time, it will improve application performance.

JAVA is following Multi Thread Model, JAVA is able to provide very good environment to create
and execute more than one thread at a time, due to this reason, JAVA is Multi threaded
Programming Language.

11. Interpretive:
JAVA is both compilative programming language and Interpretive programming language.

1.To check developers mistakes in java applications and to translate java program from High
12

level representations to low level representation we need to compile java programs


2.To execute java programs , we need an interpretor inside JVM.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


12. High Performance:
JAVA is high performance programming language due to its rich set of features like Platform
independent, Arch Nuetral, Portable, Robust, Dynamic,......

JAVA Naming Conventions:


Java is a case sensitive programming language, where in java applications, there is a seperate
recognization for lower case letters and for upper case letters.

To use lower case letters and Upper case letters seperatly in java applications, JAVA has provided
the following conventions.

1. All class names , abstract class names, interface names and enum names must be started with upper
case letter and the sub sequent symbols must also be upper case letters.

EX:
String
StringBuffer
InputStreamReader

2. All java variables must be started with lower case letters, but, the subsequent symbols must be
upper case letters.

EX:
in, out, err
pageContext, bodyContent

3. All java methods must start with lower case letter , but, the sub sequent symbols must be upper
case letters

EX:
concat(--)
forName(--)
getInputStream()

4.All java Constant variables must be provided in Upper Case letters.

EX:
MIN_PRIORITY
NORM_PRIORITY
13

MAX_PRIOITY
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5.All java package names must be provided in lower case letters

EX:
java.util
java.lang.reflect
javax.servlet.jsp.tagext

Note: All the above conventions are mandatory for predefined library, they are optional form User
defined library, but, suggestible.

EX:

1)String str=new String("abc"); ----> Valid


2)string str=new string("abc");-----> Invalid

3)class Employee{ ----> Valid and Suggestible


---
}

4)class student{ ---> valid, but, not suggestible


---
}

Java Programming Format:


1.Comment Section
2.Package Section
3.Import Section
4.Classes/Interfaces Section
5.Main Class Section

1.Comment Section:
Before starting implementation part, it is convention to provide some description about our
implementation, here to provide description about our implementation we have to use Comment
Section. Description includes author name, Objective, project details, module details, client
details,......

To provide the above specified description in comment section, we will use comments.
14
Page

There are three types of comments.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Single Line Comments
2.Multi Line Comments
3.Documentation Comments.

1.Single Line Comment:


It allows the description with in a single line.
Syntax:
// --- description------

2.Multi Line Comment:


It allows description in more than one line

Syntax:
/*
---
--description-----
----
*/

3.Documentation Comment.
It allows description in more than one page.

Syntax:
--------
/*
*----
*----
---
---
*----
*/

Note: We will use documentation comments to prepare API kind of documentations, but, it is not
suggestible. 15
Page

API kind of documentation:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


It is a document in the form of .txt file or .doc file or .pdf file or .html it includes the complete
declarative information about our programming elements like variables, methods, classes,..... which we
have used in our java file.

EX:
Employee.java
public class Employee extends Person implements Serializable, Cloneable{
puiblc String eid;
public String ename;
public float esal;
public String eaddr;

public Employee(String eid, String ename, float esal, String eaddr){


}
public Employee(String eid, String ename, float esal){
}
public Employee(String eid, String ename){
}

public void add(String eid, String ename, float esal, String eaddr){
----
}
public String search(String eid){
return "success";
}
publc void delete(String eid){
---
}
}

Employee.txt[html/pdf]

16
Page

Class : Name: Employee

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Super Class: Person
Interfaces: Serializable, Cloneable
Variables: 1) Name :eid
DataType : String
Access Mod : public

2)Name : ename
Data Type: String
Access Mod: public
----
----
Methods: 1)Name : add
Return type: void
access mod: public
parameters : eid, ename, esal, eaddr
------
Constructors: 1)Employee
----
To simpify API documentation for JAVA applications, JAVA has provided an implicit command , that
is, "javadoc".

EX: D:\javaapps\ Employee.java


public class Employee implements java.io.Serializable, Cloneable{
public String eid;
public String ename;
public float esal;
public String eaddr;
public Employee(String eid, String ename, float esal, String eaddr){
}
public Employee(String eid, String ename, float esal){
}
public Employee(String eid, String ename){
}

public void add(String eid, String ename, float esal, String eaddr){
}
public String search(String eid){
return "success";
}
public void delete(String eid){
}
17

}
Page

On Command Prompt:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


D:\javaapps>javadoc Employee.java
--- Generating xxx.html files----

To provide description[Metadata] in java programs, JDK5.0 version has provided a new feature that is
"Annotations".

Q)In java applications, to provide description we have already comments then what is the requirement
to use Annotations?
Ans:
If we provide description along with comments in java program then "Lexical Analysis" phase will
remove comments and their descriotion which we provided in java program as part of Compilation.
As per the requirement,if we want to make available our description upto .java file, upto .class file and
upto RUNTIME of our applications there we have to use "Annotations".

Note: If we provide metadata with comments then we are unable to access that metadata
programatically, but, if we provide metadata with Annotations then we are able to access that metadata
through java program.

Q)In java applications, to provide metadata at RUNTIME we are able to use XML documents then
what is the requirement to use "Annotations".
Ans:
If we use XMl documents to provide description then we are able to get the following problems.
1.We have to learn XML tech.
2.Every time we have to check whether XML documents are located properly or not.
3.Every time, we have to check whether XML documents are formatted properly or not.
4.Every time we have to check whether we are using right parsing mechanisms or not to read data
from XML documents.
To overcome all the above problems we need a java alternative , that is, Annotations.

Note: IN JAVA/J2EE applicatinos, we can utilize Annotations as an alternative to XML documents.

XML Based Tech Annotation Based Tech[XML documents Optional]


-------------- ----------------------
1.Upto JDK1.4 1.JDK5.0 and above
2.Upto JDBC3.0 2.JDBC4.0
3.Servlets2.5 3.Servlets3.0
4.Struts1.x 4.Struts2.x
5.JSF1.x 5.JSF2.x
6.EJBs2.x 6.EJBs3.x
7.Spring2.x 7.Spring3.x
----- ------
18

----- ------
Page

Package Section:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Package is the collection of related classes and interfaces as a single unit.
2.Package is a folder contains .class files representing related classes and interfaces.

Packages are able to provide some advantages in java applications

1.Modularity
2.Abstraction
3.Security
4.Reusability
5.Sharability

There are two types of packages in java

1.Predefined Packages
2.User defined Packages

1.Predefined Packages:
These packages are provided by Java programming language along with java software.

EX: java.io
java.util
java.sql
----
----

2.User defined Packages:


These packages are defined by the developers as per their application requirements.
Syntax:
package package_Name;
where package name may be
1.directly a single name
2.sub package names with . operator

EX:
package p1;
package p1.p2.p3;

If we want to use package declaration statement in java files then we have to use the following two
condition.
1.Package declaration statement must be the first statement in java file after the comment section.
2.Package name must be unique, it must not be sharable and it must not be duplicated.
19
Page

Q)Is it possible to declare more than one package statement with in a single java file?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
No, it is not possible to declare more than one package declaration statement with in a single java file,
because, package declaration statement must be first statement, in java files only one package
declaration statement must be provided as first statement.

abc.java

package p1;---> Valid


package p2;---> Invalid
package p3;---> INvalid
--
---

To provide package names, JAVA has given a convention like to include our company domain name
in reverse in package names.

EX: www.durgasoft.com
durgasoft.com
com.durgasoft
package com.durgasoft.icici.transactions.deposit;
com.durgasoft---> company domain name in reverse.
icici ----------> project name/ client name
transactions----> module name
deposit---------> sub module

3.Import Section:
The main intention of "import" statement is to make available classes and interfaces of a particular
package into the present JAVA file inorder to use in present java file.

Syntax1:
import package_Name.*;
--> It able to import all the classes and interfaces of the specified package into the present java file.

EX: import java.io.*;

Syntax2:
import package_Name.Member_Name;
--> It able to import only the specified member from the specified package into the present java file.

EX: import java.io.BufferedReader;


20
Page

Q)Is it possible to write more than one "import" statement with in a single java file?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
Yes, In a single java file, we are able to provide atmost one package declaration statement, but, we are
able to provide any no of import statements.

abc.java

package p1;
//package p2;-----> Error
//package p3;-----> Error
import java.io.*;
import java.util.*;--> No Error
import java.sql.*;---> No Error
---
----
---

Q)Is it possible to use classes and interfaces of a particular package with out importing that package?

Ans:
Yes, it is possible to use classes and interfaces of a particular package in the present java file with out
importing the respective package, but, just by using fully qualified names of the classes.

Note: Specifying class names or interface names along with their respective package names is called
as "Fully Qualified Names".

EX: java.io.BufferedReader
java.util.ArrayList
java.sql.Connection

A java program with import statement:


import java.io.*;
---
---
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
----
----

A Java program with out import statement:


java.io.BufferedReader br=new java.io.BufferedReader(new
java.io.InputStreamReader(System.in));
21
Page

4.Classes/Interfaces Section:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


The main intention of classes and interfaces is to repersent all real world entities in the form of
coding part.
EX: Account, Employee, Product, Customer, Student,......

Note: No restrictions for no of classes in a java file or in a java application, depending on the
application requirement, we are able to write any no of classes and interfaces in java applications.

5.Main Class Section:


Main Class is a java class ,it includes main() method.

The main intention of main() method is,


1.To manage application logic which we want to execute by JVM directly we have to use main()
method.
2.To define starting point and ending point to the application execution we have to use main()
method.

Syntax:
public static void main(String[] args){
----instructions----
}

Note:main() method is a conventional method with fixed prototype and with user defined
implementation part.

Steps to prepare First Java Application:


1.Install Java Software
2.Select Java Editor
3.Write Java Program
4.Save Java File
5.Compile Java File
6.Execute Java Application

22
Page

1.Install Java Software:


a) Download jdk-8-windows-i586.exe file from internet.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


b) Double click on jdk-8-windows-i586.exe file
c) Click on "Yes" button.
d) Click On "Next" button.
e) Change JDK installation location from "C:\Program Files(x86)\Java\jdk1.8.0" to
"C:\Java\jdk1.8.0" by clicking on "Change" button and "OK" button.
f ) Click on "Next" button.
g) Change JRE instrallation location from "C:\Program Files(x86)\Java\jre8" to "C:\Java\jre8"
by clicking on "Change" button and "OK" button.
h) Click on "Next" button.
i) Click on "Close" button.

After installation of JAVA software, we have to set "path" environment variable to the location where
all JDK commands are existed that is
"C:\Java\JDK1.8.0\bin" inorder to make available all JAVA commands to Operating System.

On command Prompt:
set path=C:\Java\JDK1.8.0\bin;

If we provide "path" set up like above on the command prompt then this set up is available upto the
present command prompt only, it is not available to all the command prompts.

If we want to set "path" environment variable permanently then we have to use the following steps.
1. Right Click on "Computers" or "This PC" on desktop .
2. Select "Properties".
3. Select "Advanced System Settings" hyper link.
4. Click on "Advanced" Tab[Bydefault Selected].
5. Click on "Environment VAriables.." button.
6. Goto User Variables part and click on "New" button.
7. Provide the following details.
variable name: path
variable value: C:\Java\jdk1.8.0\bin";
8. Click on "Ok" button.
9. Click on "OK" button.
10. Click on "OK" button.
23
Page

Q)If we set all three versions[JAVA6,JAVA7,JAVA8] to the "path" environment variable then which
version will come to the command prompt?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
If set all JAVA6, JAVA7, JAVA8 versions to "path" environment variable then Command prompt will
take the java version which we provided as first one to the path environment variable in the order.

EX:
path=C:\Java\jdk1.6.0\bin;C:\Java\jdk1.7.0\bin;C:\Java\jdk1.8.0\bin;
On Command Prompt:

D:\javaapps>java -version --> Enter


Java - Version: JDK1.6.0

If we want to switch java from one version to another version in simpified manner as per the
requirement then we have to use batch files.

a)Take a text file.


b)provide the required "path" command.
c)Save file with "file_Name.bat" .
d)Open Command prompt and goto the location where bat files are saved.
e)write bat file name and click on enter button.

D:\java9\ java6.bat
set path=C:\Java\jdk1.6.0\bin;

D:\java9\ java7.bat
set path=C:\Java\jdk1.7.0\bin;

D:\java9\ java8.bat
set path=C:\Java\jdk1.8.0\bin;

On Command Prompt:
D:\java9>java6.bat ---> Enter button
--- we will get java6 setup----

D:\java9>java7.bat ---> Enter button


--- we will get java7 setup----

D:\java9>java8.bat ---> Enter button


--- we will get java8 setup----
24
Page

2.Select Java Editor:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Editor is a software, it will provide very good env to write java programs and to save java programs
in our system.

EX: Notepad, Notepadplus, Editplus,....

Note: In real time application development, it is not suggestible to use Editors, it is always suggestible
to use IDEs[Integrated Development Environment].

EX: Eclipse, MyEclipse, Netbeans,........

3.Write Java Program:


To write java program we have to use some prederfined library provided by JAVA API[Application
Programming Interface].

EX
D:\javaapps\ Test.java

class Test{
public static void main(String[] args){
System.out.println("First Java Application");
}
}

4.Save Java File:


To save java file in our system, we have to follow the following two conditions.

1.If the present java file contains any public element[class, abstract class, interface, enum] then we
must save java file with public element name only.If we voilate this condition then compiler will
rise an error.

2.If no public element is identified in our java file then it is possible to save java file with any name
like abc.java or xyz.java, but, it is suggestible to save java file with main() method class name.

25
Page

Q)Is it possible to provide more than one public class with in a single java file?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
No, it is not possible to provide more than one public class with in a single java file, because, if we
provide more than one class as public then we must save that java file with more than one name, it is
not possible in all the operating systems.

EX1: File Name: abc.java

class FirstApp{
public static void main(String[] args){
System.out.println("First Java Application");
}
}

Status: No Compilation Error, but not suggestible.

EX2:File Name: FirstApp.java

class FirstApp{
public static void main(String[] args){
System.out.println("First Java Application");
}
}
Status: No COmpilation Error, it is suggestible.

EX3:File Name: FirstApp.java

public class A{
}
class FirstApp{
public static void main(String[] args){
System.out.println("First Java Application");
}
}
Status: Compilation Error. 26
Page

EX4:File Name: A.java

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public class A{
}
class FirstApp{
public static void main(String[] args){
System.out.println("First Java Application");
}
}

Status: No Compilation Error.

EX5: File Name: A.java


public class A{
}
public class B{
}
class FirstApp{
public static void main(String[] args){
System.out.println("First Java Application");
}
}
Status: Compilation Error

5.Compile Java File:


1.The main purpose of compiling JAVA file is to convert JAVA programme from High Level
Representation to LowLevelRepresentation.
2.To Check compilation errors.

To compile JAVA file,we have to use the following command on command prompt from the
location where JAVA File is Saved
javac File_Name.java

EX:
d:\java9>javac FirstApp.java
27
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we use the above command on command prompt then operating System will perform the following
actions.

1.Operating System will take "javac" command from command prompt and search for it at its
predefined commands lists and at the locations referred by "path" environment variable.

2.If the required "javac" program is not available at the above two locations then operating System will
give a message on command prompt.

"javac can not be recognized as an internal command,external command or operable program and a
batch file"

NOTE:To make available all JDK tools like javac,java...to the operating System we have to set "path"
environment variable to
"c:\java\jdk1.7.0\bin" location.

D:\java9>set path=C:\Java\jdk1.7.0\bin;

3.If the required "javac" program is identified at "c:\java\jdk1.7.0\bin" location through "path"
environment variable then operating System will execute "javac" program and activate "Java
Compiler" software.

4.When Java Complier Software is activated then Java Complier will perform the following tasks.

a)Compiler will take java File name from command prompt.

b)Compiler will search java file at current location.

c)If the required java file is not available at current location then compiler will provide the following
message on command prompt.

javac : file not found : FirstApp.java

d)If the required java file is available at current location then compiler will start compilation from
starting point to ending point of the java file.

e)In compilation process,if any syntax violations are identified then compiler will generate error
messages on command prompt.

f)In compilation process,if no syntax errors are identified then compiler will generate .class files at
28

the same current location.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:Generating no of .class files is completely depending on the no of classes,no of abstract
classes,no of interfaces,no of enums and no of inner classes which we used in the present java File

If we want to compile java file from current location and if we want to send the generated .class Files
to some other target location then we have to use the following command on command prompt

javac -d target_location File_Name.java

EX:
d:\java9>javac -d c:\abc FirstApp.java

If we use package declaration statement in java file and if we want to store the generated .class files by
creating directory structure w.r.t the package name in compilation process then we have to use
"-d" option along with "javac" command.

EX: File Name :D:\java9\FirstApp.java

package com.durgasoft.core;
enum E{
}
interface I{
}
abstract class A{
}
class B{

class C{
}
}
class FirstApp{
public static void main(String[] args){
}
}

D:\java9>javac -d c:\abc FirstApp.java

Compiler will compile FirstApp.java File from "D:\java9" location and it will generate E.class, I.class,
A.class, B.class, B$C.class, FirstApp.class files at the specified target location "C:\abc" by creating
directory structure w.r.t the package name "com.durgasoft.core".

If we want to compile all the java files which are available at current location then we have to use the
29

following command.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


D:\java9>javac *.java

If we want to compile all the java files which are prefixed with a word then we have to use the
following command.

D:\java9>javac Employee*.java

If we want to compile all the java files which are postfixed with a common word then we have to use
the following command.

D:\java9>javac *Address.java

If we want to compile all the java Files which contain particular word then we have to use the
following command

D:\java9>javac *Account*.java
D:\java9>javac -d C:\abc *Account*.java

Execute JAVA Application:


If we want to execute java program then we have to use the following command prompt.

java Main_Class_Name

EX:
d:\java9>java FirstApp

If we use the above command on command prompt then operating System will execute "java"
operable program at "C:\java\jdk1.7.0\bin",with this,JVM software will be activated and JVM
will perform the following actions.

1. JVM will take Main_Class name from command prompt.

2. JVM will search for Main_Class at current location,at Java predefined library and at the
locations referred by "classpath" environment variable.

3. If the required Main_Class .class file is not available at all the above locations then JVM
will provide the following.

JAVA6: java.lang.NoClassDefFoundError:FirstApp
30

JAVA7: Error:Could not find or load main class FirstApp


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:If main class .class file is available at some other location then to make available main
class.class file to JVM we have to set "classpath" environment varaible.

D:\java7>set classpath=E:\XYZ;

4. If the required main class .class file is available at either of the above locations then JVM will load
main class bytecode to the memory by using "Class Loaders".

5. After loading main class bytecode to the memory,JVM will search for main() method.

6. If main() method is not available at main class byteCode then JVM will provide the following.

JAVA6: java.lang.NoSuchMethodError:main

JAVA7: Error:Main method not found in class FirstApp,please define main method as:
public static void main(String args[])

7. If main() method is available at main class bytecode then JVM will access main() method by
creating a thread called as "Main thread".

8. JVM will access main() method to start application execution by using main thread,when main
thread reached to the ending point of main() method then main thread will be in destroyed/dead
state.

9. When main Thread is in dead state then JVM will stop all of its internal processes and JVM will go
to ShutDown mode.

31
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Language Fundamentals:
To prepare java applications , we need some fundamentals provided by Java programming
language.

1. Tokens
2. Data Types
3. Type Casting
4. Java Statements
5. Arrays

1. Tokens:
Smallest logical unit in java programming is called as "Lexeme".

The Collection of Lexemes come under a particular group is called as "Token"

int a=b+c*d;

Lexemes: int, a, =, b,+, c, *, d, ;-----> 9

Tokens:
1)Data Types: int
2)Identifiers: a, b, c, d
3)Operators: =, +, "*
4)Special Symbol: ;

Types of tokens: 4

To prepare java applications, java has provided the following list of tokens.
1.Identifiers
2.Literals
3.Keywords/ Reserved Words
4.Operators

32
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Identifiers
Identifier is a name assigned to the programming elements like variables, methods, classes, abstract
classes, interfaces,.....

EX:
int a=10;
int ----> Data Types
a ------> variable[Identifier]
= ------> Operator
10 -----> constant
; ------> Terminator

To provide identifiers in java programming, we have to use the following rules and regulations.
1. Identifiers should not be started with any number, identifiers may be started with an alphabet, '_'
symbol, '$' symbol, but, the subsequent symbols may be a number, an alphabet, '_' symbol, '$'
symbol.

int eno=111;------> Valid


int 9eno=999;-----> Invalid
String _eaddr="Hyd";---> Valid
float $esal=50000.0f;----> valid
String emp9No="E-9999";----> Valid
String emp_Name="Durga";----> Valid
float emp$Sal=50000.0f;------> Valid

2. Identifiers are not allowing all operators and all special symbols except '_' and '$' symbols.
int empNo=111; -------> valid
int emp+No=111;-------> Invalid
String emp*Name="Durga";-----> Invalid
String #eaddr="Hyd";--->Invalid
String emp@Hyd="Durga";-----> Invalid
float emp.Sal=50000.0f;-----> Invalid
String emp-Addr="Hyd";------> Invalid
String emp_Addr="Hyd";------> Valid

3. Identifiers are not allowing spaces in the middle.


concat(--)----> Valid
forName(--)---> Valid
for Name()----> Invalid
getInputStream()--> valid
33

get Input Stream()----> Invalid


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4. Identifiers should not be duplicated with in the same scope, identifiers may be duplicated in two
different scopes.
class A{
int i=10;-----> Class level
short i=20;----> Error
double f=33.33---> No Error
void m1(){
float f=22.22f; -----> local variable
double f=33.33;---> Error
long i=30;---> No Error
}
}

5. In java applications, we can use all predefined class names and interface names as identifiers.

EX1:
int Exception=10;
System.out.println(Exception);
Status: No Compilation Error
OP: 10

EX2:
String String="String";
System.out.println(String);
Status: No Compilation Error
OP: String

EX3:
int System=10;
System.out.println(System);
Status: COmpilation Error

Reason: Once if we declare "System"[Class Name] as an integer variable then we must use that
"System" name as integer variable only in the remaining program, in the remaining program if we use
"System" as class name then compiler will rise an error.
In the above context, if we want to use "System" as class name then we have to use its fully qualified .

Note: Specifying class names and interface names along with package names is called as Fully
Qualified Name.

EX: java.io.BufferedReader
34

java.util.ArrayList
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
int System=10;
java.lang.System.out.println(System);
System=System+10;
java.lang.System.out.println(System);
System=System+10;
java.lang.System.out.println(System);
Status: No Compilation Error
OP: 10
20
30

Along with the above rules and regulations, JAVA has provided a set of suggessions to use identifiers
in java programs
1. In java applications, it is suggestible to provide identifiers with a particular meaning.
EX:
String xxx="abc123";------> Not Suggestible
String accNo="abc123";----> Suggestible

2. In java applications, we dont have any restrictions over the length of the identifiers, we can
declare identifiers with any length, but, it is suggestible to provide length of the identifiers around
10 symbols.
EX:
String permanentemployeeaddress="Hyd";----> Not Suggestible
String permEmpAddr="Hyd";----> Suggestible

3. If we have multiple words with in a single identifier then it is suggestible to seperate multiple
words with special notations like '_' symbols.
EX:
String permEmpAddr="Hyd";----> Not Suggestible
String perm_Emp_Addr="Hyd";----> Suggestible

2. Literals:
Literal is a constant assigned to the variables .
EX:
int a=10;
int ----> data types
a ------> variables/ identifier
= ------> Operator
10 -----> constant[Literal].
; ------> Special symbol.
35

To prepare java programs, JAVA has provioded the following set of literals.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Integer / Integral Literals:
byte, short, int, long ----> 10, 20, 30,....
char -----> 'A','B',.....

2.Floating Point Literals:


float ----> 10.22f, 23.345f,.....
double----> 11.123, 456.345,....

3.Boolean Literals:
boolean -----> true, false

4.String Literals:
String ---> "abc", "def",......

Note: JAVA7 has given a flexibility like to include '_' symbols in the middle of the literals inorder to
improve readability.

EX:
float f=12345678.2345f;
float f=1_23_45_678.2345f;

If we provide '_' symbols in the literals then compiler will remove all '_' symbols which we provided,
compiler will reformate that number as original number and compiler will process that number as
original number.

Number Systems in Java:


IN general, in any programming language, to represent numbers we have to use a particular system .

There are four types of number systems in programming languages.

1. Binary Number Systems[BASE-2]


2. Octal Number Systems[BASE-8]
3. Decimal Number Systems[BASE-10]
4. Hexa Decimal Number Systems[BASE-16]

In java , all number systems are allowed, but, the default number system in java applications is
"Decimal Number Systems".
36
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1. Binary Number Systems[BASE-2]:
If we want to represent numbers in Binary number system then we have to use 0's and 1's, but, the
number must be prefixed with either '0b' or '0B'.

int a=10;-----> It is not binary number, it is decimal num.


int b=0b10;---> valid
int c=0B1010;---> valid
int d=0b1012;---> Invalid, 2 symbol is not binary numbers alphabet.

Note: Binary Number system is not supported by all the java versions upto JAVA6, but , JAVA7 and
above versions are supporting Binary Number Systems, because, it is a new feature introduced in
JAVA7 version.

2. Octal Number Systems[BASE-8]:


If we want to prepare numbers in Octal number System then we have to use the symbols like
0,1,2,3,4,5,6 and 7, but, the number must be prefixed with '0'[zero].

EX:
int a=10; ------> It is decimal nhumber, it is not octal number.
int b=012345;---> Valid
int c=O234567;---> Invalid, number is prefixed with O, not zero
int d=04567;----> Valid
int e=05678;----> Invalid, 8 is not octal number systems alphabet.

3. Decimal Number Systems[BASE-10]:


If we want to represent numbers in Decimal number system then we have to use the symbols like
0,1,2,3,4,5,6,7,8 and 9 and number must not be prefixed with any symbols.

EX:
int a=10;----> Valid
int b=20;----> Valid
int c=30;----> valid

4. Hexa Decimal Number Systems[BASE-16]:


If we want to prepare numbers in Hexa decimal number system then we have to use the symbols like
0,1,2,3,4,5,6,7,8,9, a,b,c,d,e and f, but the number must be prefixed with either '0x' or '0X'.

EX: int a=10;-----> It is not hexa decimal number, it is decimal number.


int b=0x102345;---> Valid
int c=0X56789;---> Valid
int d=0x89abcd;---> valid
37

int e=0x9abcdefg;----> Invalid, 'g' is not in hexa decimal alphabet.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: If we provide numbers in all the above number systems in java applications then compiler will
recognize all the numbers and their number systems on the basis of their prefix values , compiler will
convert these numbers into decimal system and compilers will process that numbers as decimal
numbers.

Keywords/ Reserved Words:


If any predefined word having both word recognization and internal functionality then that predefined
word is called as Keyword.

If any predefined word having only word recognization with out internal functionality then that
predefined word is called as Reserved word.

EX: goto const.

To prepare java applications, Java has provided the following list of keywords.

1.Data types and Return types:


bytes, short, int, long, float, double, char, boolean, void.

5. Access Modifiers:
public, protected, private, static, final, abstract, native, volatile, transient, synchronized, strictfp,.....

6. Flow Controllers:
if, else, switch, case, default, for, while, do, break, continue, return,....

7. Class/ Object Related:


class,enum, extends, interface, implements, package, import, new, this, super,....

8. Exception Handling Related Keywords:


throw, throws, try, catch, finally

Operators:
Operator is a symbol, it will perform a particular operation over the provided operands.

To prepare java applications, JAVA has provided the following list of operators.

1. Arithmetic Operators:
+, -, *, /, %, ++, --

2. Assignment Operators:
38

=, +=, -=, *=, /=, %=,.....


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3. Comparision Operators:
==, !=, <, >, <=, >=,.....

4. Boolean Logical Operators:


&, |, ^

5. Bitwise Logical Operators:


&, |, ^, <<, >>,...

6. Short-Circuit Operators:
&&, ||

7. Ternary Operator:
Expr1? Expr2: Expr3;

Ex1:
class Test
{
public static void main(String[] args)
{
int a=10;
System.out.println(a);
System.out.println(a++);
System.out.println(++a);
System.out.println(a--);
System.out.println(--a);
System.out.println(a);
}
}
Status: No Compilation Error
OP: 10
10
12
12
10
10
39
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Test
{
public static void main(String[] args)
{
int a=5;
System.out.println(++a-++a);
}
}

Status: No Compilation Error


OP: -1

EX:
class Test
{
public static void main(String[] args)
{
int a=5;
System.out.println((--a+--a)*(++a-a--)+(--a+a--)*(++a+a++));
}
}

Status: No Compilation Error

OP: 16

A B A&B A|B A^B


-----------------------
T T T T F
T F F T T
F T F T T
F F F F F
40
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: class Test
{
public static void main(String[] args)
{
boolean b1=true;
boolean b2=false;

System.out.println(b1&b1);//true
System.out.println(b1&b2);//false
System.out.println(b2&b1);//false
System.out.println(b2&b2);//false

System.out.println(b1|b1);//true
System.out.println(b1|b2);//true
System.out.println(b2|b1);//true
System.out.println(b2|b2);//false

System.out.println(b1^b1);//false
System.out.println(b1^b2);//true
System.out.println(b2^b1);//true
System.out.println(b2^b2);//false
}
}

A B A&B A|B A^B


--------------------
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

T----> 1
F----> 0
41
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Test
{
public static void main(String[] args)
{
int a=10;
int b=2;
System.out.println(a&b);
System.out.println(a|b);
System.out.println(a^b);
System.out.println(a<<b);
System.out.println(a>>b);
}
}

int a=10;----> 1010


int b=2;-----> 0010

a&b--->10&2--> 0010-----> 2
a|b--->10|2--> 1010-----> 10
a^b--->10^2--> 1000-----> 8

a<<b ---> 10<<2 -----> 00001010


00101000---> 40
--> Remove 2 symbols at leftside and append 2 0's at right side.

a>>b ---> 10>>2 -----> 00001010


00000010
--> Remove 2 symbols at right side and append 2 0's at left side.

Note: Removable Symbols may be o's and 1's but appendable symbols must be 0's.

Short-Circuit Operators:
The main intention of Short-Circuit operators is to improve java applications performance.

EX: 1.&& 2.||

| Vs ||

In the case of Logical-OR operator, if the first operand value is true then it is not required to check
second operand value, directly, we can predict the result of overall expression is true.
42
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the case of '|' operator, even first operand value is true , still, JVM evalutes second opoerand value
then only JVM will get the result of overall expression is true, here evaluating second operand value is
unneccessary, it will increase execution time and it will reduve application performance.

In the case of '||' operator, if the first operand value is true then JVM will get the overall expression
result is true with out evaluating second operand value, here JVM is not evaluating second operand
expression unneccessarily, it will reduce execution time and it will improve application performance.
Note: If the first operand value is false then it is mandatory for JVM to evaluate second operand value
inorder to get overall expression result.

EX:
class Test
{
public static void main(String[] args)
{
int a=10;
int b=10;
if( (a++ == 10) | (b++ == 10) )
{
System.out.println(a+" "+b);//OP: 11 11
}
int c=10;
int d=10;
if( (c++ == 10) || (d++ == 10) )
{
System.out.println(c+" "+d);//OP: 11 10
}
}
}

& Vs &&
In the case of Logical-AND operator, if the first operand value is false then it is not required to check
second operand value, directly, we can predict the result of overall expression is false.

In the case of '&' operator, even first operand value is false , still, JVM evalutes second opoerand value
then only JVM will get the result of overall expression is false, here evaluating second operand value
is unneccessary, it will increase execution time and it will reduve application performance.

In the case of '&&' operator, if the first operand value is false then JVM will get the overall expression
43

result is false with out evaluating second operand value, here JVM is not evaluating second operand
Page

expression unneccessarily, it will reduce execution time and it will improve application performance.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: If the first operand value is true then it is mandatory for JVM to evaluate second operand value
inorder to get overall expression result.

EX:
class Test
{
public static void main(String[] args)
{
int a=10;
int b=10;
if( (a++ != 10) & (b++ != 10) )
{
}
System.out.println(a+" "+b);//OP: 11 11
int c=10;
int d=10;
if( (c++ != 10) && (d++ != 10) )
{
}
System.out.println(c+" "+d);//OP: 11 10
}
}

5. Data Types:
Java is strictly a typed programming language, where in java applicatins before representing data
first we have to confirm which type of data we representing. In this context, to represent type of
data we have to use "data types".

EX: i = 10;----> invalid, no data type representation.


int i=10;--> Valid, type is represented then data is rpersented.

In java applications , data types are able to provide the following advatages.

1. We are able to identify memory sizes to store data.


EX: int i=10;--> int will provide 4 bytes of memory to store 10 value.

2.We are able to identify range values to the variable to assign.


EX: byte b=130;---> Invalid
byte b=125;---> Valid
44

Reason: 'byte' data type is providing a particular range for its variables like -128 to 127, in
Page

this range only we have to assign values to byte variables.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To prepare java applications, JAVA has provided the following data types.

1. Primitive Data Types / Primary Data types

1. Numeric Data Types

1. Integral data types/ Integer Data types:


byte ------> 1 bytes ----> 0
short------> 2 bytes-----> 0
int--------> 4 bytes-----> 0
long-------> 8 bytes-----> 0

2. Non-Integral Data Types:


float------> 4 bytes----> 0.0f
double-----> 8 bytes----> 0.0

1. Non-Numeric Data types:


char ---------> 2 bytes---> ' ' [single space]
boolean-------> 1 bit-----> false

2. User defined data types / Secondary Data types


All classes, all abstract classes, all interfaces, all arrays,......

No fixed memory allocation for User defined data types

If we want to identify range values for variablers onthe basis of data types then we have to use the
following formula.

n-1 n-1
-2 to 2 - 1
Where 'n' is no of bits.

EX: Data Type: byte , size= 1 byte = 8 bits.

8-1 8-1
-2 to 2 - 1

7 7
-2 to 2 - 1

-128 to 128 - 1
45
Page

-128 to 127

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: This formula is applicable upto Integral data types, not applicable for other data types.

To identify "min value" and "max value" for each and every data type, JAVA has provided the
following two constant variables from all the wrapper classes.

MIN_VALUE and MAX_VALUE

Note: Classes representation of primitive data types are called as Wrapper Classes

Primitive data types Wrapper Classes


-------------------- ----------------
byte --------------------> java.lang.Byte
short -------------------> java.lang.Short
int ---------------------> java.lang.Integer
long --------------------> java.lang.Long
float -------------------> java.lang.Float
double-------------------> java.lang.Double
char---------------------> java.lang.Character
boolean------------------> java.lang.Boolean

EX:
class Test{
public static void main(String[] args){
System.out.println(Byte.MIN_VALUE+"----->"+Byte.MAX_VALUE);
System.out.println(Short.MIN_VALUE+"---->"+Short.MAX_VALUE);
System.out.println(Integer.MIN_VALUE+"----->"+Integer.MAX_VALUE);
System.out.println(Long.MIN_VALUE+"----->"+Long.MAX_VALUE);
System.out.println(Float.MIN_VALUE+"----->"+Float.MAX_VALUE);
System.out.println(Double.MIN_VALUE+"----->"+Double.MAX_VALUE);
System.out.println(Character.MIN_VALUE+"----->"+Character.MAX_VALUE);
//System.out.println(Boolean.MIN_VALUE+"----->"+Boolean.MAX_VALUE);---> Error
}
}

Type Casting:

The process of converting data from one data type to another data type is called as "Type Casting".
There are two types of type castings are existed in java.

1.Primitive data Types Type Casting


46

2.User defined Data Types Type Casting


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: To perform User defined data types type casting we need either "extends" relation or
"implements" relation between user defined data types.

1.Primitive data Types Type Casting:


The process of converting data from one primitive data type to another primitive data type is
called as Primitive data types type casting.

There are two types of primitive data types type castings.

1.Implicit Type Casting


2.Explicit Type Casting

1. Implicit Type Casting:


The process of converting data from lower data type to higher data type is called as Implicit Type
Casting.

To cover all the possibilities of implicit type casting JAVA has provided the following chart.

1 2 4 8 4 8
byte ---> short ---> int ---> long ---> float ---> double
^
|
char

If we want to perform implicit type casting in java applications then we have to assign lower data type
variables to higher data type variables.

EX:
byte b=10;
int i = b;
System.out.println(b+" "+i);

Status: No COmpilation Error


OP: 10 10

If we compile the above code, when compiler encounter the above assignment stattement then
compiler will check whether right side variable data type is compatible with left side variable data type
or not, if not, compiler will rise an error like "possible loss of precision". If right side variable data
type is compatible with left side variable data type then compiler will not rise any error and compiler
will not perform any type casting.
47
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


When we execute the above code, when JVM encounter the above assignment statement then JVM
will perform the following two actions.

1.JVM will convert right side variable data type to left side variable data type implicitly[Implicit
Type Casting]
2.JVM will copy the value from right side variable to left side variable.

Note: Type Checking is the responsibility of compiler and Type Casting is the responsibility of JVM.

EX2:
class Test
{
public static void main(String[] args)
{
int i=10;
byte b=i;
System.out.println(i+" "+b);
}
}
Status: Compilation Error, Possible loss of precision.

EX3:
class Test
{
public static void main(String[] args)
{
byte b=65;
char c=b;
System.out.println(b+" "+c);
}
}
Status: Compilation Error

48
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX4:
class Test
{
public static void main(String[] args)
{
char c='A';
short s=c;
System.out.println(c+" "+s);
}
}
Status: Compilation Error, Possible loss of precision.
Reason: byte and short internal data representations are not compatible to convert into char.

EX5:
class Test
{
public static void main(String[] args)
{
char c='A';
int i=c;
System.out.println(c+" "+i);
}
}
Status: No Compilation Error
OP: A 65

Reason: Char internal data representation is compatible with int.

EX6:
class Test
{
public static void main(String[] args)
{
byte b=128;
System.out.println(b);
}
}
Status: Compilation Error,possible loss of precision.
Reason: When we assign a value to a variable of data type, if the value is greater the max limit of the
left side variable data type then that value is treated as of the next higher data type value.
Note: For both byte and short next higher data type is int only.
49
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX7:
class Test
{
public static void main(String[] args)
{
byte b1=60;
byte b2=70;
byte b=b1+b2;
System.out.println(b);
}
}
Status: Compilation Error, possible loss of precision.

EX8:
class Test
{
public static void main(String[] args)
{
byte b1=30;
byte b2=30;
byte b=b1+b2;
System.out.println(b);
}
}

Status: Compilation Error, Possible loss of precision.


Reason: X,Y and Z are three primitive data types.

X+Y=Z

1.If X and Y belongs to {byte, short, int} then Z should be int.


2.If either X or Y or both X and Y belongs to {long, float, double} then Z should be higher(X,Y).

byte+byte=int
byte+short=int
short+int=int
byte+long=long
long+float=float
float+double=double
50
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX9:
class Test
{
public static void main(String[] args)
{
long l=10;
float f=l;
System.out.println(l+" "+f);
}
}

Status: No Compilation Error


OP: 10 10.0

EX10:
class Test
{
public static void main(String[] args)
{
float f=22.22f;
long l=f;
System.out.println(f+" "+l);
}
}

Status: Compilation Error, possible loss of precision.


Reason:
two class rooms
Class Room A: 25[Size] banches---> 3 members per bench---> 75
Class Room B: 50[Size] banches---> 1 member per bench----> 50

long---> 8 bytes--> less data as per its internal data arrangement.


float--> 4 bytes--> more data as per its internal data arrangement.

Due to the above reason, float data type is higher when compared with long data type so that, we are
able to assign long variable4 to float variable directly, but, we are unable to assign float variable to
long variable directly.
51
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2. Explicit Type Casting:
The process of converting data from higher data type to lower data type is called as Explicit Type
Casting.

To perform explicit type casting we have to use the following pattern.

P a = (Q) b;

(Q)----> Cast operator


Where P and Q are two primitive data types, where Q must be either same as P or lower than P as
per implicit type casting chart.

EX1:
class Test
{
public static void main(String[] args)
{
int i=10;
byte b=(byte)i;
System.out.println(i+" "+b);
}
}

Status: No Compilation Error


OP: 10 10

When we compile the above code, when compiler encounter the above assignment statement, compiler
will check whether cast operator provided data type is compatible with left side variable data type or
not, if not, compiler will rise an error like "Possible loss of precision". If cast operator provided data
type is compatible with left side variable data type then compiler will not rise any error and compiler
will not perform type casting.

When we execute the above program, when JVM encounter the above assignment statement then JVM
will perform two actions.

1.JVM will convert right side variable data type to cast operator provided data type.
2.JVM will copy value from right side variable to left side variable.
52
Page

EX2:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test
{
public static void main(String[] args)
{
int i=10;
short s=(byte)i;
System.out.println(i+" "+s);
}
}

Status: No Compilation Error


OP: 10 10

EX3:
class Test
{
public static void main(String[] args)
{
byte b=65;
char c=(char)b;
System.out.println(b+" "+c);
}
}
Status: No Compilation Error
OP: 65 A

EX4:
class Test
{
public static void main(String[] args)
{
char c='A';
short s=(short)c;
System.out.println(c+" "+s);
}
}

Status: No Compilation Error


OP: A 65
53
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: In Implicit type casting, conversions are not possible between char and byte, short and char, but,
in explicit type casting conversions are possible in between char and byte, char and short, why
because, explicit type casting is forcable type casting.

EX5:
class Test
{
public static void main(String[] args)
{
short s=65;
char c=(byte)s;
System.out.println(s+" "+c);
}
}
Status: COmpilation Error.

EX6:
class Test
{
public static void main(String[] args)
{
byte b1=30;
byte b2=30;
byte b=(byte)b1+b2;
System.out.println(b);
}
}
Status: Compilation Error

EX7:
class Test
{
public static void main(String[] args)
{
byte b1=30;
byte b2=30;
byte b=(byte)(b1+b2);
System.out.println(b);
}
}
Status: No Compilation Error
54

OP: 60
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX8:
class Test
{
public static void main(String[] args)
{
double d=22.22;
byte b=(byte)(short)(int)(long)(float)d;
System.out.println(b);
}
}

Status: No Compilation Error


OP: 22

EX9:
class Test
{
public static void main(String[] args)
{
int i=130;
byte b=(byte)i;
System.out.println(b);
}
}

Status: No Compilation Error


OP: -126
Reason: REf Diagram

Java Statements:
Statement is the collection of expressions.

To design java applications JAVA has provided the following statements.

1. General Purpose Statements


Declaring variables, methods, classes,....
Creating objects, accessing variables, methods,.....

2. Conditional Statements:
55

1. if 2.switch
Page

3. Iterative Statements:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.for 2.while 3.do-while

4. Transfer statements:
1.break 2.continue 3.return

5. Exception Handling statements:


throw, try-catch-finally

6. Synchronized statements:
1.synchronized methods
2.synchronized blocks

Conditional Statements:
These statements are able to allow to execute a block of instructions under a particular condition.

EX:
1. if 2.switch

1. if:
syntax-1:
if(condition)
{
---instructions----
}

Syntax-2:
if(condition)
{
---instuctions----
}
else
{
----instructions----
}
56
Page

Syntax-3:
if(condition)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
---instructions----
}
else if(condition)
{
---instruction----
}
else if(condition)
{
---instructions----
}
----
----
else
{
----instructions----
}

EX1:
class Test
{
public static void main(String[] args)
{
int i=10;
int j;
if(i==10)
{
j=20;
}
System.out.println(j);
}
}

Status: Compilation Error, Variable j might not have been innitialized.


57
Page

EX2:
class Test

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
public static void main(String[] args)
{
int i=10;
int j;
if(i==10)
{
j=20;
}
else
{
j=30;
}
System.out.println(j);
}
}

Status: No Compilation Error


OP: 20

EX3:
class Test
{
public static void main(String[] args)
{
int i=10;
int j;
if(i==10)
{
j=20;
}
else if(i==20)
{
j=30;
}
System.out.println(j);
}
}

Status: Compilation Error, Variable j might not have been initialized.


58
Page

EX4: class Test


{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
int i=10;
int j;
if(i==10)
{
j=20;
}
else if(i==20)
{
j=30;
}
else
{
j=40;
}
System.out.println(j);
}
}

Status: no Compilation Error


OP: 20

EX5:
class Test
{
public static void main(String[] args)
{
final int i=10;
int j;
if(i == 10)
{
j=20;
}
System.out.println(j);
}
}

Status: No Compilation Error


OP: 20
59
Page

EX6:
class Test

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
public static void main(String[] args)
{
int j;
if(true)
{
j=20;
}
System.out.println(j);
}
}

Status: No Compilation Error


Reasons:
1.In java applications, only class level variables are having default values, local variables are not
having default values. If we declare local variables in java applications then we must provide
initializations for that local variables explicitlty, if we access any local variable with out having
initialization explicitly then compiler will rise an error like "Variable x might not have been
initialized".

EX:
class A{
int i;-----> class level variable, default value is 0..
void m1(){
int j;---> local variable, no default value.
System.out.println(i);// OP: 0
//System.out.println(j);--> Error
j=20;
System.out.println(j);---> No Error
}
}

Note: Local variables must be declared in side methods, blocks, if conditions,... and these variables are
having scope upto that method only, not having scope to outside of that method. Class level variables
are declare at class level that is in out side of the methods, blocks,.... these variables are having scope
through out the clsas that is in all methods, in all blocks which we provided in the respective class.
60
Page

2. In java, there are two types of conditional Expressions.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1. Constant Expressions
2. Variable Expressions

1. Constant Expressions:
These expressions includes only constants including final variables and these expressions would be
evaluated by "Compiler" only, not by JVM.

EX:
1.if( 10 == 10){ } ----> Constant Expression
2.if( true ){ } ------> Constant Expression
3.final int i=10;
if( i == 10 ){ } ----> Constant Expression

Note: If we declare any variable as final variable with a value then compiler will replace final
variables with their values in the remaining program, this process is called "Constant Folding", it is
one of the code optimization tech followed by Compiler.

2. Variable Expressions:
These expressions are including atleast one variable [not including final variables] and these
expressions are evaluated by JVM, not by Compiler.

EX:
1.int i=10;
int j=10;
if( i == j ){ } ----> variable expression.

2.int i=10;
if( i == 10 ){ } ----> Variable expression

switch

'if' is able to provide single condition checking bydefault, but, switch is able to provide multiple
conditions checkings.

61
Page

Syntax:
switch(Var)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
case 1:
-----instructions-----
break;
case 2:
----instructions------
break;
----
----
case n:
----instructions-----
break;
default:
----instructions-----
break;
}
Note: We will utilize switch programming element in "Menu Driven" Applications.

Stack Operations
1.PUSH
2.POP
3.PEEK
4.EXIT
Enter Your Option: 1
Enter element to PUSH: A
PUSH operation success

Stack Operations
1.PUSH
2.POP
3.PEEK
4.EXIT
Enter Your Option:2
POP operation success.
62
Page

Stack Operations
1.PUSH

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.POP
3.PEEK
4.EXIT
Enter Your Option:3
PEEK Operation Success, TOP: A

Stack Operations
1.PUSH
2.POP
3.PEEK
4.EXIT
Enter Your Option:4
Thanks for using STACK Operations.

EX:
class Test
{
public static void main(String[] args)
{
int i=10;
switch(i)
{
case 5:
System.out.println("Five");
break;
case 10:
System.out.println("Ten");
break;
case 15:
System.out.println("Fifteen");
break;
case 20:
System.out.println("Twenty");
break;
default:
System.out.println("Default");
break;
}

}
}
63
Page

Rules to write switch:


1.switch is able to allow the data types like byte, short, int and char.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: byte b=10;
switch(b)
{
----
}
Status: No Compilation Error

EX: long l=10;


switch(l)
{
----
}
Status: Compilatiopn Error.
EX: class Test
{
public static void main(String[] args)
{
char c='B';
switch(c)
{
case 'A':
System.out.println("Five");
break;
case 'B':
System.out.println("Ten");
break;
case 'C':
System.out.println("Fifteen");
break;
case 'D':
System.out.println("Twenty");
break;
default:
System.out.println("Default");
break;
}

}
}
64

Status: no Compilation Error


Page

Note:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Upto JAVA6 version, switch is not allowing "String" data type as parameter, "JAVA7" version
onwards switch is able to allow String data type.

EX:
class Test
{
public static void main(String[] args)
{
String str="BBB";
switch(str)
{
case "AAA":
System.out.println("AAA");
break;
case "BBB":
System.out.println("BBB");
break;
case "CCC":
System.out.println("CCC");
break;
case "DDD":
System.out.println("DDD");
break;
default:
System.out.println("Default");
break;
}

}
}

Status: No Compilation Error


OP: BBB

65

2. In switch, all cases and default are optional, we can write switch with out cases and with default, we
Page

can write switch with cases and with out default, we can write switch with out both cases and default.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
int i=10;
switch(i)
{

}
Status: No Compilation Error
OP: No Output.

EX:
class Test
{
public static void main(String[] args)
{
int i=10;
switch(i)
{
default:
System.out.println("Default");
break;
}

}
}

Status:No Compilation Error


OP: Default

66

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
int i=10;
switch(i)
{
case 5:
System.out.println("Five");
break;
case 10:
System.out.println("Ten");
break;
case 15:
System.out.println("Fifteen");
break;
case 20:
System.out.println("Twenty");
break;
}

}
}

Status: No Compilation Error


OP: Ten

67

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
int i=50;
switch(i)
{
case 5:
System.out.println("Five");
break;
case 10:
System.out.println("Ten");
break;
case 15:
System.out.println("Fifteen");
break;
case 20:
System.out.println("Twenty");
break;
}

}
}
Status: No Compilation Error
OP: No Output

68

3. In switch, "break" statement is optional, we can write switch with out break statement, in this
Page

context, JVM will execute all the instructions continously right from matched case untill it
encounter either break statement or end of switch.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: class Test
{
public static void main(String[] args)
{
int i=10;
switch(i)
{
case 5:
System.out.println("Five");

case 10:
System.out.println("Ten");

case 15:
System.out.println("Fifteen");

case 20:
System.out.println("Twenty");

default:
System.out.println("Default");

}
}
Status: No Compilation Error
OP: Ten
Fifteen
Twenty
Default

69

4. In switch, all case values must be provided with in the range of the data type which we provided as
Page

parameter to switch.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Test
{
public static void main(String[] args)
{
byte b=126;
switch(b)
{
case 125:
System.out.println("125");
break;
case 126:
System.out.println("126");
break;
case 127:
System.out.println("127");
break;
case 128:
System.out.println("128");
break;
default:
System.out.println("Default");
break;
}

}
}

Status: Compilation Error

70

5. In switch, all case values must be constants including final variables, they should not be normal
Page

variables.
EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test
{
public static void main(String[] args)
{
final int i=5,j=10,k=15,l=20;
switch(10)
{
case i:
System.out.println("Five");
break;
case j:
System.out.println("Ten");
break;
case k:
System.out.println("Fifteen");
break;
case l:
System.out.println("Twenty");
break;
default:
System.out.println("Default");
break;
}

}
}

Status: No Compilation Error


OP: 10

Note: in the above example, if we remove final keyword then compiler will rise an error.

71

Iterative Statements:
Page

These statements are able to allow JVM to execute a set of instructions repeatedly on the basis of a
particular condition.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: 1.for 2.while 3.do-while

1.for
Syntax:
for(Expr1; Expr2; Expr3)
{
----instructions-----
}
EX:
class Test
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
System.out.println(i);
}
}
}

Status: No Compilation Error


OP: 0
1
---
---
9
Expr1-----> 1 time
Expr2-----> 11 times
Expr3-----> 10 times
Body -----> 10 times

72

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
int i=0;
for(;i<10;i++)
{
System.out.println(i);
}
}
}
Status: No Compilation Error
OP: 0 ---- 9

EX:
class Test
{
public static void main(String[] args)
{
int i=0;
for(System.out.println("Hello");i<10;i++)
{
System.out.println(i);
}
}
}

Status: No Compilation Error


OP: Hello 0 1 ---- 9
Reason:
In for loop, Expr1 is optional, we can write for loop even with out Expr1 , we can write any statement
like System.out.println(--) as Expr1, but, always, it is suggestible to provide loop variable declaration
and initialization kind of statements as Expr1.

73

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
for(int i=0, float f=0.0f ;i<10 && f<10.0f; i++,f++)
{
System.out.println(i+" "+f);
}
}
}

Status: Compilation Error

EX:
class Test
{
public static void main(String[] args)
{
for(int i=0, int j=0 ;i<10 && j<10; i++,j++)
{
System.out.println(i+" "+j);
}
}
}

Status: Compilation Error

EX:
class Test
{
public static void main(String[] args)
{
for(int i=0, j=0 ;i<10 && j<10; i++,j++)
{
System.out.println(i+" "+j);
}
}
}

Status: No Compilation Error


74

OP: 0 0
Page

1 1
2 2

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


------
------
9 9

Reason:
In for loop, Expr1 is able to allow atmost one declarative statement, it will not allow more than one
declarative statement, we can declare more than one variable with in a single declarative statement.

EX: class Test


{
public static void main(String[] args)
{
for(int i=0; ;i++)
{
System.out.println(i);
}
}
}

Status: No Compilation Error


OP: Infinite Loop

EX: class Test


{
public static void main(String[] args)
{
for(int i=0; System.out.println("Hello") ;i++)
{
System.out.println(i);
}
}
}

Status: Compilation Error


Reason: In for loop, Expr2 is optional, we can write for loop even with out Expr2, if we write for loop
with out Expr2 then for loop will take "true" value as Expr2 and it will make for loop as an infinite
loop. If we want to write any statement as Expr2 then that statement must be boolean statement, it
must return either true value or false value.
75

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
System.out.println("Before Loop");
for(int i=0;i<=0 || i>=0 ;i++)
{
System.out.println("Inside Loop");
}
System.out.println("After Loop");
}
}
Status: No Compilation Error
OP: Before Loop
Inside Loop
----
----

EX:
class Test
{
public static void main(String[] args)
{
System.out.println("Before Loop");
for(int i=0; true ;i++)
{
System.out.println("Inside Loop");
}
System.out.println("After Loop");
}
}

Status:Compilation Error, Unreachable Statement

76

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
System.out.println("Before Loop");
for(int i=0;;i++)
{
System.out.println("Inside Loop");
}
System.out.println("After Loop");
}
}

Status: Compilation Error, Unreachable Statement

Reasons:
In java applications, if we provide any statement immediatly after infinite loop then that statement is
called as "Unreachable Statement". If compiler identifies the provided loop as an infinite loop and if
compiler identifies any followed statement for that infinite loop then compiler will rise an error like
"Unreachable Statement". If compiler does not aware the provided loop as an infinite loop then there is
no chance for compiler to rise "Unreachable Statement Error".

Note: Deciding whether a loop as an infinite loop or not is completly depending on the conditional
expression, if the conditional expression is constant expression and it returns true value always then
compiler will recognize the provided loop as an infinite loop. If the conditional expression is variable
expression then compiler will not recognize the provided loop as an infinite loop even the loop is
really infinite loop.
int i=0;
for(int i=10; i<10;i++)
{
}

77

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
for(int i=0;i<10;)
{
System.out.println(i);
i=i+1;
}
}
}

Status: No Compilation Error


OP: 0 ,1 ..... 9

EX:
class Test
{
public static void main(String[] args)
{
for(int i=0;i<10;System.out.println("Hello"))
{
System.out.println(i);
i=i+1;
}
}
}

Status: No Compilation Error


OP: 0
Hello
1
Hello
----
----
9
Hello

Note: In for loop, Expr3 is optional, we can write for loop with out expr3, we can provide any
statement as expr3, but, it is suggestible to provide loop variable increment/decrement kind of
statements as expr3.
78

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
for(;;)

}
}

Status: Compilation Error

EX:
class Test
{
public static void main(String[] args)
{
for(;;);

}
}
Status: No Compilation Error
OP: No Output, but, JVM will be in infinite loop

EX:
class Test
{
public static void main(String[] args)
{
for(;;)
{
}

}
}
Status: No Compilation Error
OP: No Output, but, JVM will be in infinite loop
Reason:In for loop, if we want to write single statement in body then curly braces
[{ }] are optional , if we dont want to write any statement as body then we must provide either ; or
curly braces to the for loop.
In general, we will utilize for loop when we aware no of iterations in advance before writing loop.
79

EX:
Page

int[] a={1,2,3,4,5};
int size=a.length;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


for(int i=0; i<size; i++)
{
System.out.println(a[i]);
}

If we use above for loop to retrive elements from arrays and from Collection objects then we are able
to get the following problems.

1.We have to manage a seperate loop variable.


2.At each and every iteration we have to execute a conditional expression that is expr2, which is more
streangthful operation and it may consume more no of system resources[Memory and execution
time].
3.At each and every iteration we have to perform either increment operation or decrement operation
explicitly.
4.In this approach, we are retriving elements from arrays on the basis of the index value , if it is not
proper then there may be a chance to get an exception like
"java.lang.ArrayIndexOutOfBoundsException".

The above drawbacks are able to reduce java application performance.

To overcome the above problems and to improve java application performance explicitly we have to
use "for-Each" loop provided by JDK5.0 version.
syntax:
for(Array_Data_Type var: Array_Ref_Var)
{
----
}

EX:
int[] a={1,2,3,4,5};
for(int x: a)
{
System.out.println(x);
} 80

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
int[] a={1,2,3,4,5};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
System.out.println();
for(int x: a)
{
System.out.println(x);
}
}
}

Status: No Compilation Error


OP:
1
2
3
4
5

1
2
3
4
5

81

2. While loop:
Page

In java applications, when we are not aware the no of iterations in advance before writing loop there
we have to utilize 'while' loop.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
D:\javaapps>java Insert.java
Enter Employee Number : 111
Enter Employee Name : AAA
Enter Employee Salary : 5000
Enter Employee Address: Hyd
Employee Inserted Successfully
One more Employee[yes/no]? :yes

Enter Employee Number : 222


Enter Employee Name : BBB
Enter Employee Salary : 6000
Enter Employee Address: Hyd
Employee Inserted Successfully
One more Employee[yes/no]? : yes

Enter Employee Number : 333


Enter Employee Name : CCC
Enter Employee Salary : 7000
Enter Employee Address: Hyd
Employee Inserted Successfully
One more Employee[yes/no]? no

--- Thank You for using this appl.----

Syntax:
while(Condition)
{
---instructions-----
}

82

EX:
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
int i=0;
while(i<10)
{
System.out.println(i);
i=i+1;
}
}
}

EX:
class Test
{
public static void main(String[] args)
{
int i=0;
while()
{
System.out.println(i);
i=i+1;
}
}
}
Status: Compilation Error
Reason: Conditional Expression is mandatory.

EX:
class Test
{
public static void main(String[] args)
{
System.out.println("Before Loop");
while(true)
{
System.out.println("Inside Loop");
}
System.out.println("After Loop");
}
}
83

Status: Compilation Error, Unreachable Statement.


Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test
{
public static void main(String[] args)
{
System.out.println("Before Loop");
int i=0;
while(i<=0 || i>=0)
{
System.out.println("Inside Loop");
}
System.out.println("After Loop");
}
}

do-while:
Q) What are the differences between while loop and do-while loop?
Ans:
1.While loop is not giving any guarantee to execute loop body minimum one time.
do-while loop will give guarantee to execute loop body minimum one time.

2.In case of while, first, conditional expression will be executes, if it returns true then only loop
body will be executed.
In case of do-while loop, first loop body will be executed then condition will be executed.

3.In case of while loop, condition will be executed for the present iteration.
In case of do-while loop, condition will be executed for the next iteration.

Syntaxes:

while(Condition)
{
---instructions-----
}

do
{
---instructions---
}
84

While(Condition):
Page

EX:
class Test

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
public static void main(String[] args)
{
int i=0;
do
{
System.out.println(i);
i=i+1;
}
while (i<10);
}
}
Status: No Compilation Error
OP: 0, 1, 2,.... 9

EX:
class Test
{
public static void main(String[] args)
{
System.out.println("Before Loop");
do
{
System.out.println("Inside Loop");
}
while (true);
System.out.println("After Loop");
}
}

Status: Compilation Error, Unreachable Statement

85

Transfer Statements:
These statements are able to bypass flow of execution from one instruction to another instruction.
Page

EX: 1.break 2.continue 3.return

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.break:
break statement will bypass flow of execution to outside of the loops or outside of the blocks by
skipping the remaining instructions in the current iteration and by skipping all the remaining iterations.

EX:
class Test
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
if(i==5)
{
break;
}
System.out.println(i);
}
}
}

Status: No Compilation Error


OP: 0
1
2
3
4

EX:
86

class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
System.out.println("Before loop");
for(int i=0;i<10;i++)
{
if(i==5)
{
System.out.println("Inside loop, before break");
break;
System.out.println("Inside loop, after break");
}
}
System.out.println("After Loop");
}
}
Status: Compilation Error, unreachable Statement
Reason: If we provide any statement immediatly after break statement tghen that statement is
Unreachable Statement, where compiler will rise an error.

EX:class Test
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)// Outer loop
{
for(int j=0;j<10;j++)// Nested Loop
{
if(j==5)
{
break;
}
System.out.println(i+" "+j);
}
// Out side of nested Loop
}
}
}

Status: No Compilation Error


87

OP: 0 0
Page

0 1
0 2

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


0 3
0 4
-------
-------
-------
9 0
9 1
9 2
9 3
9 4

Note: If we provide "break" statement in nested loop then that break statement is applicable for only
nested loop, it will not give any effect to outer loop.

In the above context, if we want to give break statement effect to outer loop , not to the nested loop
then we have to use "Labelled break" statement.

Syntax:
break label;

Where the provided label must be marked with the respective outer loop.

Continue…..

EX:
88

class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
l1:for(int i=0;i<10;i++)// Outer loop
{
for(int j=0;j<10;j++)// Nested Loop
{
if(j==5)
{
break l1;
}
System.out.println(i+" "+j);
}
// Out side of nested Loop
}
//Out side of outer loop
}
}

Status: no Compilation Error


OP: 0 0
0 1
0 2
0 3
0 4

2.Continue:
This transfer statement will bypass flow of execution to starting point of the loop by skipping all the
remaining instructions in the current iteration inorder to continue with next iteration.

Continue….

EX:
89

class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
for(int i=0;i<10;i++)
{
if(i == 5)
{
continue;
}
System.out.println(i);
}
}
}

Status: No Compilation Error


OP:
0
1
2
3
4
6
7
8
9

EX:
90

class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
System.out.println("before Loop");
for(int i=0;i<10;i++)
{
if(i == 5)
{
System.out.println("Inside Loop, before continue");
continue;
System.out.println("Inside Loop, After continue");
}
}
System.out.println("After loop");
}
}

Status: Compilation Error, Unreachable Statement.


Reason: If we provide any statement immediatly after continue statement then that statement is
unreachable statement, where compiler will rise an error.

EX:
class Test
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(j==5)
{
continue;
}
System.out.println(i+" "+j);
}
}
}
}

Status: No Compilation Error


91

OP:
Page

---
--

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


---
--
If we provide continue statement in netsted loop then continue statement will give effect to nested loop
only, it will not give effect to outer loop

EX:
class Test
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(j==5)
{
continue;
}
System.out.println(i+" "+j);
}
}
}
}

In the above context, if we want to give continue statement effect to outer loop, not to the nested loop
then we have to use labelled continue statement.
Syntax:
continue label;
Where the provided label must be marked with the respective outer loop.

EX:
92

class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
l1:for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(j==5)
{
continue l1;
}
System.out.println(i+" "+j);
}
}
}
}

Status: No Compiloation Error


OP:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
---
---
---
9 0
0 1
9 2
9 3
9 4

OOPs
93
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To prepare applications we have to select a particular type of programming language from the
following.

1.Unstructered Programming Languages


2.Structered Programming Languages
3.Object Oriented Programming Languages
4.Aspect Oriented Programming Languages

Q)What are the differences between Unstructered Programming Languages and Structered
Programming Languages?

Ans:
1. Unstructered Programming Languages are out dated programming languages, they were introduced
at starting point of computers and these programming languages are not suitable for our at present
application requirements.
EX: BASIC, FOTRAN,.....

Structered Programming languages are not out dated programming languages, these programming
languages are utilized for our at present application requirements.
EX: C , PASCAL,....

2. Unstructered Programming Languages are not following any proper structer to prepare applications.

Structered Programming Languages are following a particular structer to prepare applications.

3. Unstructered Programming languages are using mnemonic[ ADD, SUB, MUL,..][ low level code]
codes to prepare applications, which are available in very less number and which may provide very
less no of features to prepare applications.

Structered Programming Languages are using high level syntaxes, which are available in more number
and which may provide more no of features to the applications.

4.Unstructered Programming Languages are using only "goto" statement to define flow of execution ,
which is not sufficient to provide very good flow of execution in applications.

Structered Programming Languages are using more and more no of flow controllers like if, switch, for,
while, do-while, break,..... to defined very good flow of execution in applications.

5.Unstructered Programming languages are not having functions feature, it will increase code
94

redundency[Code duplication], it is not suggestible in application development.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Structered Programming languages are having functions feature to improve code reusability.

Q)What are the differences between Structered Programming Languages and Object Oriented
Programming Languages?

Ans:
1. Structered Programming Languages are providing difficult approach to prepare applications.
EX: C , PASCAL,...

Object Oriented Programming Languages are providing very simplified approach to prepare
applications.
EX: JAVA, C++,....

2.Structered Programming languages are not having modularity.

Object Oriented Programming Languages are having very good modularity.

3.Structered Programming languages are not having very good abstraction.

Object Oriented Programming Languages are having very good abstraction levels.

4.Structered Programming languages are not providing very good security for the applications.

Object Oriented programming Languages are providing very good security for the application data.

5.Structered Programming languages are not providing very good sharability.

Object Oriented programming Languages are providing very good sharability.

6.Structered Programming Languages are not providing very good code reusability.

Object Oriented programming languages are providing very good code reusability.

Aspect Oriented Programming Languages:


95

If we want to prepare applications by using Object orientation then we have to provide both
Page

business logic and Services logic in combined manner, it will provide tightly coupled design , it will
reduce sharability and code reusability.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To overcome the above problem we have to use Aspect Orientation. Aspect Orientation is a
methodology or a set of rules and regulations or a set of guid lines which are applied on object
oriented programming to get loosly coupled design inorder to improve sharability and code
reusability.

In case of Aspect orientation, we will seperate all services from business logic, we will declare each
and every sertvice as an aspect and we will inject these services to the applications at runtime as per
the requirement.

Object Oriented Features:


To show the nature of Object orientation, Object Orientation has provided the following features.

1.Class
2.Object
3.Encapsulation
4.Abstraction
5.Inheritance
6.Polymorphism
7.Message Passing

There are two types of programming languages on the basis of object oriented features.

1.Object Oriented Programming Languages


2.Object based Programming Languages

Q)What is the difference between Object Oriented Programming Languages and Object Based
programming languages?

Ans:
Object Oriented Programming languages are able to allow all the object oriented features including
"Inheritance".
EX: Java
Object based programming languages are able to allow all the object oriented features excluding
"Inheritance".
EX: Java Script

Q)What are the differences between class and Object?


96
Page

Ans:
1. Class is a group of elements having common properties and behaviours.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Object is an individual element among the group of elements having physical behaviours and
physical properties

2. Class is virtual.
Object is real

3. Class is virtual encapsulation of properties and behaviours.


Object is physical encapsulation of properties and behaviours.

4. Class is Generalization.
Object is Specialization.

5. Class is Model or Blue Print for the objects.


Object is an instance of the class.

Q)What is the difference between Encapsulation and Abstraction?

Ans:
The process of binding data and coding part is called as "Encapsulation".

The process showing neccessary data or implementation and hiding unneccessary data or
implementation is called as "Abstraction".

Note: In Object Oriented programming languages,both encapsulation and abstraction are improviding
"Security".

5.Inheritance:

The process of getting variables and methods from one class to another class is called as "Inheritance".

The main objective of inheritance is "Code Reusability".

EX:
97

class Employee{
Page

String eid;
String ename;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String eaddr;
---
---
void getEmpDetails(){
----
}
}

class Manager extends Employee{


--- Reuse variables and methods of Employee class---
}

class Accountent extends Employee{


--- Reuse variables and methods of Employee class here----
}

class Engineer extends Employee{


--- Reuse variables and methods of Employee class here----
}

6.Polymorphism:
Polymorphism is "Greak" word, where poly means many and morphism means structeres[forms].

If one thing is existed in multiple forms then it is called as Polymorphism.

The main advantage of Polymorphism is "Flexibility" to design application.

7.Message Passing:
The process of transferring data along with flow of execution from one instruction to another
instructions is called as Messsage passing.

The main advantage of message passing is to improve "Communication" between entities and "data
navigation" between entities.

Containers in Java:
98

1.Class
Page

2.Abstract Class
3.Interface

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Class:
Syntax:
[Access_Modifiers] class Class_Name [extends Super_Class_Name][implements
interface_List]
{
--- variables-----
-- methods--------
----constructors-----
----blocks------
---classes-------
----abstract classes-----
---interfaces------
---- enums--------
}

Access Modifiers:
There are two types of Access modifiers

1.To define scopes to the progvramming elements, there are four types of access modifiers.
public, protected, <default> and private.
Where public and <default> are allowed for classes, protected and private are not allowed for
classes.

Note: All public, protected , <default> and private are allowed for inner classes.

Note:Where private and protected access modifiers are defined on the basis of classes boudaries, so
that,they are not applicable for classes, they are applicable for members of the classes including inner
classes.

2.To define some extra nature to the programming elements , we have the following access
modifiers.

static, final, abstract, native, volatile, transient, synchronized, strictfp,.......

Where final, abstract and strictfp are allowed for the classes.

Note: The access modifiers like static, abstract, final and strictfp are allowed for inner classes.

Note: Where static keyword was defined on the basis of classes origin, so that, it is not applicable for
99

classes, it is applicable for members of the classes including inner classes.


Page

Where 'class' is a java keyword, it can be used to represent 'Class' object oriented featurte.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Where 'Class_Name' is name is an identifier, it can be used to recognize the classes individually.

Where 'extends' keyword is able to specify a particular super class name in class syntax inorder to get
variables and methods from the specified super clss to the present java class.
Note: In class syntax, 'extends' keyword is able to allow only one super class name, it will not
allowmore than one super class, because, it will represent multiple inheritnace, it is notpossible in
Java.

Where 'implements' keyword is able to specify one or more no of interfaces inclacss syntax inorder to
provide implementation for all abstract methods of that interfaces in the present class.
Note: In class syntax, extends keyword is able to allow only one super class, but, implements keyword
is able to allow more than one interface.

Note: In class syntax, 'extends' and 'implements' keywords are optional, we can write a class with
extends keyword and with out implements keyword, we can write a class with implements keyword
and with out extends keyword, we can write a class with out both extends and implements keywords ,
if we want to write both extends and implements keywords first we have to write extends keyword
then only we have to write implements keyword, we must not interchange extends and implements
keywords.

1.class A{ } ----> valid


2.public class A{ }----> valid
3.private class A{ }----> Invalid
4.protected class A{ }----> Invalid
5.class A{ public class B{ } }----> valid
6.class A{ private class B{ } }----> valid
7.class A{ protected class B { } }----> valid
8.class A{ class B{ } }----> valid
9.static class A{ }----> Invalid
10.final claSS A{ }----> valid
11.abstract class A{ }----> valid
12.synchronized class A{ }----> Invalid
13.native class A{ }----> Invalid
14.class A{ static class B{ } }----> valid
15.class A{ abstract class B{ } }----> valid
16.class A{ strictfp class B{ } }----> valid
17.class A{ native class B{ } }----> Invalid
18.class A extends B{ }----> valid
19.class A extends A{ }----> Invalid, cyclic inheritance Error
100

20.class A extends B, C{ }----> Invalid


21.class A implements I{ }----> valid
Page

22.class A implements I1, I2{ }----> valid


23.class A implements I extends B{ }----> Invalid

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


24.class A extends B implements I{ }----> valid
25.class A extends B implements I1, I2{ }----> valid

Procedure to write classes in java applications:


1.Declare a class by using 'class' keyword.
2.Declare variables and methods in class as per the requirement.
3.In main class and in main() method , create object for the respective class.
4.Access members of the class by using the generated reference variable.

Entities[Student, Customer, Employee,...]-----> classes


Entities data[sid, sname, saddr,...] ----> variables
Entities actions or behaviours[add, search, delete,..] ----> methods

EX:
class Employee
{
String eid="E-111";
String ename="Durga";
float esal=25000.0f;
String eaddr="Hyderabad";
String eemail="durga@durgasoft.com";
String emobile="91-9988776655";

public void display_Emp_Details()


{
System.out.println("Employee Details");
System.out.println("-------------------");
System.out.println("Employee Id :"+eid);
System.out.println("Employee Name :"+ename);
System.out.println("Employee Saslary:"+esal);
System.out.println("Employee Address:"+eaddr);
System.out.println("Employee Email :"+eemail);
System.out.println("Employee Mobile :"+emobile);
}
}
class Test
{
public static void main(String[] args)
{
Employee emp = new Employee();
101

emp.display_Emp_Details();
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


There are two types of methods.
1.Concreate methods
2.Abstract methods

Q)What are the differences between Concreate methods and abstract methods?

Ans:
1. Concreate method is a method, it will have both method declaration and method implementation.

EX: void add(int i, int j)// Method Declaration


{// Method implementation started here
int k=i+j;
System.out.println(k);
}// Method Implementation ended here

Abstract method is a method, it will have only method declaration.

EX: abstract void add(int i, int j);

2. To declare concreate methods , no need to use any special keyword.


To declare abstract method , we must use abstract keyword.

3. Concreate methods are allowed in classes and in abstract classes.


abstract methods are allowed in abstract classes and interfaces.

4. Concreate methods will provide less sharability.


Abstract methods will provide more sharability.

2.Abstract Classes:
Abstract class is a java class, it able to allow zero or more no of concreate methods and zero or more
no of abstract methods.

Note: To declare abstract classes, it is not at all mandatory condition to have atleast one abstract
method, we can declare abstract classes with 0 no of abstract methods, but, if we want to declare a
method as an abstract method then the respective class must be abstract class.
102

For abstract classes, we are able to create only reference variables, we are unable to create objects.
Page

abstract class A{
----

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}

A a = new A();--> Error


A a=null;----> No Error

Abstract classes are able to provide more sharability when compared with classes.

Procedure to use abstract classes:


a)Declare an abstract class with "abstract".
b)Declare concreate methods and abstract methods in abstract class as per the requirement.
c)Declare sub class for abstract class.
d)Implement abstract methods in sub class.
e)in main class and in main() method, create object for sub class and declare reference variable
either for abstract class or for sub class.
f)Access abstract class members.

Note: If we declare reference variable for abstract class then we are able to access only abstract class
members, but, if we declare reference variable for sub class then we are able to access bothe abstract
class members and sub class members.

EX: abstract class A


{

void m1()
{
System.out.println("m1-A");
}
abstract void m2();
abstract void m3();
}
class B extends A
{
void m2()
{
System.out.println("m2-B");
}
void m3()
{
System.out.println("m3-B");
}
103

void m4()
{
Page

System.out.println("m4-B");
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
class Test
{
public static void main(String[] args)
{
//A a=new A();--> Error
A a = new B();
a.m1();
a.m2();
a.m3();
//a.m4();--> Error
B b = new B();
b.m1();
b.m2();
b.m3();
b.m4();
}
}

Q)What are the differences between concreate classes and abstract classes?

Ans:
1.Classes are able to allow only concreate methods.
Abstract classes are able to allow both concreate methods and abstract methods.

2.To declare concreate classes, only, 'class' keyword is sufficient.


To declare abstract classes we need to use 'abstract[' keyword along with class keyword.

3.For classes, we are able to create both reference variables and objects,
For abstract classes, we are able to create only reference variables, we are unable to create objects.

4.Concreate classes will provide less sharability.


Abstract classes will provide more sharability.

104

3. Interfaces:
Interface is a java feature, it able to allow zero or more nof abstract methods only.
Page

For interfaces, we are able to declare only reference variables, we are unable to create objects.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In case of interfaces, bydefault, all the variables as "public static final".

In case of interfaces, bydefault, all the methods are "public and abstract".

When compared with classes and abstract classes, iterfaces will provide more sharability.

Procedure to Use interfaces in Java applications:


a)Declare an interface with "inetrface" keyword.
b)Declare variables and methods in interface as per the requirement.
c)Declare an implementation class for interface by including "implements" keyword.
d)Provide implementation for abstract methods in implementation class which are declared in
interface.
e)In main class, in main() method, create object for implementation class ,but, declare reference
variable either for interface or for implementation class.
f)Access interface members.

Note: If declare reference variable for interface then we are able to access only interface members, we
arew unable to access implementation class own members.If we declare reference variable for
implementation class then we are able to access both interface members and implementation class own
members.
Example:
interface I
{
int x=20;// public static final
void m1();// public and abstract
void m2();// public and abstract
void m3();// public and abstract
}
class A implements I
{
public void m1()
{
System.out.println("m1-A");
}
public void m2()
{
System.out.println("m2-A");
}
public void m3()
105

{
System.out.println("m3-A");
Page

}
public void m4()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
System.out.println("m4-A");
}
}
class Test
{
public static void main(String[] args)
{
//I i=new I();---> Error
I i=new A();
System.out.println(I.x);
System.out.println(i.x);
i.m1();
i.m2();
i.m3();
//i.m4();----> Error
A a=new A();
System.out.println(a.x);
System.out.println(A.x);
a.m1();
a.m2();
a.m3();
a.m4();
}
}

Q)What are the differences between Class, abstract clacss and interface?

Ans:
1. class is able to allow concreate methods only.
Abstract class is able to allow both concreate methods and abstract methods
interface is able to allow abstract methods only.

2. To declare class, only, class keyword is sufficient.


To declare abstract class, we have to use "abstract" keyword along with class keyword.
To declare interface we have to use "interface" keyword explicitly.
106

3. For classes only, we are able to create both reference variables and objects.
For abstract classes and interfaces , we are able to declare reference variables , we are unable to
Page

create objects.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4. In case of interfaces, bydefault, all variables are "public static final".
In case of classes and abstract classes, no default cases for variables.

5. In case of interfaces, bydefault, all methods are "public and abstract".


In case of classes and abstract classes, no default cases for methods.

6. Constructors are allowed in classes and abstract classes.


Constructors are not allowed in interfaces.

7. Classes are able to provide less sharability.


Abstract classes are able to provide moddle level sharability.
Interfaces are able toprovide more sharability.

Methods In Java:
Method is a set of instructions, it will repersent a particular action in java applications.

Syntax:
[Access_Modifiers] return_Type method_Name([param_List])[throws Exception_List]
{
----- instructions to represent a particular action-----
}

Java methods are able to allow the access modifiers like public, protected, <default> and private.
Java methods are able to allow the access modifiers like static, final, abstract, native, synchronized,
strictfp.

Where the purpose of return_Type is to specify which type of data the present method is returning.In
java applications, all primitive data types, all user defined data types and 'void' are allowed for
methods as return types.
Note: 'void' return type is representing "Nothing is returned" from methods.

Where "method_name" is an identifier, it can be used to recognize the methods individually.

Where param_List can be used to pass some input data to the methods inorder to perform an action.In
java applications, we are able to provide all primitive data types and all user defiend data types as
parameter types.

Where "throws" keyword can be used to bypass or delegate the generated exception from present
107

method to caller method of the present method


Page

To describe method information, there are two approaches.


1.Method Signature

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.Method Prototype

Q)What is the difference between Method Signature and method prototype?


Ans:
Method signature is the description of the method, it includes method name and parameter list.

EX: forName(String Class_Name)

Method prototype is the description of the method, it will include access modifiers list, return type,
method name, parameters list, throws exception list.

EX:public static Class forName(String class_Name)throws ClassNotFoundException

There are two types of methods in Java w.r.t the Object state manipulations.

1.Mutator Methods
2.Accessor Methods

Q)What are the differences between Mutator methods and Accessor methods?

Ans:
Mutator methods are the java methods, which are used to set/modify data in Objects.
EX: All setXXX(--) methods in Java Bean classes are mutator methods.

Accessor methods are the java methods, which are used to get/access data from Objects.
EX: All getXXX() methods in java bean classes are Accessor methods

--- Diagram mutatorNAccessormethods.png------


Note: Java bean is a normal java class, it will include properties and the respectove setXXX(-)
methods and getXXX() methods.
Variable-Argument Method[Var-Arg method]

In general, in java applicatinos, if we declare any method with 'n' no of parameters then we must
access that method with the same 'n' no of parameter values , it is not possible to access that method by
passing 'n+1' no of parameter values and 'n-1' no of parameter values.

EX:
108

class A
{
Page

void add(int i, int j)


{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println(i+j);
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.add(10,20);// Valid.
//a.add();--> Invalid
//a.add(10);--> Invalid
//a.add(10,20,30);--> Invalid
}
}

As per the requirement, we want to access a method with variable no of parameter values[0 no of
params or 1 no of params or 2 no of params,....]

To achhieve this requirement we have to use "Var-Arg Method" provided by JDK5.0 version.

Var-Arg method is a java method including Var-Arg parameter.


Syntax for Var-Arg Parameter:

Data_Type ... Var_Name

EX for var-Arg method:

void m1(int ... a)//int[] a={---- argumentvalues-----}


{
-----
}

When we access Var-Arg method with 'n' no of parameter values then all these 'n' no of parameter
values are stored in the form of Array wehich is generated from var-ARg parameter.

EX:
109

class A
{
Page

void add(int ... a)// int[] a={--- listof arguments---}


{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("No Of Arguments :"+a.length);
int result=0;
System.out.print("Argument List :");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
result=result+a[i];
}
System.out.println();
System.out.println("Addition :"+result);
System.out.println("----------------------------");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.add();
a.add(10);
a.add(10,20);
a.add(10,20,30);
}
}

Note: In Var-Arg methods, normal parameters are allowed along with Var-ARg parameter but they
must be provided before var-Arg parameter, not after var-Arg parameter, because, var-Arg parameter
must be last parameter in var-Arg method.

Note: Due to the above reason, Var-Arg methods are able to allow atmost one Var-Arg parameter, not
allowing more tha one Var-Arg parameters.

EX:
1.void m1(int ... i, float f){ } ----> Invalid
2.void m1(float f, int ... i){ } ----> valid
3.void m1(int ... i, float ... f){ } --->Invalid

Object Creation Statement:


110

Q)What is the requirement to create Objects in Java?


Page

Ans:
1.To store entities data temporarily in java applications we need objects.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.To Access the members of any particular class we need objects.

If we want to create Objects we have to use the following syntax.

Class_Name ref_Var = new Class_Name([param_List]);

EX:
class A{
----
}

A a = new A();

When JVM encounter the above instruction,JVM will perform the following actions.
1.Creating memory for the Object
2.Generating Identities for the object
3.Providing initializations inside the Object

1.Creating Memory for the object:


When JVM encounter "new" keyword in Object creation statement then JVM will check to which class
we are creating object on the basis of onstructor name then JVM will load the respective class
bytecode to the memory[Method Area]

After loading class bytecode, JVM will identify minimal object memory size by recognizing all the
instance variables and their data types

After getting memory size, JVM will send a request to Heap manager about to creat an object with the
specified minimal memory.

As per JVM requirement,Heap Manager will create the required block of memory at Heap Memory.

2.Generating Identities for the Object:


111

After creating a block of memory[Object] for JVM requirements,Heap manager will assign an integer
value as an identity for the object called as "HashCode".
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


After getting HashCode value,Heap Manager will send that hashCode value to JVM, where JVM will
convert that hashCode value to its Hexa Decimal form called as "Reference Value".

After getting Object reference value, JVM will assign that reference value to a variable called as
"Reference Variable".

3.Providing initializations inside the Object:


After creating object and its identities,JVM will allocate memory for all the instance variables in side
the object on the basis of their data types.

After getting memory for the instance variables, JVM will provide inital values to the instance
variables by searching initializations at class level declaration and at constructor.

If any instance variable is not having initialization at both constructor and at class level declaration
then JVM will store default value on the basis of their datatype as initial value inside the object.

--- Diagram [ObjectCreation.png] ----

Note: In java applications, when a class bytecode is loaded to the memory ,automatically, JVM will
create java.lang.Class object at heap memory with the metadata of the loaded class.

Note: In java application, when we create a thread[Main Thread or User Thread], automatically, a
stack will be created at stack memory and it able to store methods details in the form of Frames which
are accessed by the respective thread.

To get hashcode value and reference value of an object we have to use the following two methods.

public native int hashCode()


public String toString()

Note: Native method is a java method , declared in java , but, implemented in non java programming
languages may be C, ASL, .....

112

EX:
class A
Page

{
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test
{
public static void main(String[] args)
{
A a=new A();
int hashCode=a.hashCode();
System.out.println("Object HashCode :"+hashCode);
String ref=a.toString();
System.out.println("Object Reference :"+ref);
}
}

OP:
Object Hashcode : 31168322
Object Reference : A@adb9742

In Java applications, there is a common and default super class for each and every java
class[predefined classes and user defiend classes] that is "java.lang.Object" class, where
java.lang.Object class contains the following 11 methodfs inorder to share to all java classes.

1.hashCode()
2.toString()
3.getClass()
4.clone()
5.equals(Object obj)
6.finalize()
7.wait()
8.wait(long time)
9.wait(long time, int time)
10.notify()
11.notifyAll()

113

Q)If we extend a class to some other class explicitly then the respective sub class is having two super
classes[default super class [Object] and explicit super class], it repersents mutltiple inheritance, how
Page

can we say multiple inheritance is not possible in JAVA?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
In java, java.lang.Object class is common and default super class for every class when that class is not
extnding from any other super class explicitly. If our class is extending some other class explicitly then
Object class is not directly super class to the the respective sub class , Object class is indirectly super
class to the respective sub class through the explicit super class , that is, Object class is not super class
to the respective sub class through Multiple Inheriance, that is through Multi Level Inheritance.

EX:
class A{
---
}
class B extends A{
---
}
Note : Here Object class is super class to A , A is super class to B
Object<--- A<--- B

In java applications, when we pass a particular class object reference variable as parameter to
System.out.println(-) method then JVM will access toString() over the provided reference variable
internally.

EX:
class A
{
}
class Test
{
public static void main(String[] args)
{
A a=new A();

String ref=a.toString();
System.out.println(ref);

System.out.println(a.toString());

System.out.println(a);//System.out.println(a.toString());
}
}
114

OP:
A@1db9742
Page

A@1db9742
A@1db9742

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above program, when we access toString() method internally or externally , first, JVM has to
execute toString(), to execute toString() method JVM will search for toString() method in the
respective class whose reference variable we passed as parameter to System.out.println(--) method, if
the required toString() method is not existed in the respective class then JVM will search for toString()
method in its super class, here if super class is not existed then JVM will search for toString() method
in the common and default super class Object class. In Object class, toString() method was
implemented insuch a way to return a string contains "Class_Name@ref_Val" .

As per the requirement, if we want to display our own data instead of Object reference value when we
pass reference variable as parameter to System.out.println(-) method then we have to provide our own
toSrtring() method in the respective class.

EX:
class Employee
{
String eid="E-111";
String ename="Durga";
float esal=50000.0f;
String eaddr="Hyd";
String eemail="durga@durgasoft.com";
String emobile="91-9988776655";

public String toString()


{
System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Id :"+eid);
System.out.println("Employee Name :"+ename);
System.out.println("Employee Salary :"+esal);
System.out.println("Employee Address :"+eaddr);
System.out.println("Employee Email :"+eemail);
System.out.println("Employee Mobile :"+emobile);
return "";
}
}
class Test
{
public static void main(String[] args)
{
115

Employee emp=new Employee();


System.out.println(emp);
Page

}
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:

--- Employee details-----

Note: In Java, some predefined classes like String, StringBuffer, Exception, Thread, all wrapper
classes, all Collection classes are not depending on Object class toString() method, they are having
their own toString() method inorder to display their own data.

EX:
class Test
{
public static void main(String[] args)
{
String str=new String("abc");
System.out.println(str);

Exception e=new Exception("My Own Exception");


System.out.println(e);

Thread t=new Thread();


System.out.println(t);

Integer in=new Integer(10);


System.out.println(in);

java.util.ArrayList al=new java.util.ArrayList();


al.add("AAA");
al.add("BBB");
al.add("CCC");
al.add("DDD");
System.out.println(al);
}
}
116

OP:
abc
Page

java.lang.Exception: My Own Exception


Thread[Thread-0,5,main]

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10
[AAA,BBB,CCC,DDD]

In JAVA, there are two types of Objects.


1.Immutable Objects
2.Mutable Objects

Q)What is the difference between Immutable object and mutable object?

Ans:
Immutable Objects are Java objects, they will not allow modifications on their content. If we are trying
to perform operations over immutable objects content then data is allowed for operations, but, the
resultent data is not stored back in original object, the modified data will be storted by creating new
Object.

EX: All String class objects are immutable objects.


All Wrapper class objects are immutable Objects.

Mutable Objects are java objects, they will allow modifications on their content directly.
EX: Bydefault, all JAVA objects are mutable objects.
EX: StringBuffer

Q)What is the differernce between String and StringBuffer?

Ans:
----- Same above asnwer for this question also-----

117

EX:
class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
String str1=new String("Durga ");
String str2=str1.concat("Software ");
String str3=str2.concat("Solutions");
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println();
StringBuffer sb1=new StringBuffer("Durga ");
StringBuffer sb2=sb1.append("Software ");
StringBuffer sb3=sb2.append("Solutions");
System.out.println(sb1);
System.out.println(sb2);
System.out.println(sb3);
}
}

OP:
Durga
Durga Software
Durga Software Solutions

Durga Software Solutions


Durga Software Solutions
Durga Software Solutions

Q)What is the difference between Object and insrtance?


Ans:
Object is a memory unit to store data.

Instance is a copy or layer of values existed in an object at a particular point of time.

---- Digram: ObjectnInstance.png-----

118

Constructors:
1.Constructor is a java feature, it can be used to create Object.
Page

2.The role of the constructors in Object creation is to provide initial values inside the object.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.In java applications, Constructors are executed exactly at the time of creating objects, not before
creating objects and not after creating objects.
4.The main utilization of constructors is to provide initializations for class level variables mainly
instance variable.
5.Constructors must have same name of the resapective class.
6.Constructors are not having return types.
7.Constructors are not allowing the access modifiers like static, final,...
8.Constructors are able to allow the access modifiers like public, protected,<default> and private.
9.Constructors are allowing 'throws' keyword in its syntax to bypass exceptions from present
constructor to the caller .

Syntax:
[Access_Modifier] Class_Name([Param_List])[throws Exception_List]
{
-----
}

Note1:
If we provide constructor name other than class name then compiler will rise an error like "Invalid
Method declaration, return type required", because, compiler has treated the provided constructor as
normal java method with out the return type, but, for methods return is mandatory.

EX:
class A
{
B()
{
System.out.println("A-Con");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
}
}
Status: Compilation Error.
119

Note2:
If we provide return type to the constructors then Compiler will not rise any error and JVM will not
Page

rise any exception and JVM will not provide any output, because, the provided constructor is

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


converted as normal java method.In this context, if we access the provided constructor as normal java
method then it will be executed as like normal java method.

EX: class A
{
void A()
{
System.out.println("A-Con");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.A();
}
}

Status: No Compialtion Error


OP: A-Con
Note3:
If we provide the access modifiers like static, final,... to the constructors then Compiler will rise an
error like "modifier xxx not allowed here".

EX: class A
{
static A()
{
System.out.println("A-Con");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();

}
}
120

Status: Compilation Error.


Page

Note4:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we declare constructor as "private" then that constructor is available upto the respective class only,
not available to out side of the respective class.
In this context, If we want to create object for the respective class then it is possible inside the same
class only.

EX: class A
{
private A()
{
System.out.println("A-Con");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
}
}

Status: Compilation Error

There are two types constructors in jaqva


1.Default Constructors
2.User Defined Constructors

1.Default Constructors:
If we have not provided any constructor explicitly in java class then compiler will provide a 0-arg
constructor automatically, here the compiler provided 0-arg constructor is called as "Default
Constructor".

If we provide any constructor explicitly then compiler will not provide any default constructor.

D:\javaapps\ Test.java
public class Test{
}
121
Page

On Command Prompt:
D:\javaapps>javac Test.java

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


D:\javaapps>javap Test
Compiled from Test.java
public class Test{
public Test(){ -----> Default constructor
}
}

Note: Default Constructors are having the same scope of the respective class.

2.User Defined Constructors:


These constructors are provided by the developers as per their application requirements.

If we provide any constructor explicictly with out parameters then that constructor is called as 0-arg
constuctor.

If we provide any constructor with atleast one parameter then that constructor is called as
parameterized Constuctor.

Note: By default, all the default constructors are 0-arg constructors, but, all 0-arg constructors are not
default constructors, some 0-arg constructors are provided by the compiler are called as Default
Constructors and some other 0-arg constuctors are provided by the users they are called as User
defined constructors.

EX:
class Employee
{
String eid;
String ename;
float esal;
String eaddr;

Employee()
{
eid="E-111";
ename="Durga";
esal=50000.0f;
eaddr="Hyd";
}

public void getEmpDetails()


122

{
System.out.println("Employee Details");
Page

System.out.println("-----------------------");
System.out.println("Employee Id :"+eid);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("Employee Name :"+ename);
System.out.println("Employee Salary :"+esal);
System.out.println("Employee Address :"+eaddr);
}
}
class Test
{
public static void main(String[] args)
{
Employee emp=new Employee();
emp.getEmpDetails();
}
}

In the above program, if we create more than one object for the Employee class by executing 0-arg
constructor then same data will be stored in all multiple objects of the Employee.

As per the requirement, if we want to create multiple Employee objects with different data then we
have to provide data to the Objects explicitly, for this we have to use parameterized constructor.

EX:
class Employee
{
String eid;
String ename;
float esal;
String eaddr;

Employee(String emp_Id, String emp_Name, float emp_Sal, String emp_Addr)


{
eid=emp_Id;
ename=emp_Name;
esal=emp_Sal;
eaddr=emp_Addr;
}

public void getEmpDetails()


{
System.out.println("Employee Details");
System.out.println("-----------------------");
123

System.out.println("Employee Id :"+eid);
System.out.println("Employee Name :"+ename);
Page

System.out.println("Employee Salary :"+esal);


System.out.println("Employee Address :"+eaddr);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}
class Test
{
public static void main(String[] args)
{
Employee emp1=new Employee("E-111", "Durga", 50000.0f, "Hyd");
emp1.getEmpDetails();
System.out.println();
Employee emp2=new Employee("E-222", "Anil", 60000.0f, "Hyd");
emp2.getEmpDetails();
System.out.println();
Employee emp3=new Employee("E-333", "Rahul", 80000.0f, "Hyd");
emp3.getEmpDetails();
}
}

Constructor Overloading:
If we declare more than one constructor with the same name and with the different parameter list then
it is called as "Constructor Overloading".

EX:
class A
{
int i,j,k;
A()
{
}
A(int i1)
{
i=i1;
}
A(int i1, int j1)
{
i=i1;
j=j1;
}
A(int i1, int j1, int k1)
{
i=i1;
124

j=j1;
k=k1;
Page

}
void add()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
System.out.println("Addition :"+(i+j+k));
}
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
a1.add();
A a2=new A(10);
a2.add();
A a3=new A(10,20);
a3.add();
A a4=new A(10,20,30);
a4.add();
}
}

Note: If we declare more than one method with the same name and with different parameter list then it
is called as "Method Overloading"

Instance Context/Instance Flow of execution:


In Java,for every class loading a seperate context will be creaed called as Static Context and for every
Object a separate context will be created called as Instance context.

In Java,instance context is represented in the form of the following elements.

1.Instance Variables
2.Instance Methods
3.Instance Blocks

125
Page

1.Instance Variables:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Instance Variable is a normal Java variable,whose values will be varied from one instance to
another instance of an object.

Instance Variable is a variable,which will be recognized and initialized just before executing the
respective class constructor.

In Java applications,instance variables must be declared at class level and non-static, instance
variables never be declared as local variables and static variables.

In Java applications, instance variables data will be stored in Object memory that is in "Heap
Memory".

2.Instance Methods:
Instance Method is a normal Java method,it is a set of instructions,it will represent an action of an
entity.
In Java applications,instance methods will be executed when we access that method.In Java
applications,all the methods wont be executed with out the method call.

EX:
class A{
int i=m1();
A(){
System.out.println("A-Con");
}
int m1(){
System.out.println("M1-A");
return 10;
}
}
class Test{
public static void main(String args[]){
A a =new A();
}
}
OP:
M1-A
A-con
126
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A {
int j=m1();
int m2(){
System.out.println("m2-A");
return 10;
}
A(){
System.out.println("A-con");
}
int m1(){
System.out.println("m1-A");
return 20;
}
int i=m2();
}
class Test{
public static void main(String args[]){
A a =new A();
}
}

OP: m1-A
m2-A
A-con

3.Instance Block:
Instance Block is a set of instructions which will be recognized and executed just before executing
the respective class constructors.
Instance Block as are having the same power of constructors,it can be used as like constructors.

Syntax:
{
---instructions----
} 127
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A {
A(){
System.out.println("A-CON");
}
{
System.out.println("IB-A");
}
}
class Test{
public static void main(String args[]){
A a=new A();
}
}

OP:
IB-A
A-CON

EX:
class A {
A(){
System.out.println("A-CON");
}
{
System.out.println("IB-A");
}
int m1(){
System.out.println("m1-A");
return 10;
}
int i=m1();
}
class Test{
public static void main(String args[]){
A a=new A();
}
}

OP: IB-A
m1-A
128

A-CON
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A{
int m1(){
System.out.println("m1-A");
return 10;
}
{
System.out.println("IB-A");
}
int i=m2();
A(){
System.out.println("A-con");
}
int i=m1();
{
System.out.println("IB1-A");
}
int m2();
{
System.out.println("m2-A");
return 20;
}}
class Test{
public static void main(String args[]){
A a1=new A();
A a2=new A();
}
}
OP:
IB-A
m2-A
m1-A
IB1-A
A-con
IB-A
m2-A
m1-A
IB1-A
A-con
129
Page

'this' keyword:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


'this' is a Java keyword,it can be used to represent current class object.

In Java applications,we are able to utilize 'this' keyword in the following four ways.

1.To refer current class variable


2.To refer current class methods
3.To refer current class constructors
4.To refer current class object

1.To refer current class variables:


If we want to refer current class variables by using 'this' keyword then we have to use the following
syntax.

this.var_Name

NOTE:In Java applications,if we provide same set of variables at local and at class level and if we
access that variables then JVM will give first priority for local variables,if local variables are not
available then JVM will search for that variables at class level, even at class level also if that variables
are not available then JVM will search at super class level.At all the above locations,if the specified
variables are not available then compiler will rise an error.

NOTE:In Java applications,if we have same set of variables at local and at class level then to access
class level variables over local variables we have to use 'this' keyword.

EX:
class A{
int i=10;
int j=20;
A(int i,int j) {
System.out.println(i+" "+j);
System.out.println(this.i+" "+this.j);
}
}
class Test{
public static void main(String args[]){
A a=new A(30,40);
}}
OP:
30 40
10 20
130
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:In general,in enterprise applications,we are able to write no. of Java bean classes as per
application requirement.In Java bean classes,we are able to provide variables and their setter methods
and getter methods.In Java bean classes,in setter methods, we have to declare parameter variable with
the same name of the respective class level variable, here we have to transfer data from local variabe to
class level variable, for this, we have to assign local variable to class level variable.In this context, to
refer class level variable over local variable seperately we have to use 'this' keyword. In getter
methods,always,we have to return class level variables only , so that, it is not required to use 'this'
keyword.

EX: class User{


private String uname;
private String upwd;
public void setUname(String uname) {
this.uname=uname;
}
public void setUpwd(String upwd) {
this.upwd=upwd;
}
public getUname() {
return uname;
}
public getUpwd(){
}
}
class Test{
public static void main(String[] args){
User u=new User();
u.setUname("abc");
u.setUpwd("abc123");
System.out.println("User Login Details");
System.out.println("----------------------");
System.out.println("User Name :"+u.getUname());
System.out.println("Password :"+getEaddr());
}
} 131
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: class Employee
{
private String eid;
private String ename;
private float esal;
private String eaddr;

public void setEid(String eid)


{
this.eid=eid;
}
public void setEname(String ename)
{
this.ename=ename;
}
public void setEsal(float esal)
{
this.esal=esal;
}
public void setEaddr(String eaddr)
{
this.eaddr=eaddr;
}

public String getEid()


{
return eid;
}
public String getEname()
{
return ename;
}
public float getEsal()
{
return esal;
}
public String getEaddr()
{
return eaddr;
}
132

}
class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
Employee emp=new Employee();
emp.setEid("E-111");
emp.setEname("AAA");
emp.setEsal(5000.0f);
emp.setEaddr("Hyd");

System.out.println("Employee Details");
System.out.println("---------------------");
System.out.println("Employee Id :"+emp.getEid());
System.out.println("Employee Name :"+emp.getEname());
System.out.println("Employee Salary :"+emp.getEsal());
System.out.println("Employee Address :"+emp.getEaddr());
}
}

2.To refer current class method:


If we want to refer current class method by using 'this' keyword then we have to use the following
syntax.

this.method_Name([param_List]);

Note: To access current class methods, it is not rewquired to use any reference variable and any
keyword including 'this', directly we can access.

EX:
class A{
void m1(){
System.out.println("m1-A");
}
void m2(){
System.out.println("m2-A");
m1();
this.m1();
}
}
class Test{
public static void main(String args[]){
A a=new A();
a.m2();
133

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
m2-A
m1-A
m1-A

3.To refer current class constructors:


If we want to refer current class constructor by using 'this' keyword then we have to use the
following syntax.

this([param_List]);

EX:
class A{
A(){
this(10);
System.out.println("A-0-arg-con");
}
A(int i){
this(22.22f);
System.out.println("A-int-param-con");
}
A(float f){
this(33.3333);
System.out.println("A-float-param-con");
}
A(double d){
System.out.println("A-double-param-con");
}
}
class Test{
public static void main(String args[]){
A a=new A();
}
}

OP:
A-double-param-con
A-float-param-con
A-int-param-con
A-0-arg-con
134
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:In the above program we have provided more than one constructor with the same name and
with the different parameter list,this process is called as "Constructor Overloading".
In the above program,we have called all the current class constructors by using 'this' keyword in chain
fashion,this proccess is called as "Constructor Chaining".

NOTE:If we want to access current class constructor by using 'this' keyword then the respective 'this'
statement must be provided as first statement, if we have not provided 'this' statement as first statement
then compiler will rise an error like 'call to this must be first statement in constgructor'.

EX:
class A{
A(){

System.out.println("A-0-arg-con");
this(10);
}
A(int i){

System.out.println("A-int-param-con");
this(22.22f);
}
A(float f){

System.out.println("A-float-param-con");
this(33.3333);
}
A(double d){
System.out.println("A-double-param-con");
}
}
class Test{
public static void main(String args[]){
A a=new A();
}
}
Status: Compilation Error

NOTE:If we want to refer current class constructor by using 'this' keyword then the respective 'this'
statement must be provided in the current class another constructor only,not in normal Java methods.If
we voilate this condition then compiler will rise an error like 'call to this must be firststatement in
135

constructors'.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
A()
{
System.out.println("A-0-arg-con");
}
A(int i)
{
System.out.println("A-int-param-con");
}
void m1()
{
this(10);
System.out.println("m1-A");
}
}
class Test
{
public static void main(String args[])
{
A a=new A();
a.m1();
}
}

Status: Compilation Error.

Q)Is it possible to refer more than one current class constructors by using 'this' keyword from a single
current class constructor?

Ans:
No, It is notpossible to refer more than one current class constructors by using 'this' keyword, because,
in constructors, 'this' statement must be first statement while referring current class constructors. If we
provide more than one time this(---) statement then only one this() statement is first statement among
multiple this statements,in this case, compiler will rise an error like 'call to this must be first statement'.
136
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
A()
{
this(10);
this(22.22f);
System.out.println("A-0-arg-con");
}
A(int i)
{
System.out.println("A-int-param-con");
}
A(float f)
{
System.out.println("A-float-param-con");
}
}
class Test
{
public static void main(String args[])
{
A a=new A();
}
}

Status: Compilation Error.

137
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.To return Current class Object:
To return current class object by using 'this' keyword thn we have to use the followng syntax.

return this;

EX:
class A{
A getRef1(){
A a=new A();
return a;
}
A getRef2(){
return this;
}
}
class Test{
public static void main(String args[]){
A a=new A();//[a=abc123]
System.out.println(a);
System.out.println();
System.out.println(a.getRef1());//[abc123.getRef1()]
System.out.println(a.getRef1());//[abc123.getRef1()]
System.out.println(a.getRef1());//[abc123.getRef1()]
System.out.println();
System.out.println(a.getRef2());//[abc123.getRef2()]
System.out.println(a.getRef2());//[abc123.getRef2()]
System.out.println(a.getRef2());//[abc123.getRef2()]
}
}

OP:
A@5e3a78ad

A@50c8d62f
A@3165d118
A@138297fe

A@5e3a78ad
A@5e3a78ad
A@5e3a78ad
138
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above program, for every call of getRef1() method JVM will encounter "new" keyword,JVM
will create new Object for class A every time and JVM will return new object reference value every
time.This approach will increase no. of objects in Java application,it will not provide Objects
reusability, it will provide object duplication, it is not suggestible in application development.

In the above program,for every call of getRef2() method JVM will encounter "return this"
statement,JVM will not create new Object for class A every time,JVM will return the same reference
value on which we have called getRef2() method.This approach will increase Objects reusability.

'static' keyword:
'static' is a Java keyword,it will improve sharability in Java applications.

In Java applications, static keyword will be utilized in the following four ways.

1.Static variables
2.Static methods
3.Static blocks
4.Static import

1.Static variables:
Static variables are normal Java variables,which will be recognized and executed exactly at the time
of loading the respective class bytecode to the memory.

Static variables are normal java variables,they will share their last modified values to the future
objects and to the past objects of the respective class.

In Java applications,static variables will be accessed either by using the respective class reference
variable or by using the respective class name directly.

NOTE:To access static variables we can use the respective class reference variable which may or may
not have reference value.To access static variables it is sufficient to take a reference variable with null
value.

NOTE:If we access any non-static variable by using a reference variable with null value then JVM
will rise an exception like "java.lang.NullPointerException". If we access static variable by using a
reference variable contains null value then JVM will not rise any exception.
In Java applications,static variables must be declared as class level variables only ,they never be
declared as local variables.
In Java applications,static variable vlaues will be stored in method area, not in Stack memory and not
139

in Heap Memory.
In Java applications,to access current class static variables we can use "this" keyword.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
static int i=10;
int j=10;
void m1(){
//static int k=30;--->error
System.out.println("m1-A");
System.out.println(this.i);
}
}
class Test{
public static void main(String args[]){
A a=new A();
System.out.println(a.i);
System.out.println(A.i);
a.m1();
A a1=null;
//System.out.println(a1.j);--->NullPointerException
System.out.println(a1.i);
}
}
OP:
10
10
m1-A
10
10

140
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
static int i=10;
int j=10;
}
class Test{
public static void main(String args[]){
A a1=new A();
System.out.println(a1.i+" "+a1.j);
a1.i=a1.i+1;
a1.j=a1.j+1;
System.out.println(a1.i+" "+a1.j);
A a2=new A();
System.out.println(a2.i+" "+a2.j);
a2.i=a2.i+1;
a2.j=a2.j+1;
System.out.println(a1.i+" "+a1.j);
System.out.println(a2.i+" "+a2.j);
A a3=new A();
System.out.println(a3.i+" "+a3.j);
a3.i=a3.i+1;
a3.j=a3.j+1;
System.out.println(a1.i+" "+a1.j);
System.out.println(a2.i+" "+a2.j);
System.out.println(a3.i+" "+a3.j);
}}

OP:
10 10
11 11
11 10
12 11
12 11
12 11
12 10
13 11
13 11
13 11
NOTE:In Java applications,Instance variable is specific to each and every object that is a separate
copy of instance variables will be maintained by each and every object but static variable is common
141

to every object that is the same copy of static variable will be maintained by all the objects of the
respective class.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: In Java, for a particular, class Byte-Code will be loaded only one time but we can create any
no.of objects.

2.Static Methods:
Static method is a normal java method,it will be recognized and executed the time when we access
that method.
Static methods will be accessed either by using reference variable or by using the respective class
name directly.

Note: In the case of accessing static methods by using reference variables,reference variable may or
may not have object reference value,it is possible to access static methods with the reference variables
having 'null' value. If we access non-static method by using a reference variable contains null value
then JVM

will rise an exception like "java.lang.NullPointerException".

Static methods will allow only static members of the current class,static methods will not allow non-
static members of the current class directly.

Note:If we want to access non-static members of the current class in static methods then we have to
create an object for the current class and we have to use the generated reference variable.

Static methods are not allowing 'this' keyword in its body but to access current class static methods we
are able to use 'this' keyword.

EX:
class A{
int i=10;
static int j=20;
static void m1(){
System.out.println("m1-A");
System.out.println(j);
//System.out.println(i);---->error
//System.out.println(this.j);----------->error
A a=new A();
System.out.println(a.i);
}
void m2(){
System.out.println("m2-A");
this.m1();
142

}
}
Page

class Test{
public static void main(String[] args){

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


A a=new A();
a.m1();
a=null;
a.m1();
A.m1();
}
}

OP:
m1-A
20
10
m1-A
20
10
m1-A
20
10

Q)Is it possible to print a line of text on command prompt with out using main() method?

Ans:
Yes,it is possible to display a line of text on command prompt with out using main() method, but, by
using static variable and static method combination.

EX:
class Test{
static int i=m1();
static int m1(){
System.out.println("Welcome to durga software soultions");
System.exit(0);//to terminate the application
return 10;
}
}

OP:
Welcome to durga software soultions
143
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we provide 'Test' class name along with 'java' command on command prompt then JVM will take
main class from command prompt,JVM will search for its .class file,if it is available then JVM will
load main class bytecode to the memory that is Test class bytecode. At the time of loading Test class
bytecode to the memory, JVM will recognize and initialize static variable, as part of initialization,
JVM will execute static method. By the execution of static method,JVM will display the required
message on command prompt, when JVM encounter System.exit(0) statement then JVM will terminate
the application.

NOTE:The above question and answer are valid upto JAVA6 version, it is invalid from JAVA7
version, because, In JAVA6 version JVM will load main class bytecode to the memory irrespective of
main() method availability. In JAVA7, first, JVM will check whether main() method is existed or not
in main class, if main() method is available then only JVM will load main class bytecode to the
memory, if main() method is not available in main class then JVM will not load main class bytecode to
the memory and JVM will provide the following error message.

Error:Main Method not found in class Test,please define the main method as:
public static void main(String args[])

3.Static Block:
Static Block is a set of instructions,which will be recognized and executed at the time of loading the
respective class bytecode to the memory.
Static blocks are able to allow static members of the current class directly, Static blocks are not
allowing non-static members of the current class directly.

Note:If we want to access non-static members of the current class in static block then we must create
object for the respective class and we have to use the generated reference variable.

Static blocks are not allowing 'this' keyword in its body.

144
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
int i=10;
static int j=20;
static{
System.out.println("SB-A");
System.out.println(i);//-------->Error
A a=new A();
System.out.println(a.i);
System.out.println(j);
System.out.println(this.j);-------->Error
}
}
class Test{
public static void main(String[] args){
A a=new A();
}
}

OP:
SB-A
10
20

Q)Is it Possible to print a line of text on command prompt with out using main() method,static variable
and static method?

Ans:
Yes,it is possible to display a line of text on command prompt without using main() method,static
variable,static method but by using static block.

EX:
class Test{
static{
System.out.println("Welcome to DurgaSoftware Soultions");
System.exit(0);//To terminate the programme
}
}
OP:
Welcome to DurgaSoftware Soultions
145
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we provide main class name 'Test' along with 'java' command on command prompt then JVM will
take main class name i.e Test and JVM will search for its .class file.If Test.class file is identified then
JVM will load its bytecode to the memory, at the time of loading main class bytecode to the memory
static block will be executed, with this, the required message will be displayed on command prompt.
When JVM encounter System.exit(0) then JVM will terminate the program execution.

NOTE:The above question and answer are valid upto JAVA6 version, they are invalid from JAVA7
version onwards, because, in JAVA6 version JVM will load main class bytecode to the memory with
out checking main() method availability but in JAVA7 , first, JVM will search for main() method , if it
is available then only JVM will load main class bytecode to the memory, if it is not existed then JVM
will provide the following Error message.

Error:Main method not found in class Test,please define the main method as:
public static void main(String args[])

Q)Is it possible to display a line of text on command prompt with out using main() method,static
variable,static method,static block?

Ans:
Yes,it is possible to display a line of text on command prompt with out using main() method,a static
variable,a static method and static block but by using "static Anonymous Inner class of Object class".

EX:
class Test{
static Object obj=new Object(){
{
System.out.println("Welcome To durga Software Solutions");
System.exit(0);//TO termiante the application.
}
};
}
OP:
JAVA6:Welcome to Durga Software Soultions
JAVA7:Error:main method not found in class Test,please define the main method as:
public static void main(String[] args)
146
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.static import:
In Java,applications,if we import a particular package to the present java file then it is possible to
access all the classes and interfaces of that package directly with out using package name every time as
fully qualified name.

If we want to access classes and interfaces of a particular package with out importing then we must use
fully Qualified name every time that is we have to use package name along with class names.

A java program With out import statement:


java.io.BufferedReader br=new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

A java program With import statement:


import java.io.*;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

In Java applications, if we want to access static members of a particular class in present java file then
we must use either reference variable of the respective class or directly class name.

In Java applications,if we want to access static members without using the respective class name and
with out using the respective class reference variable then we have to import static members of that
respective class in the present Java file.

To import static members of a particular class in the present java file, JDK 5.0 version has provided a
new feature called as "static import".

Syntaxes:
1.import static package_Name.Class_Name_Or_Interface_Name.*;
--> It will import all the static members from the specified class or interface.
2.import static package_Name.Class_Name_Or_Interface_Name.member_Name;
It will import only the specified member from the specified class or interface.

147
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import static java.lang.Thread.*;
import static java.lang.System.out;
class Test{
public static void main(String args[]){
out.println(MIN_PRIORITY);
out.println(MAX_PRIORITY);
out.println(NORM_PRIORITY);
}
}
OP:
1
10
5

Static Context / Static Flow of Execution:

In Java,Static Context will be represented in the form of the following three elements.
1.Static variables.
2.Static methods.
3.Static blocks
In Java applications,instance context will be created separately for each and every object but static
context will be created for each and every class.

In Java applications,static context will be recognized and executed exactly at the time of loading the
respective class bytecode to the memory.
In Java applications,when we create object for a particular class,first,JVM has to access
constructor,before executing constructor,JVM has to load the respective class bytecode to the memory.
At the time of loading class bytecode to the memory,JVM has to recognize and execute static context.

148
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
static {
System.out.println("SB-A");
}
static int i=m1();
static int m1(){
System.out.println("m1-A");
return 10;
}
}
class Test{
public static void main(String args[]){
A a=new A();
}
}
OP:
SB-A
m1-A
EX:
class A{
static int i=m2();
static int m1(){
System.out.println("m1-A");
return 10;
}
static{
System.out.println("SB-A");
}
static int m2(){
System.out.println("m2-A");
return 20;
}
static int j=m1();
}
class Test{
public static void main(String args[]){
A a1=new A();
A a2=new A();
}
149

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
m2-A
SB-A
m1-A

EX:
class A{
static int i=m2();
A(){
System.out.println("A-con");
}
int m1(){
System.out.println("m1-A");
return 10;
}
static{
System.out.println("SB-A");
}
int j=m1();{
System.out.println("IB-A");
}
static int m2(){
System.out.println("m2-A");
return 10;
}
}
class Test{
public static void main(String args[]){
A a1=new A();
A a2=new A();
}
}
OP:
m2-A
SB-A
m1-A
IB-A
A-con
m1-A
IB-A
150

A-con
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Factory Method:
Factory Method is a method,it can be used to return the same class Object where we have declared that
method.
Factory Method is an idea provided by a design pattern called as "Factory Method Design Pattern".

NOTE:Design pattern is a System,it will provide problem definition and its solution inorder to solve
design problems.

EX:
class A{
private A(){
System.out.println("A-con");
}
void m1(){
System.out.println("m1-A");
}
static A getRef()//Factory Method
{
A a=new A();
return a;
}
}
class Test{
public static void main(String args[]){
A a=A.getRef();
a.m1();
}
}
OP:
A-con
m1-A

151
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


There are two types of Factory Methods

1.Static Factory Method


2.Instance Factory Method

Static Factory Method:


Static Factory Method is a static method returns the same class object.

EX:
Class c=Class.forName(--);
NumberFormat nf=NumberFormat.getInstance(-);
DateFormat df=DateForamt.getInstance(--);
ResourceBundle rb=ResourceBundle.getBundle(--);

Instance Factory Method:


If any non-static method returns the same class object then that method is called as "Instance
Factory Method".

EX: Allmost all the String class methods are Instance Factory methods.
String str=new String("DurgaSoftware Solutions");
String str1=str.concat(" Hyderabad");
String str2=str.trim();
String str3=str.toUpperCase();
String str4=str.substring(5,14);

Singleton Class:
If any JAVA class allows to create only one Object then that class is called as "Singleton Class".
Singleton Class is an idea provided by a design pattern called as "Singleton Design Pattern".

152
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX1: class A{
static A a=null;
private A(){
}
static A getRef(){
if(a==null){
a=new A();
return a;
}
else{
return a;
}
}
}
class Test{
public static void main(String args[]){
System.out.println(A.getRef());
System.out.println(A.getRef());
System.out.println(A.getRef());
}
}
OP: A@a6eb38a
A@a6eb38a
A@a6eb38a
Another Alternative for Singleton Class:
class A{
static A a=null;
static{
a=new A();
}
private A(){
}
static A getRef(){
return a;
}
}
class Test{
public static void main(String args[]){
System.out.println(A.getRef());
System.out.println(A.getRef());
153

System.out.println(A.getRef());
}
Page

}
OP:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


A@a6eb38a
A@a6eb38a
A@a6eb38a

Alternative Logic for Singleton Class:

class A{
static A a=new A();
private A(){
}
static A getRef(){
return a;
}
}
class Test{
public static void main(String args[]){
System.out.println(A.getRef());
System.out.println(A.getRef());
System.out.println(A.getRef());
}}
OP:
A@69cd2e5f
A@69cd2e5f
A@69cd2e5f

MVC is a design pattern, it will provide a standard structer to prepare web applications/GUI
applications, where in MVC based applications we must use a servlet/ filter[ A Java class] as
controller, a set of JSP pages/Html pages as view part and a java bean or EJb component or JDBC
program or Hibernate program as Model component. As per MVC Arch rules and regulations, only
one controller must be provided for application, that is, the class which we used as controller must
provide one object, therefore, controller class must be singleton class.

---- Diagram: mvc.png-----

154
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX1: Struts is MVC based Framework, where "ActionServlet" is controller, so it is Singleton class.
EX2: JSF[Java Server Faces] is MVC based framework, where "FacesServlet" is controller, so it is
Singleton class.
---
---

Class.forName(--)

Consider the following program


class A
{
static
{
System.out.println("Class Loading");
}
A()
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args)throws Exception
{
A a=new A();
}
}

When we access a constructor along with "new" keyword then JVM will perform the following actions
automatically.

1.JVM will load the respective class bytecode to the memory.


2.JVM will create object for the loaded class.

As per the requirement, if we want to load class byte code to the memory with out creating object then
we have to use the following method from java.lang.Class class.

public static Class forName(String class_Name)throws ClassNotFoundException

EX: Class c=Class.forName("A");


155
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


When JVM encounter the above instruction, JVM will perform the following actions.

1.JVM will take class name from forName(-) method.


2.JVM will serach for its .class file at current location, at java predefined library and at the
locations refered by "classpath" environment variable.
3.If the required .class file is not available at all the above locations then JVM will rise an
exception like "java.lang.ClassNotFoundException".
4.If the required .class file is available at either of the above locations then JVM will load its
bytecode to the memory.
5.After loading class bytecode to the memory, JVM will take metadata of the loaded class like
class name, super class details, implemented interfaces details, variables details, methods
details,.... and JVM will store them by creating java.lang.Class object in heap memory and
JVM will returen the generated Class object reference value from Class.forName(-);

EX:
class A
{
static
{
System.out.println("Class Loading");
}
A()
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args)throws Exception
{
Class c=Class.forName("A");
}
}

OP:
Class Loading

After loading class bytecode by using Class.forName(-) method, if we want to create object explicitly
then we have to use the following method.
156

public Object newInstance()throws InstantiationException, IllegalAccessException


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: Object obj=c.newInstance();

When JVM encounter the above instruction, JVM will pewrform the following actions.
1.JVM will goto the loaded class bytecode and JVM will check whether
0-arg and non-private constructor is existed or not.
2.If 0-arg and non-private constructor is existed then JVM will execute that constructor and JVM
will create object for the loaded class.
3.If the constructor parameterized constructor with out 0-arg constructor then JVM will rise an
excewption like "java.lang.InstantiationException".
4.If the constructor is private constrictor then JVM will rise an exception like
"java.lang.IllegalAccessException".

Note:If the constructor is both parameterized and 0-arg then JVM will rise
"java.lang.InstaitiationException" only.

EX:
class A
{
static
{
System.out.println("Class Loading");
}
A()
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args)throws Exception
{
Class c=Class.forName("A");
Object obj=c.newInstance();
}
}

OP:
Class Loading
Object Creating
157
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In JDBC Appl, we are going to use Driver to map JAVA representations to Database representations
and Database representations to Java representations. In Jdbc applications, we must load driver class,
not to create object for Driver class, for this, we have to use
"Class.forName(-)"

In general, all server side components like Servlets, JSPs, EJBs,... are executed by the
server[Container] by following their lifecycle actions like loading, instantiation, innitialization,....... In
this context, to perform server side components loading Container will use
"Class.forName(-)" method and to perform instantiation lifecycle action container will use
"newInstance()" method internally.

Final Keyword:
final is a Java Keyword it can be used to declare constant expressions.
In java applications, 'final' keyword is able to improve security.

In Java applications, there are three ways to utilize 'final' keyword.


1.final variable
2.final method
3.final class

1.final variable:
final variable is a variable,it will not allow modifications on its value.

EX:
final int i=10;
i=i+10;----> Compilation Error

EX:
for(final int i=0;i<10;i++) ----> Compilation Error
{
System.out.println(i);
}

NOTE:In general, in bank applications, after creating an account it is possible to change the account
details like account name, address details....but it is not possible to update 'accNo' value once it is
created. Due to this reason, we have to declare 'accNo' variable as 'final' variable.
158
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.final method:
final method is a Java method,it will not allow method overriding.
In method overriding, we have to provide same method with different implementation at both super
class and at sub class, where super class method never be declared as final irrespective of sub class
method final.

EX1:
class A{
final void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String[] args){
A a = new B();
a.m1();
}
}

Status: Compilation Error.


EX2: class A{
final void m1(){
System.out.println("m1-A");
}
}
class B extends A{
final void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String[] args){
A a = new B();
a.m1();
}
159

}
Status: Compilation Error.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX3:
class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
final void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String[] args){
A a = new B();
a.m1();
}
}

Status: No Compilation Error.

3.final class:
Final class is a Java class,it will not allow inheritance.
In Java applications,super classes never be declared as final classes,but sub classes may be final.

EX:
final class A
{
}
class B extends A
{
}

Status:Invalid

EX:
final class A
{
}
final class B extends A
{
160

}
Status:Invalid
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
}
final class B extends A
{
}

Status:Valid

In Java applications to declare constant variables Java has provided a convention like to declare
constants with "public static final".

EX:
In System Class:
public static final PrintStream out;
public static final InputStream in;
public static final PrintStream err;

In Thread Class:
public static final int MIN_PRIORITY=1;
public static final int NORM_PRIORITY=5;
public static final int MAX_PRIORITY=10;

EX:
class User_Status{
public static final String AVAILABLE="Available";
public static final String BUSY="Busy";
public static final String IDLE="Idle";
}
class Test{
public static void main(String args[]){
System.out.println(User_Status.AVAILABLE);
System.out.println(User_Status.BUSY);
System.out.println(User_Status.IDLE);
}
}
OP:
Available
Busy
161

Idle
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To declare constant variables in Java applications if we use the above convention then we are able to
get the following problems.

1.We must declare "public static final" for each and every constant variable explicitly.
2.It is possible to allow multiple data types to represent one type,it will reduce typedness in Java
applications.
3.If we access constant variables then these variables will display their values,here constant variable
values may or may not reflect the actual meaning of constant variables.

To overcome all the problems,we have to go for "enum".


In case of enum,

1.All the constant variables are by default "public static final",no need to declare explicitly.
2.All the constant variables are by default the same enum type,it will improve Typedness in Java
applications.
3.All the constant variables are by default "Named Constants" that is,these constant variables are
displaying their names instead of their values.

Syntax:
[Access_modifier] enum Enum_Name
{
----- List of constants-----
}

EX:
enum User_Status{
AVAILABLE,BUSY,IDLE;
}
class Test{
public static void main(String args[]){
System.out.println(User_Status.AVAILABLE);
System.out.println(User_Status.BUSY);
System.out.println(User_Status.IDLE);
}
}

OP:
Available
Busy
Idle
162
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:The default super class for every enum is “java.lang.Enum” class and “Object” class is Super
class to “Enum” class.
If we compile the above Java file then Compiler will translate "User_Status" enum into "User_Status"
final class like below.
final class User_Status extends java.lang.Enum{
public static final MailStatus AVAILABLE;
public static final MailStatus BUSY;
public static final MailStatus IDLE;
---------
}

NOTE: In Java, java.lang.Object class is common and default super class for all the classes.
Similarly,All the Java enums are having a common and default super class that is "java.lang.Enum".
NOTE: In Java applications,it is possible to implement inheritance between two classes but it is not
possible to implement inheritance between two "enums", because, bydefault, enums are final classses.

In Java applications,we can utilize enum like as classes,where we can provide normal
variables,methods,constructors....

EX
enum Apple{
A(500),B(250),C(100);
int price;
Apple(int price){
this.price=price;
}
public int getPrice(){
return price;
}
}
class Test{
public static void main(String args[]){
System.out.println("A-Grade Apple :"+Apple.A.getPrice());
System.out.println("B-Grade Apple :"+Apple.B.getPrice());
System.out.println("C-Grade Apple :"+Apple.C.getPrice());
}
}

OP: A-Grade Apple :500


B-Grade Apple :250
163

C-Grade Apple :100


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we compile the above programme,then compiler will translate enum into the following class:
final class Apple extends Enum{
public static final Apple A=new Apple(500);
public static final Apple B=new Apple(250);
public static final Apple C=new Apple(100);
int price;
Apple(int price){
this.price=price;
}
public int getPrice(){
return price;
}
----
}

EX: enum Book{


A(500,250),B(300,150),C(200,100);
int no_of_pages;
int cost;
Book(int no_of_pages,int cost){
this.no_of_pages=no_of_pages;
this.cost=cost;
}
public void getBookDetails(){
System.out.println(no_of_pages+"--------->"+cost);
}
}
class Test{
public static void main(String args[]){
System.out.println("Durga Books Store");
System.out.println("-------------------");
System.out.println("No of Pages Cost");
System.out.println("-------------------");
Book.A.getBookDetails();
Book.B.getBookDetails();
Book.C.getBookDetails();
}
}
164
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
Durga Books Store
---------------------------
No of Pages Cost
---------------------------
500------------->250
300------------->150
200------------->100

If we compile the above program,then compiler will translate the enum


Into the following class
Translated Code for the above enum(Book):
final class Book extends Enum{
public static final Book A=new Book(500,250);
public static final Book B=new Book(300,150);
public static final Book C=new Book(200,100);
int cost;
int no_of_pages;
Book(int no_of_pages,int cost){
this.no_of_pages=no_of_pages;
this.cost=cost;
}
public void getBookDetails(){
System.out.println(no_of_pages+"--------->"+cost);
}
----
}

Importance of main() method in Java:


The main intention of main() method in Java applications is,
1.To define application logic in Java program.
2.To define starting point and ending point for the applications execution.

Syntax:
public static void main(String args[])
{
----application logic---
}
Note: Main() method is not predefined method and it is not user defined method,it is a conventional
method with fixed prototype and with user defined implementation.
165

In Java,JVM is implemented in such a way to access main() method automatically in order to execute
application logic.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)What is the requirement to declare main() method as public?
Ans:
In Java applications,JVM has to access main() method inorder to start application execution. To access
main() method by JVM first main() scope must be available to JVM.In this context,to bring main()
method scope to JVM,we must declare main() method as "public".

Case-1:
If main() method is declared as "private" then main() method will be available upto the main class only
,not to JVM.

Case-2:
If main() method is declared as "<default>" then main() method will be available upto the package
where main class is existed, not to the JVM.

Case-3:
If main() method is declared as "protected" then main() method will be available upto the package
where main class is existed and upto child classes available in other packages but not to the JVM.

Case-4:
To make available main() method to JVM,only one possibility we have to take that is "public", where
public members are available through out our system, so that, JVM can access main() method to start
application execution.

NOTE:In Java applications,if we declare main() method with out "public" then compiler will not rise
any error but JVM will provide the following.
JAVA6:Main Method not public.
JAVA7:Error:Main method not found in class Test,please define main method as:
public static void main(String args[])

Q)What is the requirement to declare main() method as "static"?

Ans:
In Java applications,to start application execution JVM has to access main() method.JVM was
implemented in such a way that to access main() method by using the respective main class directly.

In Java applications, only static methods are eligible to access by using their respective class name,so
that,as per the JVM predefined implementation we must declare main() method as static.

NOTE:In Java applications,if we declare main() method without "static" then compiler will not rise
166

any error but JVM will provide the following.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JAVA6: Java.lang.NoSuchMethodError:main
JAVA7: Error:Main method is not static in class Test,please define main method as:
public static void main(String[] args)

Q)What is the requirement to provide "void" as return type to main() method?

Ans:
In Java applications,as per Java conventions,JVM will start application execution at the starting point
of main method and JVM will terminate application execution at the ending point of main()
method.Due to this convention,we must start application logic at the starting point of main() method
and we must terminate application logic at the ending point of main() method.To follow this Java
convention we must not return any value from main() method, for this,we must provide "void" as
return type.

NOTE:In Java applications,if we declare main() method with out void return type then compiler will
not rise any error but JVM will provide the following

JAVA6: java.lang.NoSuchMethodError:main
JAVA7:Error:Main method must return a value of type void in class Test,please define the
main method as:
public static void main(String[] args)

NOTE:The name of this method "main" is to show the importance of this method.

Main method parameters:


Q)What is the requirement to provide parameter to main() method?

Ans:
In Java applications,there are three ways to provide input to the Java programs.

1.Static Input
2.Dynamic Input
3.Command Line Input
167
Page

1.Static Input:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Providing input to the Java program at the time of writing Java program.

EX:
class Test
{
int i=10;
int j=20;
void add()
{
System.out.println(i+j);
}
}

2.Dynamic Input:
Providing Input to the Java program at runtime.

D:\Java7>javac Add.java
D:\java7>java Add
First value : 10
Second value :20
Addition :30

3.Command Line Input:


Providing input to the Java program along with "java" command on command prompt.
EX:
D:\java7>javac Add.java
D:\java7>java Add 10 20
Addition : 30

If we provide command line input like above in Java applications then JVM will perform the following
actions.
a)JVM will read all the command line input at the time of reading main class name from command
prompt.
b)JVM will store all the command line inputs in the form of String[]
c)JVM will pass the generated String[] as parameter to main() method at the time of calling main()
method.
Due to the above JVM actions,the main method is required parameters inorder to store all the
command line inputs in the form String[] array.
168
Page

Q)What is the requirement to provide only String data type as parameter to the main() method?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
In general,from application to application or from developer to developer the types of command line
input may be varied,here even developers are providing different types of command line input,still, our
main() method must store all the command line input. In Java, only String data types is able to
represent any type of data so that String data types is required as parameter to main() method.

To allow different types of command line input, main() method must require String dataType.

Q)What is the requirement to provide an array as parameter to main() method?


Ans:
In general,from application to application and from developer to developer no.of command line inputs
may be varied,here even developers are providing variable no.of command line inputs our main()
method parameter must store them.In Java,to store more than one value we have to take array.Due to
this reason,main() method must require array type as parameter. main() method will take array type as
parameter is to allow multiple no.of command line input.

EX:
class Test{
public static void main(String args[]){
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
}
}
OP:
D:\java7>javac Test.java
D:\java7>java Test 10 "abc" 22.22f 34.345 'A' true
10
"abc"
22.22f
34.345
'A'
true

169
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test
{
public static void main(String[] args) throws Exception
{
String val1=args[0];
String val2=args[1];
int fval=Integer.parseInt(val1);
int sval=Integer.parseInt(val2);
System.out.println("ADD :"+(fval+sval));
System.out.println("SUB :"+(fval-sval));
System.out.println("MUL :"+(fval*sval));
}
}
OP:
D:\javaapps>javac Test.java
D:\javaapps>java Test 10 5
ADD :15
SUB :5
MUL :50

NOTE: If we declare main() method without String[] parameter then compiler will not rise any error
but JVM will provide the following.
JAVA6:java.lang.NoSuchMethodError:main
JAVA7:Error:Main Method not found in class Test,please define main method as:
public static void main(String args[])

Q)Find the valid syntaxes of main() method from the following list?
1.public static void main(String[] args)--> Valid
2.public static void main(String[] abc)---> valid
3.public static void main(String args)----> Invalid
4.public static void main(String[][] args)-->Invalid
5.public static void main(String args[])---> Valid
6.public static void main(String []args)---> Valid
7.public static void main(string[] args)---> Invalid
8.public static void Main(String[] args)---> Invalid
9.public static int main(String[] args)----> Invalid
10.public final void main(String[] args)---> Invalid
11.public void main(String[] args)---------> Invalid
12.static void main(String[] args)---------> Invalid
13.static public void main(String[] args)--> Valid
170

14.public static void main(String ... args)-> Valid


Page

Q)Is it possible to provide more than one main() method with in a single java application?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
Yes,it is possible to provide more than one main() method with in a single java application,but,we
have to provide more than one main() method in different classes,not in a single class.

EX: File Name : D:\java7\abc.java

class A{
public static void main(String args[]){
System.out.println("main()-A");
}
}
class B{
public static void main(String args[]){
System.out.println("main()-B");
}
}
OP:
D:\java7>javac abc.java
D:\java7>java A
main()-A
D:\java7>java B
main()-B

NOTE:If we compile the above abc.java file then compiler will generate two .class
files[A.class,B.class].To execute the above program,we have to give a class name along with "java"
command,here which class name we are providing along with "java" command that class main()
method will be executed by JVM.

NOTE:In the above program,it is possible to access one main() method from another main() method
by passing String[] as parameter and by using the respective class name as main() method is static
method.

171
Page

EX: FIle name : D:\java7\abc.java

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A{
public static void main(String args[]){
System.out.println("main()-A");
String[] str={"AAA","BBB","CCC"};
B.main(str);
B.main(args);
}
}
class B{
public static void main(String args[]){
System.out.println("main()-B");
}
}
OP:
D:\java7>javac abc.java
D:\java7>java A
main()-A
main()-B
main()-B

Q)Is it possible to overload main() method?

Ans:
Yes, In Java,it is possible to overload main() method but it is not possible to override main()
method,because,in Java applications static method overloading is possible but static method overriding
is not possible.

EX: class Test


{
public static void main(String[] args)
{
System.out.println("String[]-param-main()");
}
public static void main(int[] args)
{
System.out.println("int[]-param-main()");
}
public static void main(float[] args)
{
System.out.println("float[]-param-main()");
172

}
}
Page

OP:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String[]-param-main

****************** Completed Upto This *****************

Relationships in JAVA:
As part of Java application development,we have to use entities as per the application requirements.

In Java application development,if we want to provide optimizations over memory utilization,code


Reusability, Execution Time, Sharability then we have to define relationships between entities.

There are three types of relationships between entities.

1.Has-A relationship
2.IS-A relationship
3.USE-A relationship

Q)What is the difference between HAS-A Relationship and IS-A relationship?

Ans:
Has-A relationship will define associations between entities in Java applications,here associations
between entities will improve communication between entities and data navigation between entities.

IS-A Relationship is able to define inheritance between entity classes, it will improve "Code
Reusability" in java applications.

Associations in JAVA:
There are four types of associations between entities

1.One-To-One Association
2.One-To-Many Association
3.Many-To-One Association
4.Many-To-Many Association

To achieve associations between entities,we have to declare either single reference or array of
reference variables of an entity class in another entity class.
173
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Address{
----
}
class Student{
----
Address[] addr;-->It will establish One-To-Many Association
}

1.One-To-One Association:
It is a relation between entities, where one instance of an entity should be mapped with exactly one
instance of another entity.

EX: Every employee should have exactly one Account.


EX:
class Account{
String accNo;
String accName;
String accType;
Account(String accNo,String accName,String accType){
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}
}
class Employee{
String eid;
String ename;
String eaddr;
Account acc;
Employee(String eid,String ename,String eaddr,Account acc){
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
this.acc=acc;
}
public void getEmployee(){
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id :"+eid);
System.out.println("Employee Name :"+ename);
174

System.out.println("Employee Address :"+eaddr);


System.out.println();
Page

System.out.println("Account Details");
System.out.println("----------------");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("Account Number :"+acc.accNo);
System.out.println("Account Name :"+acc.accName);
System.out.println("Account Type :"+acc.accType);
}}
class OneToOneEx{
public static void main(String args[]){
Account acc=new Account("abc123","Durga N","Savings");
Employee emp=new Employee("E-111","Durga","Hyd",acc);
emp.getEmployee();
}
}
OP:
Employee Details
------------------------
Employee Id :E-111
Employee Name:Durga
Employee Address:Hyd

Account Details
----------------------
Account Number :abc123
Account Name :Durga N
Account Type :Savings

Data Flow Diagram on One-To-One:

2.One-To-Many Association:
It is a relationship between entity classes, where one instance of an entity should be mapped with
multiple instances of another entity.

EX:Single department has multiple employees.

175
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Employee{
String eid;
String ename;
String eaddr;
Employee(String eid,String ename,String eaddr){
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
}
}
class Department{
String did;
String dname;
Employee[] emps;
Department(String did,String dname,Employee[] emps){
this.did=did;
this.dname=dname;
this.emps=emps;
}
public void getDepartmentDetails(){
System.out.println("Department Details");
System.out.println("--------------------");
System.out.println("Department Id :"+did);
System.out.println("Department Name:"+dname);
System.out.println();
System.out.println("EID ENAME EADDR");
System.out.println("----------------");
for(int i=0;i<emps.length;i++){
Employee e=emps[i];
System.out.println(e.eid+" "+e.ename+" "+e.eaddr);
}
}
}
class OneToManyEx{
public static void main(String args[]){
Employee e1=new Employee("E-111","AAA","Hyd");
Employee e2=new Employee("E-222","BBB","Hyd");
Employee e3=new Employee("E-333","CCC","Hyd");
Employee[] emps=new Employee[3];
emps[0]=e1;
176

emps[1]=e2;
emps[2]=e3;
Page

Department dept=new Department("D-111","Admin",emps);


dept.getDepartmentDetails();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}

OP:
Department Details
-----------------------------
Department Id :D-111
Department Name:Admin
EID ENAME EADDR
----------------------------------
E-111 AAA Hyd
E-222 BBB Hyd
E-333 CCC Hyd

Many-To-One Association:
It is a relationship between entities,where multiple instances of an entity should be mapped with
exactly one instance of another entity.

EX:Multiple Student have joined with a single branch.

EX:
class Branch{
String bid;
String bname;
Branch(String bid,String bname){
this.bid=bid;
this.bname=bname;
}
}
class Student{
String sid;
String sname;
String saddr;
Branch branch;
Student(String sid,String sname,String saddr,Branch branch){
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
this.branch=branch;
}
177

public void getStudentDetails(){


System.out.println("Student Details");
Page

System.out.println("----------------");
System.out.println("Student Id :"+sid);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("Student name :"+sname);
System.out.println("Student Address:"+saddr);
System.out.println("Branch Id :"+branch.bid);
System.out.println("Branch Name :"+branch.bname);
System.out.println();
}
}
class ManyToOneEx{
public static void main(String args[]){
Branch branch=new Branch("B-111","CS");
Student std1=new Student("S-111","AAA","Hyd",branch);
Student std2=new Student("S-222","BBB","Hyd",branch);
Student std3=new Student("S-333","CCC","Hyd",branch);
std1.getStudentDetails();
std2.getStudentDetails();
std3.getStudentDetails();
}
}
OP:
Student Details
----------------------
Student Id :S-111
Student name:AAA
Student Address:Hyd
Branch Id :B-111
Branch Name:CS
Student Details
------------------------
Student Id :S-222
Student name:BBB
Student Address:Hyd
Branch Id :B-111
Branch Name:CS
Student Details
-----------------------
Student Id :S-333
Student name:CCC
Student Address:Hyd
Branch Id :B-111
Branch Name:CS
178
Page

4.Many-To-Many Associations:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


It is a relationship between entities,Where multiple instances of an entity should be mapped with
multiple instances of another entity.
EX:Multiple Students Have Joined with Multiple Courses.

EX: class Course{


String cid;
String cname;
int ccost;
Course(String cid,String cname,int ccost){
this.cid=cid;
this.cname=cname;
this.ccost=ccost;
}
}
class Student{
String sid;
String sname;
String saddr;
Course[] crs;
Student(String sid,String sname,String saddr,Course[] crs){
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
this.crs=crs;
}
public void getStudentDetails(){
System.out.println("Student Details");
System.out.println("----------------");
System.out.println("Student Id :"+sid);
System.out.println("Student name :"+sname);
System.out.println("Student Address:"+saddr);
System.out.println("CID CNAME CCOST");
System.out.println("----------------------");
for(int i=0;i<crs.length;i++){
Course c=crs[i];
System.out.println(c.cid+" "+c.cname+" "+c.ccost);
}
System.out.println();
}}
class ManyToManyEx{
179

public static void main(String[] args){


Course c1=new Course("C-111","C",500);
Page

Course c2=new Course("C-222","C++",1000);


Course c3=new Course("C-333","JAVA",5000);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Course[] crs=new Course[3];
crs[0]=c1;
crs[1]=c2;
crs[2]=c3;
Student std1=new Student("S-111","AAA","Hyd",crs);
Student std2=new Student("S-222","BBB","Hyd",crs);
Student std3=new Student("S-333","CCC","Hyd",crs);
std1.getStudentDetails();
std2.getStudentDetails();
std3.getStudentDetails();
}}
OP:
Student Details
----------------------
Student Id :S-111
Student name :AAA
Student Address:Hyd
CID CNAME CCOST
------------------------------------
C-111 C 500
C-222 C++ 1000
C-333 JAVA 5000
Student Details
------------------------
Student Id :S-222
Student name:BBB
Student Address:Hyd
CID CNAME CCOST
------------------------------------
C-111 C 500
C-222 C++ 1000
C-333 JAVA 5000
Student Details
-----------------------
Student Id :S-333
Student name:CCC
Student Address:Hyd
CID CNAME CCOST
-----------------------------------
C-111 C 500
180

C-222 C++ 1000


C-333 JAVA 5000
Page

In java applications, Associations are existed in the following two forms.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Aggregation
2.Composition

Q)What is the difference between Aggregation and Composition?

Ans:
1.Where Aggregation is representing weak association that is less dependency but composition is
representing strong association that is more dependency.

2.In case of Aggregation, if contained object is existed even without container object.

In case of Composition ,if contained object is not existed without container object.

3.In the case of Aggregation,the life of the contained Object is independent of the container Object
life.

In the case of composition,the life of contained objects is depending on the container object life that is
same as container object life.

EX:
If we take an association between "Library" and "Students","Library" and "Books". "Students" can
exist without "Library",so that,the association between "Library" and "Student" is
Aggregation."Books" can not exist without "Library",so that,the association between "Library" and
"Books" is composition

IS-A Relationship:
It is a relationship between entity classes,it will provide inheritance between entity classes,where
inheritance relationship will improve "code reusability" in Java application.

The process of getting variables and methods from one class to another class is called as
Inheritance.

At the basic level of Object Orientation,There are two types of inheritances.

1.Single Inheritance
2.Multiple Inheritance
181
Page

1.Single Inheritance:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


The process of getting variables and methods from only one super class to one or more no.of
subclasses is called as Single Inheritance.

Java is able to allow Single Inheritance.

2.Multiple Inheritance:
The process of getting variables and methods from more than one super class to one or more no.of
sub classes is called as Multiple Inheritance.

Java is not allowing Multiple Inheritance.

On the basis of Single and Multiple inheritances ,there are 3 more Inheritances.
1. Multi-Level Inheritance
2. Hierarchical Inheritance
3. Hybrid Inheritance

1. Multi-Level Inheritance :
It is a Combination of single inheritance in more than one level. Java is able to allow multi-level
inheritance.

EX:
class A{
}
class B extends A{
}
class C extends B{
}

2. Hierarchical Inheritance :
It is the combination of single inheritance in a particular structure.Java is able to allow Hierarchical
inheritance.

182
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A{
}
class B extends A{
}
class C extends A{
}
class D extends B{
}
class E extends B{
}
class F extends C{
}
class G extends C{
}

3.Hybrid Inheritance:
It is the combination of single inheritance and multiple inheritances.

Java is not allowing Hybrid Inheritance.

EX:
class A{
}
class B extends A{
}
class C extends A{
}
class D extends B,C{
}

EX:
class Employee {
String eid;
String ename;
String eaddr;
public void getEmpDetails() {
System.out.println("Employee Id :"+eid);
System.out.println("Employee name :"+ename);
System.out.println("Employee Address :"+eaddr);
}
183

}
class Manager extends Employee {
Page

Manager(String eid1,String ename1,String eaddr1) {


eid=eid1;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


ename=ename1;
ename=eaddr1;
}
public void getManagerDetails() {
System.out.println("manager Details");
System.out.println("-----------------");
getEmpDetails();
}
}
class Accountant extends Employee {
Accountant (String eid1,String ename1,String eaddr1) {
eid=eid1;
ename=ename1;
eaddr=eaddr1;
}
public void getAccountantDetails() {
System.out.println("Accountant Details");
System.out.println("--------------------"); getEmpDetails(): } } class InheritanceEx { public static
void main(String[] args){
Manager m=new Manager("E-111","AAA","Hyd");
m.get ManagerDetails();
System.out.println();
Accountant acc=new Accountant("E-222","BBB","Hyd"); acc.getAccountantDetails();
}
}
On Command Prompt:
==================
D:\java7>javac InheritanceEx.java
D:\java7>java Inheritance Ex
Manager Details:
================
Employee Id :E-111
Employee Name :AAA
Employee Address :Hyd
Accountant Details:
===================
Employee Id :E-222
Employee Name :BBB
Employee Address :Hyd
184
Page

Static Context in Inheritance:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the case of inheritance, if we create an object for sub class then JVM has to execute sub class
constructor, before executing sub class constructor, JVM has to check whether sub class bytecode is
loaded already in the memory or not, if not, JVM has to load subclass bytecode to the memory.

In the above context,before loading sub class bytecode to the memory, first, JVM has to load the
respective super class bytecode to the memory.

Therefore,in the case of inheritance,JVM will load all the classes bytecode right from super class to
sub class order.

If we provide static context in both super class and subclass then JVM will recognize and execute
static context of the respective classes at the time of loading the respective classes, that is from
super class to sub class ordering.

EX:
class A{
static{
System.out.println("SB-A");
}
}
class B extends A{
static{
System.out.println("B-con");
}
}
class C extends B{
static{
System.out.println("SB-C");
}
}
class Test{
public static void main(String[] args){
C c=new C();
}
}
OP:
SB-A
B-con
SB-C
185
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A{
static{
System.out.println("SB-A");
}
static int m1(){
System.out.println("m1-A");
return 10;
}
static int i=m1();
}
class B extends A{
static int j=m2();
static{
System.out.println("SB-B");
}
static int m2(){
System.out.println("m2-B");
return 20;
}}
class C extends B{
static int m3(){
System.out.println("m3-C");
return 30;
}
static int k=m3();
static{
System.out.println("SB-C");
}}
class Test{
public static void main(String[] args){
C c1=new C();
C c2=new C();
}}

OP: SB-A
m1-A
m2-B
SB-B
m3-C
SB-C
186
Page

Instance Context in Inheritance:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the case of Inheritance,if we create object for sub class then JVM has to execute sub class
constructor,but before executing sub class constructor JVM has to execute 0-argument constructor
in the respective super class. If we provided instance context in both super class and sub class then
JVM will execute the provided instance context just before executing the respective class
constructor.

EX:
class A{
A(){
System.out.println("A-con");
}
}
class B extends A{
B(){
System.out.println("B-con");
}
}
class C extends B{
C(){
System.out.println("C-con");
}
}
class Test{
public static void main(String[] args){
C c=new C();
}
}

OP: A-Con
B-Con
C-Con

187
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class A{
A(){
System.out.println("A-con");
}
}
class B extends A{
}
class C extends B{
C(){
System.out.println("C-con");
}
}
class Test{
public static void main(String[] args){
C c=new C();
}
}
OP:
A-Con
C-Con

EX:
class A{
A(int i){
System.out.println("A-int-param-con");
}
}
class B extends A{
B(int i){
System.out.println("B-int-param-con");
}
}
class C extends B{
C(int i){
System.out.println("C-int-param-con");
}
}
class Test{
public static void main(String[] args){
C c=new C(10);
188

}
}
Page

Status: Compilation Error

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Reason:In case of Inheritance,super classes must have 0-argument constructors irrespective of the sub
class constructors.

In the case of Inheritance,if we provide instance context at all the classes then JVM will recognize and
execute them just before executing the respective class constructors.

EX: class A{
A(){
System.out.println("A-con");
}
int i=m1();
int m1(){
System.out.println("m1-A");
return 10;
}
{
System.out.println("IB-A");
}
}
class B extends A{
int j=m2();
int m2(){
System.out.println("m2-B");
return 20;
}
{
System.out.println("IB-B");
}
B(){
System.out.println("B-Con");
}}
class C extends B{
C(){
System.out.println("C-con");
}
{
System.out.println("IB-C");
}
int k=m3();
int m3(){
189

System.out.println("m3-C");
return 30;
Page

}
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test{
public static void main(String args[]){
C c=new C();
}
}

OP:
m1-A
IB-A
A-con
m2-B
IB-B
B-Con
IB-C
m3-C
c-con
EX:
class A{
A(){
System.out.println("A-con");
}
static{
System.out.println("SB-A");
}
int m1(){
System.out.println("m1-A");
return 10;
}
static int m2(){
System.out.println("m2-A");
return 20;
}
{
System.out.println("IB-A");
}
static int i=m2();
int j=m1();
}
class B extends A{
{
190

System.out.println("IB-B");
}
Page

int m3(){
System.out.println("m3-B");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


return 30;
}
static{
System.out.println("SB-B");
}
int k=m3();
B(){
System.out.println("B-Con");
}
static int l=m4();
static int m4(){
System.out.println("m4-B");
return 40;
}
}
class C extends B{
static int m5(){
System.out.println("m5-C");
return 50;
}
int m6(){
System.out.println("m6-C");
return 60;
}
C(){
System.out.println("C-con");
}
int m6();
static int n=m5();{
System.out.println("IB-C");
}
static{
System.out.println("SB-C");
}
}
class Test{
public static void main(String args[]){
C c1=new C();
C c2=new C();
}
191

}
Page

Super Keyword:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Super is a Java keyword,it can be used to represent super class object from sub classes.

There are three ways to utilize "super" keyword.


1.To refer super class variables
2.To refer super class constructors
3.To refer super class methods.

1.To refer super class variables:


If we want to refer super class variables by using 'super' keyword then we have to use the following
syntax.
super.var_Name;

NOTE:We will utilize super keyword,to access super class variables when we have same set of
variables at local,at current class and at the super class.

EX:
class A{
int i=100;
int j=200;
}
class B extends A{
int i=10;
int j=20;
B(int i,int j){
System.out.println(i+" "+j);
System.out.println(this.i+" "+this.j);
System.out.println(super.i+" "+super.i);
}
}
class Test{
public static void main(String args[]){
B b=new B(50,60);
}
}
OP:
50 60
10 20
100 100
192
Page

2.To refer super class constructors:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we want to refer super class constructor from sub class by using 'super' keyword then we have to
use the following syntax.

super([Param_List]);

NOTE:In general,in inheritance,JVM will execute 0-argument constructor before executing sub class
constructor.In this context,instead of executing 0-argument constructor we want to execute a
parametrized constructor at super class,for this,we have to use 'super' keyword.

EX:
class A{
A(){
System.out.println("A-Con");
}
A(int i){
System.out.println("A-int-param-Con");
}
}
class B extends A{
B(){
super(10);
System.out.println("B-Con");
}
}
class Test{
public static void main(String args[]){
B b=new B();
}
}
OP:
A-int-param-Con
B-Con

If we want to access super class constructor from subclass by using "super" keyword then the
respective "super" statement must be provided as first statement.
If we want to access super class constructor from sub class by using "super" keyword then the
respective "super" statement must be provided in the subclass constructors only,not in subclass normal
Java methods.

If we voilate any of the above conditions then compiler will rise an error like "call to super must be
193

first statement in constructor".


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:Due to the above rules and regulations,it is not possible to access more than one super class
constructor from a single sub class constructor by using "super" keyword.

In the case of inheritance, when we access sub class constructor then ,first, JVM will execute super
class 0-arg constructor then JVM will execute sub class constructor, this flow of execution is possible
in Java because of the following compiler actions over source code at the time of compilation.
a)Compiler will goto each and every class available in the source file and checks whether any
requirement to provide "default constructors".
b)If any class is identified with out user defined constructor explicitly then compiler will add a 0-
argument constructor as default constructor.
c)After providing default constructors,compiler will goto all the constructors at each and every class
and compiler will check "super" statement is provided or not by the developer explicitly to access
super class constructor.
d)If any class constructor is identified with out "super" statement explicitly then compiler will append
"super()" statement in the respective constructor to access a 0- argument constructor in the respective
super class.
e)With the above compiler actions,JVM will execute super class 0-arg constructor as part of executing
sub class constructor explicitly.
Write the translated code:

class A{
A(){
System.out.println("A-con");
}
}
class B extends A{
B(int i){
System.out.println("B-int-param-con");
}
}
class C extends B{
C(int i){
System.out.println("C-int-param-con");
}
}
class Test{
public static void main(String args[]){
C c=new C();
}
}
194

Status:Compilation Error
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
A(){
System.out.println("A-con");
}
}
class B extends A{
B(int i){
System.out.println("B-int-param-con");
}
}
class C extends B{
C(int i){
super(10);
System.out.println("C-int-param-con");
}
}
class Test{
public static void main(String args[]){
C c=new C(10);
}
}

OP:
A-con
B-int-param-con
C-int-param-con

3.To refer super class method:


If we want to refer super class methods from sub class by using "super" keyword then we have to
use the following syntax.
super.method_Name([Param_List]);

NOTE:In Java applications,when we have same method at both subclass and at super class,if we
access that method at sub class then JVM will execute sub class method only,not super class method
because JVM will give more priority for the local class methods.In this context,if we want to refer
super class method over sub class method then we have to "super" keyword.
195
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m2(){
System.out.println("m2-B");
m1();
this.m1();
super.m1();
}
}
void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String args[]){
B b=new B();
b.m2();
}
}

Class Level Type Casting:


The process of converting the data from one user defined data type to another user defined data type is
called as User Defined Data type casting or Class level type Casting. If we want to perform Class
Level Type Casting or User Defined data types casting then we must require either "extends" or
"implements" relationship between two user defined data types.

There are two types of User defined data type casting:


1.UpCasting.
2.DownCasting.

1.UpCasting:
The process of converting the data from sub type to super type is called as UpCasting.
To perform Upcasting,we have to assign sub class reference variable to super class reference variable.
196
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
}
class B extends A{
}
B b=new B();
A a=b;

If we compile the above code then compiler will check whether 'b' variable data type is compatible
with 'a' variable data type or not,if not,compiler will rise an error like "InCompatible Types".If "b"
variable data type id compatible to "a" variable data type then compiler will not rise any error.

NOTE:In Java applications,always sub class types are compatible with super class types,so that we
can assign sub class reference variable to super class reference variables directly.

NOTE:In Java,super class types are not compatible with sub class types,so that,we cannot assign super
class reference variables to sub class reference variables directly,where if we want to assign super class
reference variables to sub class reference variables then we must require "cast operator" explicitly,that
is called as "Explicit Type Casting".

If we execute the above code then JVM will perform the following two actions.
1.JVM will convert "b" variable data type[sub class type] to "a" variable data type[Super class type]
implicitly.
2.JVM will copy the reference value of "b" variable to "a" variable.
With the upcasting,we are able to access only super class members among the availability of both
super class and sub class members in sub class object.

class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m2(){
System.out.println("m2-B");
}
}
class Test{
public static void main(String[] args){
B b=new B();
197

b.m1();
b.m2();
Page

A a=b;
a.m1();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


//a.m2();---->error
}
}
OP:
m1-A
m2-B
m1-A

2.DownCasting:
The process of converting the data from super type to sub type is called as "DownCasting".

If we want to perform DownCasting then we have to use the following format.

EX:
class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m2(){
System.out.println("m2-B");
}
}
class Test{
public static void main(String args[]){
case 1:
A a=new A();
B b=a;

Status:Compilation error,incompatible types

Reason:In Java,always,subclass types are compatible with super class types but super class types are
not compatible with sub class types.It is possible to assign sub class reference variables directly but it
is not possible to assign super class reference variable to sub class reference variables directly,if we
assign then compiler will rise an error like "InCompatible Types error".
198
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Case 2:
A a=new A();
B b=(B)a;
Status:No Compilation error,but classCastException
Reason:In Java,always,it is possible to keep subclass object reference value in super class
reference variable but it is not possible to keep superclass object reference value in subclass
reference variable.If we are trying to keep super class object reference value in sub class
reference variable then JVM will rise an exception like "java.lang.classCastException".

Case 3:
A a=new B();
B b=(B)a;
Status:No compilation error,no exception
b.m1();
b.m2();
}
}

EX:
class A{
}
class B extends A{
}
class C extends B{
}
class D extends C{
}

Ex1:
A a=new A();
B b=a;
Status:Compilation error,incompatible types
Ex2:
A a=new A();
B b=(B)a;
Status:No Compilation error,ClassCastException
Ex3:
A a=new A();
B b=(B)a;
Status:No Compilation error,No Exception
199

Ex4:
A a=new C();
Page

B b=(C)a;
Status:No Compilation error,No Exception

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ex5:
A a=new B();
B b=(C)a;
Status:No Compilation Error;ClassCastException
Ex6:
A a=new C();
C c=(D)a;
Status:No Compilation Error,ClassCastException
Ex7:
B b=new D();
C c=(D)b;
Status:NO Compilation Error,No Exception
Ex8:
A a=new D();
D d=(D)(C)(B)a;
Status:No Compilation error,No Exception
Ex9:
A a=new C();
D d=(D)(C)(B)a;
Status:No Compilation Error,ClassCastException
Ex10:
A a=new C();
C c=(D)(C)(B)a;
Status:No Compilation Error,ClassCastException

USES-A RelationShip:
This is a relationship between entities,where one entity will use another entity upto a particular
action or behaviour or method.

To provide USES-A Relationship in java applications,we have to provide contained Entity class
reference variable as parameter to a method in Container entity class,not as class level variable.

If we declared contained entity reference variable as class level reference variable in container
entity class then that relationship is "HAS-A" relationship.
200
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Account{
String accno;
String accName;
String accType;
int bal=10000;
Account(String accNo,String accName,String accType){
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}
}
class Transaction{
String tx_tid;
String tx_Type;
Transaction(String tx_id,String tx_Type){
this.tx_Id=tx_Id;
this.tx_Type=tx_Type;
}
public void deposit(Account acc,int dep_Amt){
int initial_Amt=acc.bal;
int total_Avl_Amt=initial_Amt+dep_Amt;
acc.bal=total_Avl_Amt;
System.out.println("Transaction Details");
System.out.println("--------------------");
System.out.println("Transaction Id :"+tx_Id);
System.out.println("Account Number :"+acc.accNo);
System.out.println("Account Type :"+acc.accType);
System.out.println("Initial Amount :"+initial_Amt);
System.out.println("Deposit Amount :"+dep_Amt);
System.out.println("Total Avl Amount :"+total_Avl_Amt);
System.out.println("Transaction Status:SUCCESS");
System.out.println("********THANKQ,VISIT AGAIN***********");
}
}
class UsesAEx{
public static void main(String[] args){
Account acc=new Account("abc123","Durga","Savings");
Transaction tx=new Transaction("T-111","Deposit");
tx.deposit(acc,5000);
201

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
Transaction Details

Transaction Id :T-111
Account Number :abc123
Account Type :Savings
Initial Amount :10000
Deposit Amount :5000
Total Avl Amount :15000
Transaction Status:SUCCESS

********THANKQ,VISIT AGAIN**********

Polymorphism:
Polymorphism is a Greek word,where poly means many and morphism means Structures.

If one thing is existed in more than one form then it is called as Polymorphism.

The main advantage of Polymorphism is "Flexibility" to design Applicatins.

There are two types of Polymorphisms

1.Static Polymorphism or Early binding


2.Dynamic Polymorphism or Late Binding

1.Static Polymorphism:
If the Polymorphism is existed at compilation time then that Polymorphism is called as Static
Polymorphism.

EX:Method Overloading

2. Dynamic Polymorphism:
If the Polymorphism is existed at runtime then that Polymorphism is called as Dynamic
Polymorphism.

EX:Method Overriding.
202
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Method Overloading:
The process of extending the existed method functionality upto some new Functionality is called as
Method Overloading.
If we declare more than one method with the same name and with the different parameter list is called
as Method Overloading.
To perform method overloading, we have to declare more than one method with different method
signatures that is same method name and different parameter list.

EX:
class A{
void add(int i,int j){
System.out.println(i+j);
}
void add(float f1,float f2){
System.out.println(f1+f2);
}
void add(String str1,String str2){
System.out.println(str1+str2);
}
}
class Test{
public static void main(String[] args){
A a=new A();
a.add(10,20);
a.add(22.22f,33.33f);
a.add(“abc”,”def”);
}
}
OP:
30
55.550003
abcdef

203
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Employee{
void gen_Salary(int basic,float hk,float pf,int ta){
float salary=basic+((basic*hk)/100)-((basic*pf)/100)+ta);
System.out.println("Salary :"+salary);
}
void gen_Salary(int basic,float hk,float pf,int ta,int bonus){
float salary=basic+((basic*hk)/100)-((basic*pf)/100)+ta)+bonus;
System.out.println("Salary :"+salary);
}
}
class Test{
public static void main(String[] args){
Employee e=new Employee();
e.gen_Salary(20000,25.of,12.0f,2000);
e.gen_Salary(20000,25.of,12.0f,2000,5000);
}
}

Method Overriding:
The process of replacing existed method functionality with some new functionality is called as
Method Overriding.

To perform Method Overriding, we must have inheritance relationship classes.

In Java applications, we will override super class method with sub class method.

In Java applications,we will override super class method with subclass method.

If we want to override super class method with sub class method then both super class method and
sub class method must have same method prototype.

Steps to perform Method Overriding:

1.Declare a super class with a method whih we want to override.


2.Declare a sub class and provide the same super class method with different implementation.
3.In main class,in main() method,prepare object for sub class and prepare reference variable for
super class[UpCasting].
4.Access super class method then we will get output from sub class method.
204
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Loan{
public float getIR(){
return 7.0f;
}
}
class GoldLoan extends Loan{
public float getIR(){
return 10.5f;
}
}
class StudyLoan extends Loan{
public float getIR(){
return 12.0f;
}}
class CraftLoan extends Loan{
}
class Test{
public static void main(String[] args){
Loan gold_Loan=new GoldLoan();
System.out.println("Gold Loan IR :"+gold_Loan.getIR()+"%");
Loan study_Loan=new StudyLoan();
System.out.println("Study Loan IR :"+study_Loan.getIR()+"%");
Loan craft_Loan=new CraftLoan();
System.out.println("Craft Loan IR :"+craft_Loan.getIR()+"%");
}
}

NOTE: To prove method overriding in Java, we have to access super class method but JVM will
execute the respective sub class method and JVM has to provide output from the respective sub class
method, not form super class method. To achieve the above requirement we must create reference
variable for only super class and we must create object for sub class.

class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m1(){
205

System.out.println("m1-B");
}
Page

}
class Test{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String args[]){
/* A a=new A();
a.m1();
Status:Here Method Overriding is not happend,because Mehtod overriding must require sub
class
object,not super class object.
*/
/*
B b=new B();
b.m1();

Status:Here method Overriding is happened,but,to prove method overriding we must require super
class reference variable,not sub class reference variable,because,subclass reference variable is able to
access only sub class method when we have the same method in both sub class and super class.
*/
A a=new B();
a.m1();
}
}

Rules to perform Method Overriding:


1.To override super class method with sub class then super class method must not be declared as
private.

EX:
class A{
private void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m1(){
System.ou.println("m1-B");
}
}
class Test{
public static void main(String args[]){
A a=new A();
a.m1();
}
206

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.To override super class method with sub class method then sub class method should have the same
return type of the super class method.

EX:
class A{
int m1(){
System.ou.println("m1-A");
return 10;
}
}
class B extends A{
void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String args[]){
A a=new B();
a.m1();
}
}

3.To override super class method with sub class method then super class method must not be declared
as final sub class method may or may not be final.

EX:
class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
final void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String[] args){
A a=new B();
a.m1();
207

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.To override superclass method with sub class method either super class method or subclass method
as static then compiler will rise an error.If we declare both super and sub class method as static in
method overriding compiler will not rise any error,JVM will provide output from the super class
method.

NOTE:If we are trying to override superclass static method with sub class static method then super
class static method will override subclass static method,where JVM will generate output from super
class static method.

EX:
class A{
static void m1(){
System.out.println("m1-A");
}
}
class B extends A{
static void m1(){
System.out.println("m1-B");
}
}
class Test{
public static void main(String args[]){
A a=new B();
a.m1();
}
}

5.To override super class method with subclass method,sub class method must have either same scope
of the super class method or more scope when compared with super class method scope otherwise
compiler will rise an error.

EX:
class A{
protected void m1(){
System.out.println("m1-A");
}
}
class B extends A{
public void m1(){
System.out.println("m1-B");
208

}
}
Page

class Test{
public static void main(String args[]){

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


A a=new A();
a.m1();
}
}

6.To override super class method with subclass method subclass method should have either same
access privileges or weaker access privileges when compared with super class method access
privileges.

Q)What are the differences between method overloading and method overriding?

Ans:
1. The process of extending the existed method functionality with new functionality is called as
Method Overloading.
The process of replacing existed method functionality with new functionality is called as Method
Overriding
2.In the case of method overloading, different method signatures must be provided to the methods
In the case of method overriding same method prototypes must be provided to the methods.

3.With or without inheritance we can perform method overloading


With inheritance only we can perform Method overriding

EX:
class DB_Driver{
public void getDriver(){
System.out.println("Type-1 Driver");
}
}
class New_DB_Driver extends DB_Driver{
public void getDriver(){
System.out.println("Type-4-Driver");
}
}
class Test{
public static void main(String args[]){
DB_Driver driver=new New_DB_Driver();
driver.getDriver();
}
}
209
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above example, method overriding is implemented, in method overriding, for super class
method call JVM has to execute subclass method, not super class method. In method overriding,
always JVM is executing only subclass method, not super class method. In method overriding, it is not
suggestible to manage super class method body without execution, so that, we have to remove super
class method body as part of code optimization. In Java applications, if we want to declare a method
without body then we must declare that method as "Abstract Method".

If we want to declare abstract methods then the respective class must be abstract class.

abstract class DB_Driver{


public abstract void getDriver();
}
class New_DB_Driver extends DB_Driver{
public void getDriver(){
System.out.println("Type-4 Driver");
}
}
class Test{
public static void main(String args[]){
DB_Driver driver=new New_DB_Driver();
driver.getDriver();
}
}

In Java applications, if we declare any abstract class with abstract methods, then it is convention to
implement all the abstract methods by taking sub class.
To access the abstract class members, we have to create object for subclass and we have to create
reference variable either for abstract class or for subclass.
If we create reference variable for abstract class then we are able to access only abstract class
members, we are unable to access subclass own members

If we declare reference variable for subclass then we are able to access both abstract class members
and subclass members.

abstract class A{
void m1(){
System.out.println("m1-A");
}
abstract void m2();
210

abstract void m3();


}
Page

class B extends A{
void m2(){

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("m2-B");
}
void m3(){
System.out.println("m3-B");
}
void m4(){
System.out.println("m4-B");
}
}
class Test{
public static void main(String args[]){
A a=new B();
a.m1();
a.m2();
a.m3();
//a.m4();---error
B b=new B();
b.m1();
b.m2();
b.m3();
b.m4();
}
}

In Java applications,it is not possible to create Object fro abstract classes but it possible to provide
constructors in abstract classes,because,to recognize abstract class instance variables in order to store
in the sub class objects.

EX: abstract class A{


A(){
System.out.println("A-Con");
}
}
class B extends A{
B(){
System.out.println("B-Con");
}
}
class Test{
public static void main(String[] args){
211

B b=new B();
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java applications, if we declare any abstract class with abstract methods then it is mandatory to
implement all the abstract methods in the respective subclass. If we implement only some of the
abstract methods in the respective subclass then compiler will rise an error, where to come out from
compilation error we have to declare the respective subclass as an abstract class and we have to
provide implementation for the remaining abstract methods by taking another subclass in multilevel
inheritance.

EX:
abstract class A{
abstract void m1();
abstract void m2();
abstract void m3();
}
abstract class B extends A{
void m1(){
System.out.println("m1-A");
}
}
class C extends B{
void m2(){
System.out.println("m2-C");
}
void m3(){
System.out.println("m3-C");
}
}
class Test{
public static void main(String[] args){
A a=new C();
a.m1();
a.m2();
a.m3();
}
}
212
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java applications, if we want to declare an abstract class then it is not at all mandatory condition to
have atleast one abstract method, it is possible to declare abstract class without having abstract
methods but if we want to declare a method as an abstract method then the respective class mustbe
abstract class.
abstract class A{
void m1(){
System.out.println("m1-A");
}
}
class B extends A{
void m2(){
System.out.println("m2-B");
}
}
class Test{
public static void main(String args[]){
A a=new B();
a.m1();
//a.m2();---------->Error
B b=new B();
b.m1();
b.m2();
}
}

In Java applications, it is possible to extends an abstract class to concrete class and from concrete class
to abstract class.
class A{
void m1(){
System.out.println("m1-A");
}
}
abstract class B extends A{
abstract void m2();
}
class C extends B{
void m2(){
System.out.println("m2-C");
}
void m3(){
213

System.out.println("m3-C");
}
Page

}
class Test{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String args[]){
A a=new C();
a.m1();
//a.m2();--- error
//a.m3();--- error
B b=new C();
b.m1();
b.m2();
//b.m3();--- error
C c=new C();
c.m1();
c.m2();
c.m3();
}
}

Note: In Java applications, it is not possible to extend a class to the same class, if we do the same then
compiler will rise an error like "cyclic inheritance involving".

class A extends A{
}
Status: Compilation Error: “cyclic inheritance involving".
class A extends B{
}
class B extends A{
}

Status: Compilation Error: “cyclic inheritance involving".

Interfaces:
Interface is a Java Feature, it will allow only abstract methods.

In Java applications, for interfaces, we are able to create only reference variables, we are unable to
create objects.

In the case of interfaces, by default, all the variables are "public static final".

In the case of interfaces, by default, all the methods are "public and abstract".

In Java applications, constructors are possible in classes and abstract classes but constructors are not
214

possible in interfaces.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Interfaces will provide more sharability in Java applications when compared with classes and abstract
classes.

In Java applications, if we declare any interface with abstract methods then it is convention to declare
an implementation class for the interface and it is convention to provide implementation for all the
abstract methods in implementation class.

interface I{
void m1();
void m2();
void m3();
}
class A implements I{
public void m1(){
System.out.println("m1-A");
}
public void m2(){
System.out.println("m2-A");
}
public void m3(){
System.out.println("m3-A");
}
}
public void m4(){
System.out.println("m4-A");
}
}
class Test{
public static void main(String args[]){
I i=new A();
i.m1();
i.m2();
i.m3();
//i.m4();------>error
A a=new A();
a.m1();
a.m2();
a.m3();
a.m4();
}
215

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java applications, if we declare an interface with abstract methods then it is mandatory to provide
implementation for all the abstract methods in the respective implementation class. In this context if
we provide implementation for some of the abstract methods at the respective implementation class
then compiler will rise an error, where to come out from the compilation error we have to declare the
respective implementation class as an abstract class and we have to provide implementation for the
remaining abstract methods by taking a sub class for the abstract class.

interface I{
void m1();
void m2();
void m3();
}
abstract class A implements I{
public void m1(){
System.out.println("m1-A");
}
}
class B extends A{
public void m2(){
System.out.println("m2-B");
}
public void m3(){
System.out.println("m3-B");
}
}
class Test{
public static void main(String args[]){
I i=new I();
i.m1();
i.m2();
i.m3();
A a=new B();
a.m1();
a.m2();
a.m3();
B b=new B();
b.m1();
b.m2();
b.m3();
}
216

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java applications, it is not possible to extend more than one class to a single class but it is possible
to extend more than one interface to a single interface.

EX:
interface I1{
void m1();
}
interface I2{
void m2();
}
interface I3 extends I1,I2{
void m3();
}
class A implements I3{
public void m1(){
System.out.println("m1-A");
}
public void m2(){
System.out.println("m2-A");
}
public void m3(){
System.out.println("m3-A");
}
}
class Test{
public static void main(String args[]){
I1 i1=new A();
i1.m1();
I2 i2=new A();
i2.m2();
I3 i3=new A();
i3.m1();
i3.m2();
i3.m3();
A a=new A();
a.m1();
a.m2();
a.m3();
}
}
217
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java applications, it is possible to implement more than one interface into a single implementation
class.
interface I1{
void m1();
}
interface I2{
void m2();
}
interface I3{
void m3();
}
class A implements I1,I2,I3{
public void m1(){
System.out.println("m1-A");
}
public void m2(){
System.out.println("m2-A");
}
public void m3(){
System.out.println("m3-A");
}
}
class Test{
public static void main(String args[]){
I1 i1=new A();
i1.m1();
I2 i2=new A();
i2.m2();
I3 i3=new A();
i3.m3();
A a=new A();
a.m1();
a.m2();
a.m3();
}
}
218
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)Fond Valid Syntaxes between classes,abstract classes and Interfaces from the following list of
syntaxes?
class extends class --->Valid
class extends class,class--->InValid
class extends abstract class--->Valid
class extends abstract class,class--->InValid
class extends abstract class,abstract class--->InValid
class extends interface--->InValid
class implements interface--->Valid
class implements interface,interface--->Valid
class implements interface extends class--->InValid
class implements interface extends abstract class--->InValid
class extends class implements interface--->Valid
class extends abstract class implements interface--->Valid
abstract class extends class--->Valid
abstract class extends abstract class--->Valid
abstract class extends class,class--->InValid
abstract class extends abstract class,abstract class--->InValid
abstract class extends class,abstract class--->InValid
abstract class extends interface--->InValid
abstract class implements interface--->Valid
abstract class implements interface,interface--->Valid
abstract class extends class implements interface--->Valid
abstract class extends abstract class implements interface--->Valid
abstract class implements interface extends class-->InValid
abstract class implements interface extends abstract class-->InValid
interface extends interface -->Valid
interface extends interface,interface -->Valid
interface extends class -->InValid
interface extends abstract class -->InValid
interface implements interface -->InValid

Marker Interfaces:
Marker Interface is an Interface, it will not include any abstract method and it will provide some
abilities to the objects at runtime of our Java application.

EX: java.io.Serializable , java.lang.Cloneable


219
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


java.io.Serializable:
The process of separating the data from an object is called as Serialization.
The process of reconstructing an Object on the basis of data is called as Deserialization.
Serialization & Deserialization
Where java.io.Serializable interface is a marker interface, it was not declared any method but it will
make eligible any object for Serialization and Deserialization.

java.lang.Cloneable:
The process of generating duplicate object is called as Object Cloning.
IN java applications, bydefault, all objects are not eligible for Object cloning, only the objects
which implements java.lang.Cloneble interface are eligible for Object cloniong.

JAVA8 Features over Interfaces:


1.Default Methods in Interfaces
2.Static Methods in Interfaces
3.Functional Interfaces

1.Default Methods in Interfaces:


In general, if we declare abstract methods in an interface then we have to implement all that
interface methods in more no.of classes with variable implementation part.
In the above context, if we require any method implementation common to every implementation
class with fixed implementation then we have to implement that method in the interface as default
method.
To declare default methods in interfaces we have to use "default" keyword in method syntax like
access modifier.

EX:
interface I{
default void m1(){
System.out.println("m1-A");
}
}

class A implements I{}


class Test{
public static void main(String args[]){
I i=new A();
i.m1();
}
}
220

NOTE:It is possible to provide more than one default methods with in a single interface.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
interface I{
default void m1(){
---------
}
default void m2(){
--------
}
}
1.In JAVA8,it is possible to override default methods in the implementation classes.
interface I{
default void m1(){
System.out.println("m1-A");
}
}
class A implements I{
public void m1(){
System.out.println("m1-A");
}
}
class Test{
public static void main(String args[]){
I i=new A();
i.m1();
}
}

2.Static Methods in Interfaces:

Upto JAVA7 version, static methods are not possible in interfaces but from JAVA8 version static
methods are possible in interfaces in order to improve sharability.

If we declare static methods in the interfaces then it is not required to declare any implementation class
to access that static method,we can use directly interface name to access static method.

NOTE:If we declare static methods in an interface then they will not be available to the respective
implementation classes,we have to access static methods by using only interface names not even by
using interface reference variable
221
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
interface I{
static void m1(){
System.out.println("m1-1");
}
}
class Test{
public static void main(String args[]){
I.m1();
}
}

Note:In JAVA8 version, interfaces will allow concrete methods along with either "static" keyword or
"default" keyword.

3.Functional Interface:
If any Java interface allows only one abstract method then it is called as "Functional Interface".
To make any interface as Functional Interface then we have to use the following annotation just
above of the interface.
@FunctionalInterface

EX: java.lang.Runnable
java.lang.Comparable

NOTE:In Functional Interfaces we have to provide only one abstract method but we can provide any
no.of default methods and any no.of static methods.

222
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


@Functional Interface
interface I{
void m1();
//void m2();---->error
default void m3(){
System.out.println("m3-I");
}
static void m4(){
System.out.println("m4-I");
}
class A implements I{
public void m1(){
System.out.println("m1-A");
}
}
class Test{
public static void main(String args[]){
I i=new A();
i.m1();
i.m3();
//i.m4();--->error
I.m4();
//A.m4();--->error
}}

Instanceof operator:
It is a boolean operator,it can be used to check whether the specified reference variable is
representing the specified class object or not that is compatible or not.

ref_Var instanceof Class_Name

where ref_Var and Class_Name must be related otherwise compiler will rise an error like
"incompatible types error".

If ref_Var class is same as the specified Class_Name then instanceof operator will return "true".

If ref_Var class is subclass to the specified Class_Name then instanceof operator will return "true".

If ref_Var class is super class to the specified Class_Name then instanceof operator will return
"false".
223
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
}
class B extends A{
}
class C{
}
class Test{
public static void main(String args[]){
A a new A();
B b=new B();
System.out.println(a instanceof A);
System.out.println(a instanceof B);
System.out.println(b instanceof A);
//System.out.println(a instanceof C);
}}

Object Cloning:
The process of creating duplicate object for an existed object is called as Object Cloning.

If we want to perform Object Cloning in Java application then we have to use the following steps.

1.Declare an User defined Class.


2.Implement java.lang.Cloneable interface inorder to make eligible any object for cloning.
3.Override Object class clone() method in user defined class.
public Object clone() throws CloneNotSupportedException
4.In Main class,in main() method,access clone() method over the respective object.

EX:
class Student implements Cloneable{
String sid;
String sname;
String saddr;
Student(String sid,String sname,String saddr){
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
224

}
public String toString(){
Page

System.out.println("Student details");
System.out.println("----------------");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("Student Id :"+sid);
System.out.println("Student name:"+sname);
System.out.println("Student Address:"+saddr);
return "";
}}
class Test{
public static void main(String args[]){
Student std1=new Student("S-111","Durga","Hyd");
System.out.println("Student Details Before Cloning");
System.out.println(std1);
Student std2=(Student)std1.clone();
System.out.println();
System.out.println("Student Details After cloning");
System.out.println(std2);
}
}

There are two types clonings in Java:


1.Shallow Cloning/Shallow Copy
2.Deep Cloning/Deep Copy

1.Shallow Cloning/Shallow Copy:


In this cloning mechanism,while cloning an object if any associated object is encountered then JVM
will not duplicate associated object along with data duplication,where duplicated object is also refer
the same associated object which was refereed by original object.

NOTE:Shallow Cloning is default cloning mechanism in Java.

2. Deep Cloning/Deep Copy:


In this cloning mechanism,while cloning an object if JVM encounter any associated object then JVM
will duplicate associated object also along with data duplication.In this cloning mechanism,both
original object and cloned object are having their own duplicated associated objects copy,both are not
referring a single associated object

225
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Account{
String accNo;
String accName;
String accType;
Account(String accNo,String accName,String accType){
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}
}
class Employee implements Cloneable{
String eid;
String ename;
String eddr;
Account acc;
Employee(String eid,String ename,String eaddr,Account acc){
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
this.acc=acc;
}
public Object clone() throws CloneNotSuppoertException{
return super.clone();
}
public String toString(){
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id :"+eid);
System.out.println("Employee Address :"+eaddr);
System.out.println("Employee Name :"+ename);
System.out.println("Account Deatails");
System.out.println("----------------");
System.out.println("Account Number:"+acc.accNo);
System.out.println("Account Name :"+acc.accName);
System.out.println("Account Type :"+acc.accType);
System.out.println("Account Reference: "+acc);
return "";
}}
class Test{
226

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


Account acc=new Account("abc123","Durga","Savings");
Page

Employee emp1=new Employee("E-111","Durga","Hyd",acc);


System.out.println("Employee Details Before Cloning");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println(emp1);
Employee emp2=(Employee)emp1.clone();
System.out.println("Employee Details After Cloning");
System.out.println(emp2);
}
}

To prepare example for deep cloning provide the following clone() method in employee class in the
above example of(shallow Cloning)
public Object clone()throws CloneNotSupportedException{
Account acc1=new Account(acc.accNo,acc.accName,acc.accType);
Employee emp=new Employee(eid,ename,eaddr,acc1);
return emp;

227
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Inner Classes
Declaring a class inside a class is called as Inner class.

Syntax:
class Outer_Class
{
class Inner_Class
{
}
}

In java applications, Inner classes are able to provide the following advantages.

1.Modularity
2.Adstraction
3.Security
4.Sharability
5.Reusability

1.Modularity:
In java appl, we are able to improv we modularity by using packages.
If we want to devide our implementation in a class in the form of modules then we have to use Inner
classes.

EX:
class Account
{
class SavingsAccount{
----
}
class CurrentAccount{
----
}
}

2.Adstraction:
If we declare any variable or method in an inner class thenthat variable and method are having
228

scope upto that inner class only , it is not available to other inner classes, so that, Inner classes are
able to improve Abstraction.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
class B{
int i=10;
}
class C{
void m1(){
i=i+10;--> Error
}
}
}

3.Security:
It is not possible to declare a class as private, but, it is possible to declare an inner class as private,
so that , inner classes are able to improve Security.

EX:
private class A{
}
Status: Invalid

EX:
class A{
private class B{
----
}
}

Status: Valid.

4.Sharability:
It is not possible to declare a class as Static, but, it is possible tio declare an inner class as static, so
that, inner classes are able to improve Sharability.

EX:
static class A{
}

Status: Invalid
229
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
static class B{
}
}

Status: Valid

5.Reusability:
In java, inheritance feature will imprive Code Reusability.
IN java applications, we can extend one inner class to another class, so that, inner classes are able to
improve Code Reusability.

EX:
class A{
class B{
---
}
class C extends B{
---
}
}
Status: Valid

There are four types of inner classes in java.


1.Member Inner class
2.Static Inner class
3.Method Local Inner class
4.Anonymous Inner class.

Note: If we compile java file contains inner classes then Compiler will generate a seperate .class for
outer class and a seperate .class file will be generated for inner class.

Outer_Class.class ---> for Outer class


Outer_Class$Inner_Class.class---> For Inner class
230
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Member Inner class:
Declaring a normal class[Non static class] inside a class is called as member inner class.

EX:
class Outer{
class Inner{
----
}
}

If we want to access the members of inner class then we have to create object for the inner class, for
this , we have to use the following syntax.

Outer.Inner ref_Var=new Outer().new Inner();

1.By using outer class reference variable we are able to access only outer class members, we are
unable to access inner class members.
2.By using Inner class reference variable we are ABle to access only inner class members we are
unable to access outer class members.
3.Bydefault , all outer class members are available to inner class, so we can access outer class
members inside the inner class, but, Inner class members are not available to outer classes, we are
unable to access inner class members in outer classes.
4.Member inner classes are not allowing static declarations directly, but, static keyword is allowed
along with final keyword.

EX:
class A
{
void m1()
{
System.out.println("m1-A");
}
class B
{
//static int i=10;--> Error
static final int j=20;
void m2()
{
System.out.println("m2-B");
231

System.out.println(j);
}
Page

void m3()
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("m3-B");
}
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();
//a.m2();--> Error
A.B ab=new A().new B();
ab.m2();
ab.m3();
//ab.m1();--> Error
}
}

In Member inner classes, we can extend one inner class to another inner class but both the inner
classes must be provided with in the same outer class.

EX:
class A
{
class B
{
void m1()
{
System.out.println("m1-B");
}
void m2()
{
System.out.println("m2-B");
}
}
class C extends B
{
void m3()
{
System.out.println("m3-C");
232

}
void m4()
Page

{
System.out.println("m4-C");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}
}
class Test
{
public static void main(String[] args)
{
A.B ab=new A().new C();
ab.m1();
ab.m2();
//ab.m3();--> Error
A.C ac=new A().new C();
ac.m1();
ac.m2();
ac.m3();
ac.m4();
}
}

We can not extend one inner class to another inner class which are available in two different outer
classes.

EX:
class A{
class B{
---
}
}
class C{
class D extends A.B{
---
}
}

Status: Invalid.

We can extend an inner class from an outer class.


233
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A{
---
}
class B{
class C extends A{
----
}
}
Status: Valid

We can extend the immediate outer class to its inner class.

EX:
class A{
class B extends A{
---
}
}

Q)Is it possible to write an interface inside a class?

Ans:
Yes, it is possible to provide an interface inside a class, but, the respective implementation class must
be provided with in the same outer class.

EX:
class A
{
interface I
{
void m1();
void m2();
void m3();
}
class B implements I
{
public void m1()
{
234

System.out.println("m1-B");
}
Page

public void m2()


{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("m2-B");
}
public void m3()
{
System.out.println("m3-B");
}
}
}
class Test
{
public static void main(String[] args)
{
A.I ai=new A().new B();
ai.m1();
ai.m2();
ai.m3();
}
}

EX:
class A
{
abstract class B
{
void m1()
{
System.out.println("m1-B");
}
abstract void m2();
abstract void m3();
}
class C extends B
{
void m2()
{
System.out.println("m2-C");
}
void m3()
{
235

System.out.println("m3-C");
}
Page

}
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Test
{
public static void main(String[] args)
{
A.B ab=new A().new C();
ab.m1();
ab.m2();
ab.m3();
}
}

Static Inner class:


Declaring a static class inside a class is called as Static inner class.

Syntax:
class Outer
{
static class Inner
{
----
}
}

If we want to access the members of static inner class we have to create object for static inner class, for
this we have to use the following syntax.

Outer.Inner ref_Var= new Outer.Inner();

1.Static inner classes are able to allow only static members of the outer class, it will not allow non
static members of the outer class.
2.IN general, inner classes are not allowing static keyword directly, but, static inner class is able to
allow static declarations directly.

EX:
class A
{
static class B
{
void m1()
{
236

System.out.println("m1-B");
}
Page

void m2()
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("m2-B");
}
static void m3()
{
System.out.println("m3-B");
}
}
}
class Test
{
public static void main(String[] args)
{
A.B ab=new A.B();
ab.m1();
ab.m2();
A.B.m3();
}
}

Q)Is it possible to write a class inside an interface?

Ans:
Yes, it is possible to write a class inside an interface, If we declare a class inside an interface then that
class is converted as a static inner class, we can access members of this inner class like static inner
class members.

EX:
interface I
{
class A// static class A
{
void m1()
{
System.out.println("m1-A");
}
void m2()
{
System.out.println("m2-A");
}
}
237

}
class Test
Page

{
public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
I.A ia=new I.A();
ia.m1();
ia.m2();
}
}

Note: We can write abstract class inside an interface,but, the respective sub class must be declared in
the same interface, here the declared sub class is converted as static inner class.
EX:
interface I
{
abstract class A
{
void m1()
{
System.out.println("m1-A");
}
abstract void m2();
abstract void m3();
}
class B extends A
{
void m2()
{
System.out.println("m2-B");
}
void m3()
{
System.out.println("m3-B");
}
}
}
class Test
{
public static void main(String[] args)
{
I.A ia=new I.B();
ia.m1();
ia.m2();
238

ia.m3();
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: We can write an interface inside an interface, but, the respective iplementation class must be
provided with in the same outer interface.

EX:
interface I1
{
interface I2
{
void m1();
void m2();
void m3();
}
class A implements I2
{
public void m1()
{
System.out.println("m1-A");
}
public void m2()
{
System.out.println("m2-A");
}
public void m3()
{
System.out.println("m3-A");
}
}
}
class Test
{
public static void main(String[] args)
{
I1.I2 i12=new I1.A();
i12.m1();
i12.m2();
i12.m3();
}
}
239
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Method Local Inner class:
Declaring class inside a method is called as Method Inner class.

If we declare a class inside a method then the scope of that is available upto the respective method
only, we have to create object for5 that inner class in the respective method onky, we have to access
the members of that inner class inside the respective methpd.

EX:
class A
{
void m1()
{
class B
{
void m2()
{
System.out.println("m2-B");
}
void m3()
{
System.out.println("m3-B");
}
}//B
B b=new B();
b.m2();
b.m3();
}//m1()
}//A
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();
}
}
240
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Anonymous Inner classes:
Anonymous inner classes are nameless inner classes, these are used to provide implementation for
abstract classes and interfaces.

Note: For abstract class we may take sub classes and for interfaces we may take implementatin classes
to provide implementations , but, here sub classes of the abstract class and implementation class of the
interface are able to allow their own members and these sub classes and implementation classes
objects are having their identity, not interface identity and abstract class identity.

In java applicatins, if we want to provide implementations for only abstract class members or interface
members and if we want to create objects with interface identity and with abstract class identity then
we have to use Anonymous inner classes.

Syntax:
abstract class Name / interface Name
{
----
}
class Outer{
Name ref_Var=new Name()
{
---implementation----
};
}
EX:
abstract class A
{
void m1()
{
System.out.println("m1-A");
}
abstract void m2();
abstract void m3();
}
class Outer
{
A a=new A()
{
void m2()
241

{
System.out.println("m2-AIC");
Page

}
void m3()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
System.out.println("m3-AIC");
}
void m4()
{
System.out.println("m4-AIC");
}
};
}
class Test
{
public static void main(String[] args)
{
Outer o=new Outer();
o.a.m1();
o.a.m2();
o.a.m3();
//o.a.m4();--> Error
}
}

EX:
interface I
{
void m1();
void m2();
void m3();
}
class Outer
{
I i=new I()
{
public void m1()
{
System.out.println("m1-AIC");
}
public void m2()
{
System.out.println("m2-AIC");
}
242

public void m3()


{
Page

System.out.println("m3-AIC");
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public void m4()
{
System.out.println("m4-AIC");
}
};
}
class Test
{
public static void main(String[] args)
{
Outer o=new Outer();
o.i.m1();
o.i.m2();
o.i.m3();
//o.i.m4();--> Error
}
}

IN general, we will use Anonymous Inner classes when we have requirement to pass any interface or
abstract class references as parameters to the methods.

EX:
interface I
{
void m1();
void m2();
void m3();
}
class A
{
void meth(I i)
{
i.m1();
i.m2();
i.m3();
}
}
class Test
{
public static void main(String[] args)
243

{
A a=new A();
Page

a.meth(new I()
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public void m1()
{
System.out.println("m1-AIC");
}
public void m2()
{
System.out.println("m2-AIC");
}
public void m3()
{
System.out.println("m3-AIC");
}
public void m4()
{
System.out.println("m4-AIC");
}
});
}
}

244
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Wrapper Classes
Collection is an object , it able to store a group of other objects.

In java applications, Collection objects are able to store only objects , they will not store primitive
data.

JAVA has provided 8 no of wrapper classes w.r.t the 8 no of primitive data types.

Primitive DTs Wrapper Classes

byte --------------------> java.lang.Byte


short--------------------> java.lang.Short
int----------------------> java.lang.Integer
long---------------------> java.lang.Long
float--------------------> java.lang.Float
double-------------------> java.lang.Double
char---------------------> java.lang.Character
boolean------------------> java.lang.Boolean

Note: Java has provided all the wrapper classes in the form of immutable classes.

Conversions from Primitve Type To Object Type:

a)By using parameterized constructors from wrapper classes.


public XXX(xxx value)
XXX ----> Wrapper classes
xxx ----> Primitive types.
EX:int i=10;
Integer in=new Integer(i);
System.out.println(i+" "+in);

OP: 10 10

b)By using valueOf(-) method provided by Wrapper classes:


public static XXX valueOf(xxx value)
XXX ----> Wrapper classes
xxx ----> primitive data types
245

EX: int i=10;


Integer in=Intreger.valueOf(i);
System.out.println(i+" "+in);
Page

OP: 10 10

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


c)By using Auto-Boxing approach:
Auto-Boxing approach was provided by JDK5.0 version, in this approach no need to use prederfined
methods and constructor, simply, we have to assign primitive variable to wrapper class reference
variable.
EX: int i=10;
Integer in=i;
System.out.println(i+" "+in);
OP: 10 10

2.Conversions from Object type to primitive types:


a)By using xxxValue() method from wrapper classes:
public xxx xxxValue()
xxx ----> primitive data types
EX: Integer in=new Integer(10);
int i=in.intValue();
System.out.println(in+" "+i);
OP: 10 10
b)By using Auto-Unboxing:
Auto-Unboxing was provided by JDK5.0 version, in this approach no need to use any prdefined
methods, simply assign wrapper class reference variables to the respective primitive variables.

EX: Integer in=new Integer(10);


int i=in;
System.out.println(in+" "+i);

OP: 10 10
3)Conversions from String type to Object Type:
a)By using String parameterized constructors from wrapper classes:
public XXX(String value)
XXX----> Wrapper classes
EX: String data="10";
Integer in=new Integer(data);
System.out.println(data+" "+in);
OP: 10 10
b)By using static valueOf(-) method from wrapper classes:
public
static XXX valueOf(String data)
EX: String data="10";
Integer in=Integer.valueOf(data);
246

System.out.println(data+" "+in);
Page

OP: 10 10

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.COnversions from Object type to String type:
a)By using toString() method from Wrapper classes:
public String toString()
EX: Integer in=new Integer(10);
String data=in.toString();
System.out.println(in+" "+data);
OP: 10 10

b)By Using '+' concatination operator:


If we concatinate any reference variable with "" by using '+' operator then JVM will access
toString() method over the provided reference variable.
EX: Integer in=new Integer(10);
String data=""+in;
System.out.println(in+" "+data);
OP: 10 10

5.Conversions from Primitive data types to String data types:


a)By using static toString() method from werapper classes:
public static String toString(xxx value)
xxx----> Primitive types
EX: int i=10;
String data=Integer.toString(i);
System.out.println(i+" "+data);
OP: 10 10
b)By using '+' concatination operator:
If we concatinate any primitive variable with "" by using '+' operator then the resultent value will be
generated in String data type.
EX: int i=10;
String data=""+i;
System.out.println(i+" "+data);
OP: 10 10

6.Conversions from String type to primitive type:


a)By using parseXXX() methode from wrapper classes:
public static xxx parseXxx(String data)
EX: String data="10";
int i=Integer.parseInt(data);
System.out.println(data+" "+i);
OP: 10 10
247
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Packages
package is the collection of related classes and interfaces as a single unit.

Package is a folder contains .class files representing related classes and interfaces

In java applications, packages are able to provide the following advantages.

1.Modularity
2.Abstraction
3.Security
4.Sharability
5.Reusability

1.Modularity:
Deviding a requirement set into no of pieces , providing solutions to the individual parts and
combining all individual solutions to a single is called as "Modularization".

In java applications, Module is a folder contains .class files representing related classes and
interfaces as a single unit.

Due to the above module definition, we can conclude that Packages are able to improve modularity.

2.Abstraction:
If we declare classes and interfaces in a module or in a package then that classes and interfaces are
not visible in out side of the package bydefault, so that, packages are able to improve Abstraction.

3.Security:
IN java applications, packages are able to provide Abstraction and Encapsulation, where both are
able to improve Security.

4.Sharability:
In java applications, if we declare packages one time then we are able to share that package content
to any no of applications or modules at a time.

5.Reusability

In java applications, if we declare a package one time then we are able to reuse any no of times with in
248

a single application or in more than one application.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


There are two types of packages in java .
1.Predefined Packages
2.User defined Packages

1.Predefined Packages:
These packages are provided by JAVA programming language along with Java software.

EX1: java.lang :

This package is default package in java applications , no need to import this package to the present
java file, when we save java file with .java extension then automatically java.lang package is imported
internally.
This package is able to provide all fundamental classes and interfaces which are required to prepare
basic java applications.
java.lang package includes the following classes and interfaces to prepare java applications.

String, StringBuffer, StringBuilder,....


Object, System, Class,......
Exception , ArithmeticException, NullPointerException,...
Thread, Runnable, Cloneable, Comparable......
Integer, Byte, Short, Float, Long,.....

EX2: java.io :

This package is able to provide predefined classes and interfaces inorder to perform Input and Output
operations in Java.

This package includes the following classes and interfaces in java applications.

InputStream, ByteArrayInputStream, FileInputSTream,.....


OutputStream, ByteArrayOutputStream, FileOutputStream,.....
Reader, CharArrayReader, FileReader, .......
Writer , CharArrayWriter, FileWriter,.......
Serializable, Externalizable,.......

EX3: java.util :
249
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


This package is able to provide all predefined classes and interfaces which are representing data
structeres .

This package is able to provide classes and interfaces like below.

Collection, List, Set,Queue


ArrayList, Vector, Stack, LinkedList.
HashSet, LinkedHashSet, SortedSet, NavigableSet, TreeSet
Queue, PriorityQueue, BlockingQueue, LinkedBlockingQueue,.....
Map, HashMap, LinkedHashMap, IdentityHashMap, WeakHashMap,.....

EX4: java.awt :

This package is able to provide predefined classes and interfaces repersenting all GUI components
inorder to prepare GUI applications.

This packege has provided the following classes and interfaces to prepare GUI applications.

Component, Label, TextField, TextArea, Button, CheckBox, List, Choice, Frame,.....

EX5: javax.swing :

This package is able to provide predefined library to prepare GUI applications.

Q)What are the differences between AWT[java.awt] and SWING[javax.swing]?

Ans:
1. AWT provided GUI components are platform dependent GUI components.
SWING provided GUI components are Platform Independent GUI Components.

2. AWT provided GUI components are heavy weight GUI components.


SWING GUI components are light weight GUI components.

3. AWT provided GUI COmponents are basic GUI components.


EX:TextField, TextArea, Label, Button,....
SWING provided GUI components are most advanced GUI components.
EX: JColorChooser, JFileChooser, JTable, JTree,....

4. AWT provided GUI components are able to reduce application performance.


250

SWING provided GUI components are able to improve application performance.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


javax.swing package has provided the following predefined classes and interfaces to design GUI
applications.

JComponent, JTextField, JPasswordField, JButton, JCheckBox, JRadioButton, JFrame,


JColorChooser, JFileChooser,......

EX6: java.net :

If we prepare any java application with out using Client-Server Arch then that java application is
called as Standalone Application.

If we prepare any java application on the basis of Client-Server Arch then that java application is
called as Distributed application.

To prepare distributed applications, JAVA has provided the following distributed technologies.
1.Socket Programming
2.RMI[Remote Method Invocation]
3.CORBA[Common Object Request Broker Arch/Agent]
4.EJBs[Enterprise Java Beans]
5.Web Services

java.net package has provided predefined library to prepare distributed applications by using Socket
Programming.

Socket
ServerSocket
URL, URI, URN
URLConnection
---
---

EX7: java.rmi :

java.rmi package is able to provide predefined library to prepare Distributed applications on the basis
RMI .

Remote
RemoteException
Naming
251

---
---
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX8: java.sql :

The process of interacting with database from java application is called as JDBC[Java Dayabase
Connectivity].

To prepare JDBC applications, java has provided predefined library in the form of java.sql package.

java.sql package has provided the following classes and interfaces to prepare JDBC applications.

Driver, DriverManager, Connection, Statement, PreparedStatement, CallableStatement, ResultSet,


ResultSetMetaData, DatabaseMetaData, ....

User Defined Packages:


These packages are defined by the developers as per their application requirements.

Syntax: package package_Name;

If we want to use package declaration statement in java applications then we have to use the following
two conditions.
1.Package Declaration Statement must be first statement.
2.Package name must be unique, it must not be sharable and it must not be duplicated.

Q)Is it possible to provide more than one package declaration statement with in a single java file?

Ans:
No, it is not possible to provide more than one package declaration statement with in a single java file,
because, package declaration statement must be provided as first statement in java files.

To provide package names in java applications, JAVA has provided a convention like to include our
company domain name in reverse.

EX:
package com.durgasoft.icici.transactions.deposit;
com.durgasoft---> Company Domain name in reverse.
icici -----> client/project name
transactions---> Module name
deposit ------> sub module name

If we declare classes and interfaces in a package and if we want to use these classes and interfaces in
252

the present java file then we have to import the respective package to the present java file.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To import packages to the present java file we have to use the following syntaxes.

import package_Name.*;
--> It able to import all the classes and interfaces of the specified package.

EX: import java.util.*;

import package_Name.member_Name;
--> It able to import only the specified member from the specified package.

EX: import java.util.ArrayList;

Note: In java files, we are able to provide atmost one package declaration statement, but, we are able
to provide any no of import statements.

Q)Is it possible to use classes and interfaces of a particular package with out importing the respective
package?

Ans:
Yes, it is possible to use classes and interfaces of a particular package with out importing that package,
but by using fully qualified names of the respective classes and interfaces.
Note: Specifying class name or interface name along with package name is called as "Fully Qualified
Name"

EX: java.io.BufferedReader
java.util.ArrayList
---
----
A java program with import statement:
import java.io.*;
---
BufferedReader br=new BufferedReader(new InputStreamReader( System.in));

A Java program with out import statement:

java.io.BufferedReader br=new java.io.BufferedReader(new java.io.InputStreamReader(System.in));


253
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Application-1:

D:\abc
------
Employee.java

C:\xyz
------
com
|----durgasoft
|----core
|-----Employee.class

D:\javaapps\ packages
---------------------
Test.java
Test.class

Employee.java
--------------
package com.durgasoft.core;
public class Employee
{
String eid;
String ename;
float esal;
String eaddr;
public Employee(String eid, String ename, float esal, String eaddr)
{
this.eid=eid;
this.ename=ename;
this.esal=esal;
this.eaddr=eaddr;
}
public void getEmpDetails()
{
System.out.println("Employee Details");
System.out.println("-----------------------");
254

System.out.println("Employee Id :"+eid);
System.out.println("Employee Name :"+ename);
Page

System.out.println("Employee Salary :"+esal);


System.out.println("Employee Address:"+eaddr);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}

On Command Prompt:
D:\abc>javac -d C:\xyz Employee.java

Test.java

import com.durgasoft.core.*;
public class Test
{
public static void main(String[] args)
{
Employee emp=new Employee("E-111", "Durga", 50000.0f, "Hyderabad");
emp.getEmpDetails();
}
}

On Command Prompt:
D:\javaapps\packages>set classpath=C:\xyz;.;
D:\javaapps\packages>javac Test.java
D:\javaapps\packages>java Test
--- Employee Details----

classpath: To specify the location where package is existed.


import com.durgasoft.core.* : To specify in which package Employee class is existed.

JAR Files in JAVA:


In java applications development, moving .class files from one machine to another machine in the
network , uploading .class files directly to the websites,.... are not suggestible. Always, it is
suggestible to prepare JAR files for the .class files inorder to move in the network and to upload
applications in the websites.

To create JAR files we have to use the following Command .

jar -cvf File_Name.jar *.*

EX:
D:\javaapps>jar -cvf durgaapp.jar *.*
255

To extract JAR file we have to use the following command on command prompt.
Page

jar -xvf file_Name.jar

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
D:\javaapps>jar -xvf durgaapp.jar

If we want to access packages or classes or interfaces from JAR file then we have to set
classpath path environment variable to JAR file directly.

Application-2:

D:\abc
------
Account.java

C:\xyz
------
com
|---durgasoft
|----icici
|-----accounts
|------Account.class

C:\xyz
-------
durga_icici.jar

Move durga_icici.jar from C:\xyz location to D:\xyz location


D:\xyz
-------
durga_icici.jar

D:\javaapps\packages
---------------------
Test.java
Test.class
256
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Account.java

package com.durgasoft.icici.accounts;
public class Account
{
String accNo;
String accName;
String accType;
String accBranch;
String accBank;
public Account(String accNo, String accName, String accType, String accBranch, String
accBank)
{
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
this.accBranch=accBranch;
this.accBank=accBank;
}
public void getAccountDetails()
{
System.out.println("Account Details");
System.out.println("---------------------");
System.out.println("Account Number :"+accNo);
System.out.println("Account Name :"+accName);
System.out.println("Account Type :"+accType);
System.out.println("Account Branch :"+accBranch);
System.out.println("Account Bank :"+accBank);
}
}

On Command Priompt:
D:\abc>javac -d C:\xyz Account.java
C:\xyz>jar -cvf durga_icici.jar *.*

Move durga_icici.jar from C:\xyz location to D:\xyz location.


257
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Test.java
import com.durgasoft.icici.accounts.*;
public class Test
{
public static void main(String[] args)
{
Account acc=new Account("abc123", "Durga", "Savings", "S R Nagar", "ICICI");
acc.getAccountDetails();
}
}

On Command Prompt:
D:\javaapps\packages>set classpath=D:\xyz\durga_icici.jar;.;
D:\javaapps\packages>javac Test.java
D:\javaapps\packages>java Test
---- Account Details-----

MANIFEST File in JAR :


MANIFEST.MF file is created by "jar" command at the time of creating JAR file under "META-INF"
folder and it will provide metadata about the jar file in the from of Key-Value pairs.

Executable Jar Files:


If we prepare any JAR file with main class and main() method then that jar file is called as "Executable
Jar" file.

To prepare Executable JAR file we have to use the following steps.

1.Prepare Java application as per the requirement and Compile Java application:
EX:D:\javaapps\packages\ Test.java

import java.awt.*;
class LogoFrame extends Frame
{
LogoFrame()
{
this.setVisible(true);
this.setSize(900,300);
this.setBackground(Color.green);
this.setTitle("Logo Frame");
258

}
public void paint(Graphics g)
Page

{
Font f=new Font("arial", Font.BOLD, 40);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


g.setFont(f);
this.setForeground(Color.red);
String logo="DURGA SOFTWARE SOLUTIONS";
g.drawString(logo, 100,150);
}
}
class Test
{
public static void main(String[] args)
{
LogoFrame lf=new LogoFrame();
}
}

On Command Prompt:
D:\javaapps\packages>javac Test.java

2.Prepare a text file with "Main-Class" attribute with Main class name:

D:\javaapps\packages\ abc.txt

Main-Class: Test

Note: The main intention to specify "Main-Class" attribute in text file is to send Main-Class attribute
information to MANIFEST.MF file.

3.Create JAR file with the MANIFEST.MF file, it must include


Main-Class attribute which we specified in text file.

On Command Prompt
D:\javaapps\packages>jar -cvfm durgaapp.jar abc.txt *.*

4.Execute JAR fle

On Command prompt:

D:\javaapps\packages>java -jar durgaapp.jar


259
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Internal Flow:
1.JVM will recognizse -jar option and JVM will take jar file name from command prompt.
2.JVM will search for jar file at current location, if it is available then JVM will goto
MANIFEST.MF file which is available META-INF folder.
3.In MANIFEST.MF file, JVM will search for Main-Class attreibute, if it is available then JVM
will take its value that is Main Class name.
4.After getting Main Class name from MANIFEST.MF file JVM will execute Main Class and
generate output.

If we want to execute the above application through batch file, first, we have to prepare batch file with
the required execution command then double click on that batch.

durga.bat[Take Text file and save with .bat extension]


-------------------------------------------------------
java -jar durgaapp.jar

NOTE: We must save both jar file and bat file at the same location.

260
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String Manipulations
In C and C++ applications, to perform String operations, C and C++ programming languages have
provided some predefined library in the form of the fucntions.

In Java, to perform String operations JAVA has provided the following predefined classes.

1.java.lang.String
2.java.lang.StringBuffer
3.java.lang.StringBuilder
4.java.util.StringTokenizer

Q)What is the difference between String and StringBuffer?

Ans:
1.String class objects are immutable objects, where Immutable objects are not allowing modifications
over their content, if we are trying to perform modifications over immutable object content then
operations are allowed , but, the resultent data will not be stored back in original object, where the
resultent data will be stored by creating new object.

StringBuffer objects are mutable objects, they are able to allow modifications on their content.

Q)What are the differences between StringBuffer and StringBuilder?

Ans:
1.StringBuffer class was introduced in JDK1.0 version.
StringBuilder class was introduced in JDK5.0 version.

2.StringBuffer is synchronized .
StringBuilder is not Synchronized.

3.Almost all the methods are Synchronized in StringBuffer.


No method is synchronized in Stringbuilder.

4.StringBuffer is able to allow only one thread to access data.


StringBuilder is able to allow more than one thread to access data.

5.StringBuffer is following sequential execution.


261

StringBuilder is following parallel execution.

6.StringBuffer will increase execution time.


Page

StringBuilder will reduce execution time.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


7.StringBuffer will reduce application performance.
StringBuilder will increase application performance.

8.StringBuffer is able to give guarantee for Data Consistency.


StringBuilder is unable to give guarantee for data consistency.

9.StringBuffer is threadsafe.
StringBuilder is not threadsafe.

Q)What is String tokenization and how it is possible to perform String Tokenization in java
applications?

Ans:
The process of deviding a string into no of tokens is called as String Tokenization.

To perform String Tokenization JAVA has provided a predefined class in the form of
java.util.StringTokenizer.

To perform String Tokenization in java applications we have to use the following steps.

1.Create StringTokenizer class object:

To create StringTokenizer class object we have to use the following constructor.

public StringTokenizer(String data)

EX: StringTokenizer st=new StringTokenizer("Durga Software Solutions");

When JVM encounter the above instruction, JVM will take the provided String , JVM will devide the
provided String into no of tokens and JVM will store thegenerated tokens by creating object for
StringTokenizer class.

NOTE: When StringTokenizer class object is created with the no of tokens then a pointer or cursor
will be created before the first token.

To get no of tokens which are existed in StringTokenizer class object we have to use the following
method.
262

public int countTokens()


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.Retrive tokens from StringTokenizer object:

To retrive tokens from StringTokenizer object we have to use the following steps for each and every
token.

a)Check whether more tokens are available or not from the current cursor position by using the
following method.

public boolean hasMoreTokens()


--> It will return true value if atleast next token is existed.
--> It will return false value if no more tokens are existed.
b)If atleast next token is available then read next token and move cursor to next position by using the
following method.
public String nextToken()

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer ("Durga Software Solutions");
System.out.println("No Of Tokens :"+st.countTokens());
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

263
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String Class Library :
Costructor:

1.public String()
--> It able to create an emptyy String object.
EX: String str=new Stirng();

2.public String(String str)


-->This constructor can be used to create String class object with the specified data.

EX: String str=new String("Durga Software Solutions");


System.out.println(str);
OP: Durga Software Solutions

Q)What is the difference between the folloowing two statements.


a)String str=new String("Durga Software Solutions");
b)String str="Durga Software Solutions";

Ans:
To create String class object if we use first statement then one String object will be created at heap
memory as per "new" keyword and another String object will be created at String Constant Pool Area
inside method Area as per "".

To create String object if we use second statement then String object will be created at String COnstant
Pool Area only in Method Area.

Note: The objects which are created in String Constant Pool Area are not eligible for Garbage
Collection.The objects which are created in Heap memory are eligible for Garbage Collection.

3.public String(byte[] b)
--> This constructor can be used to create String object with the String equalent of the specified byte[]
.
EX: byte[] b={65,66,67,68,69,70};
String str=new String(b);
System.out.println(str);
OP: ABCDEF
264
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.public String(byte[] b, int start_index, int no_Of_Chars)
-->This constructor can be used to create String class object with the String equalent of the specified
byte[] starts from the specified start index and upto the specified no of elements.

EX: byte[] b={65,66,67,68,69,70};


String str=new String(b,2,3);
System.out.println(str);

OP: CDE

5.public String(char[] ch)


--> This constructor can be used to create String object with the String equalent of the specified char[].

EX:char[] ch={'A','B','C','D','E','F'};
String str=new String(ch);
System.out.println(str);

OP: ABCDEF

6.public String(char[] ch, int start_Index,int no_Of_Chars)


--> It will create String object with the String equalent of the specified char[] starts from the specified
start index and upto the specified no of element.

EX:char[] ch={'A','B','C','D','E','F'};
String str=new String(ch,2,3);
System.out.println(str);

OP: CDE

Note: Construuctors 3 and 4 are used to convert data from byte[] to String and constuctors 5 and 6 are
used to convert data from char[] to String.

Methods:
1.public int length()
--> This method will return an integer value representing the no of characters existed in the String
including spaces.

EX: String str=new String("Durga Software Solutions");


System.out.println(str.length());
265

OP: 24
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.public String concat(String str)
--> This method will add the specified String to String object content in immutable manner.

EX:
String str1=new String("Durga ");
String str2=str1.concat("Software ");
String str3=str2.concat("Solutions");
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);

OP: Durga
Durga Software
Durga Software Solutions

EX:
String str="Durga".concat("Software ").concat("Solutions");
System.out.println(str);

OP:
Durga Software Solutions

3.public boolean equals(Object obj)


-->This method will check whether the two String objects content is same or not. if two string objects
content is same then equals(-) method will return "true" value otherwise equals(-) method will return
"false" value.

Q)What is the difference between == operator and equals(-) method?

Ans:
'==' is basically a comparision operator, it will check whether the provided operand values are same or
not, where operands may be normal primitive variables or object reference variables.

Iniitally equals(-) method was defined in java.lang.Object class , it was implemented in such a way
that to provide comparision between two object reference values.

String class has overridden Object class equals(-) method in such a way that to provide comparision
between two String object contents
266
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A();

int i=10;
int j=10;

String str1=new String("abc");


String str2=new String("abc");

System.out.println(i == j);// true


System.out.println(a1 == a2);// false
System.out.println(str1 == str2);// false
System.out.println(a1.equals(a2));// false
System.out.println(str1.equals(str2));//true
}
}

4.public boolean equalsIgnoreCase(String str)


--> In String class, equals(-) method will perform case sensitive comparision between two String
object contents, but, equalsIgnoreCase(-) method will perform case insensitive comparision between
two String objects content.

EX:
String str1=new String("abc");
String str2=new String("ABC");
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));

OP:
false
true
267
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5.public int compareTo(String str)
--> This method will check whether two string objects contents are existed in dictinary order or not.

str1.compareTo(str2)
a)If str1 come first when compared with str2 in dictionary order then compareTo() method will return -
ve value.
b)If str2 come first when compared with str1 in dictinary order then compareTo() method will return
+ve value.
c)If str1 and str2 are available at the same position in dictionary order then compareTo() method will
return 0 value.

EX:
String str1=new String("abc");
String str2=new String("def");
String str3=new String("abc");
System.out.println(str1.compareTo(str2));
System.out.println(str2.compareTo(str3)); System.out.println(str3.compareTo(str1));

OP: -3
3
0
6.public boolean startsWith(String str)
--> It will check whether the String starts with the specified String or not.

7.public boolean endsWith(String str)


--> It will check whether the String ends with the specified String or not.

8.public boolean contains(String str)


--> It will check whether String contains the specified String or not.

EX:
String str=new String("Durga Software Solutions");
System.out.println(str.startsWith("Durga"));
System.out.println(str.endsWith("Solutions"));
System.out.println(str.contains("Software"));
OP:
true
true
true
268
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


9.public String replace(char old_Char, char new_Char)
-->This method will replace the specified old char with the specified new char.

10.public char charAt(int index)


--> It will return a character which is existed at the specified index value.

11.public int indexOf(String str)


--> It will return an index value where the first occurence of the specified String.

12.public int lastIndexOf(String str)


--> It will return an index value where the last occurence of the specified String.

EX:
String str=new String("Durga Software Solutions");
System.out.println(str);
System.out.println(str.replace('S', 's'));
System.out.println(str.charAt(6));
System.out.println(str.indexOf("So"));
System.out.println(str.lastIndexOf("So"));
OP:
Durga Software Solutions
Durga software solutions
S
6
15

13.public String substring(int start_index)


--> This method return a substing starts from the specified index value.

14.public String substring(int start_Index, int end_Index)


--> This method will return a substring starts from the specified start index and upto the specified end
index.

EX:
String str=new String("Durga Software Solutions");
System.out.println(str.substring(6));
System.out.println(str.substring(6,14));
OP:
Software Solutions
269

Software
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


15.public byte[] getBytes()
--> This method will convert data from Strng to byte[].

16.public char[] toCharArray()


--> This method will convert data from String to char[].

EX:
String str=new String("Durga Software Solutions");
byte[] b=str.getBytes();
for(int i=0;i<b.length;i++)
{
System.out.print(b[i]+" ");
}
System.out.println();
char[] ch=str.toCharArray();
for(int i=0;i<ch.length;i++)
{
System.out.print(ch[i]+" ");
}

17.public String[] split(String str)


-->It will devide the String into no pieces on the basis of the provided String.

EX:
String str=new String("Durga Software Solutions");
String[] s=str.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}

18.public String trim()


-->This method will remove pre-spaces and post-spaces of a particular String.

19.public String toLowerCase()


--> It will convert String into lower case letters.
270
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


20.public String toUpperCase()
--> It will convert String into Upper case letters.
EX:
String str=new String(" Durga Software Solutions ");
System.out.println(str);
System.out.println(str.trim());
String str1=new String("Durga Software Solutions");
System.out.println(str1.toLowerCase());
System.out.println(str1.toUpperCase());

StringBuffer:

Costructors:
1.public StringBuffer()
-->This constructor can be used to create an empty StringBuffer object with 16 elements as initial
capacity.

EX: StringBuffer sb=new StringBuffer();


System.out.println(sb.capacity());
OP: 16

2.public StringBuffer(int capacity)


--> This constructor can be used to create an empty StringBuffer object with the specified capacity
value.

EX: StringBuffer sb=new StringBuffer(10);


System.out.println(sb.capacity());
OP: 10

3.public StringBuffer(String str)


--> This constructor can be used to create StringBuffer object with the specified data .

New_capacity=Iitial_Capacity+data_Length;

EX:
StringBuffer sb=new StringBuffer("abc");
System.out.println(sb);
System.out.println(sb.capacity());

OP: abc
271

19
Page

Methods:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.public StringBuffer append(String data)
-->This method will append the specified data to the StringBuffer object content.

EX:
StringBuffer sb1=new StringBuffer("Durga ");
StringBuffer sb2=sb1.append("Software ");
StringBuffer sb3=sb2.append("Solutions");
System.out.println(sb1);
System.out.println(sb2);
System.out.println(sb3);

OP:
Durga Software Solutions
Durga Software Solutions
Durga Software Solutions

2.public void ensureCapacity(int capacity)


-->This method can be used to set a particular capacity value to StringBuffer object . If the provided
capacity value is less than 16 then StringBuffer object will take 16 as capacity value. If the provided
capacity value is greater than 16 and less than 34 then StringBuffer will take 34 as capaqcity value. If
the provided capacity value is greater than 34 then StringBuffer object will take the specified value as
capacity value.

EX:
StringBuffer sb=new StringBuffer();
sb.ensureCapacity(10);
System.out.println(sb.capacity());

OP: 16

3.public StringBuffer reverse()


-->This method will reverse the content of StringBuffer object.

EX:
StringBuffer sb=new StringBuffer("Durga Software Solutions");
System.out.println(sb);
System.out.println(sb.reverse());
272
Page

4.public StringBuffer delete(int start_index, int end_index)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


--> This method can be used to delete a string from StringBuffer object content starts from the
specified start index and upto the specified end idex.

EX:
StringBuffer sb=new StringBuffer("Durga Software Solutions");
System.out.println(sb);
System.out.println(sb.delete(6,14));
EX:
Durga Software Solutions
Durga Solutions

5.public StringBuffer insert(int index, String str)


-->This method can be used to insert the specified String at the specified index in StringBuffer object.

EX:
StringBuffer sb=new StringBuffer("Durga Solutions");
System.out.println(sb);
System.out.println(sb.insert(6,"Software"));
OP:
Durga Solutions
Durga Software Solutions

273
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Exception Handling
Q)What is the difference between Error and Exception?

Ans:
Error is a problem in java applications.
There are two types of errors in java.
1.Compile time Errors
2.Runtime Errors

1.Compile time errors:


These are problems identified by the compiler at compilation time.
In general, There are three types of compile time errors.

1.Lexical Errors: Mistakes in keywords,..

EX:int i=10; ----> Valid


nit i=10; ----> Invalid

2.Syntax Errors: Gramatical Mistakes or syntactical mistakes.

EX: int i=10;---> Valid


i int 10 ; --> Invalid

3.Semantic Errors: Providing operators inbetween incompatible types.

EX: int i=10;


int j=20;
int k=i+j; ----> Valid

EX: int i=10;


boolean b=true;
char c= i+b;----> Invalid.

NOTE: Some other errors are generated by Compiler when we voilate JAVA rules and regulations in
java applications.

EX: Unreachable Statements, valriable might not have been initialization


,possible loss of precision,....
274
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.Runtime Errors:
These are the problems for which we are unable to provide solutions programatically and these
errors are not identified by the compilers and these errors are occurred at runtime.

EX: Insufficient Main Memory.


Unavailability of IO Components.
JVMInternal Problems.

2.Exception:
Exception is a problem, for which we are able to provide solutions programatically.

EX: ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
----
-----
Exception: Exception is an unexpected event occured in java applications at runtime , which may be
provided by users while entering dynamic input in java applications, provided by the Database Engines
while executing sql queries in Jdbc applications, provided by Network while establish connection
between local machine and remote machine,.....causes abnormal termination to the java applications.

There are two types of terminations in java applications.

1.Smooth Termination

Terminating program at end is called as Smooth termination.

2.Abnormal Termination

Terminating program in the middle is called as Abnormal Termination.

In general, Exceptions are providing abnormal terminations, these abnormal termionations may crash
local operating systems , these abnormal terminations may provide hangedout situations to the
network,.....

To overcome the above problems we have to handle exceptions properly, to handle exceptions
properly wew have to use "Exception Handling Mechanism".

Java is a Robust programming language, because,


275
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Java is having very good memory management system in the form of Heap Memory Management
system , it is a dynamic memory management system, it allocates and deallocates memory for the
objects at runtime.
2.Java is having very good exception handling mechanisms, JAVA has provided very good predefined
library to represent and handle almost all the frequently generated exceptions.

There are two types of exceptions in Java.


1.Predefined Exceptions
2.User defined Exceptions

1.Predefined Exceptions

These Exceptions are defined by JAVA programming language and provided along Java software.
-- Diagram----

There are two types predefined Exceptions.


1.Checked Exceptions
2.Unchecked Exceptions

Q)What is the difference between checked exceptions and Unchecked Exceptions?

Ans:
Checked Exception is an exception recognized at compilation time, but, not occured at compilation
time.

Unchecked Exceptions are not recognized at compilation time, these exceptions are recognized at
runtime by JVM.

Note: In Exceptions Arch, RuntimeException and its sub classes and Error and its sub classes are the
examples for Unchecked Exceptions and all the remaining classes are the examples for Checked
Exceptions.

There are two types of Checked Exceptions


1.Pure Checked Exceptions
2.Partially Checked Exceptions

Q)What is the difference between Pure checked exception and Partially Checked Exceptions?
Ans:
If any checked exception is having only checked exceptions as sub classes then this exception is called
as Pure Checked Exception.
276

EX: IOException
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If any Checked Exception contains atleast one sub class as unchecked exception then that Checked
Exception is called as Partially Checked Exception.

EX: Exception , Throwable

Predefined Exceptions Overiview:

1.ArithmeticException

In java applications, when we have a situation like a number is devided by zero then JVM will rise
Arithmetic Exception.

EX:
class Test
{
public static void main(String[] args)
{
int i=10;
int j=0;
float f=i/j;
System.out.println(f);
}
}

If we run the above program then JVM will provide ArithmeticException with the following Exception
message.

Exception in thread "main" java.lang.ArithmeticException: / by zero


at Text.main(Test.java:7)

The above exception message is devided into the following three parts.
1.Exception Name: java.lang.ArithmeticException
2.Exception Descrioptioun: / by zero
3.Exception Location : Test.java:7 277
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.NullPointerException:
In java applications, when we access any instance variable and instance methods by using a
reference variable contaiuns null value then JVM will rise NullPointerException.

EX:
class Test
{
public static void main(String[] args)
{
java.util.Date d=null;
System.out.println(d.toString());
}
}

If we run the above code then JVMwill provide the following exception details.
1.Exception Name : java.lang.NullPointerException
2.Exception Description: --- No description----
3.Exception Location: Test.java:6

3.ArrayIndexOutOfBoundsException:
In java applications, when we insert an element to an array at a particular index value and when we
are trying to access an element from an array at a particular index value and if the specified index
value is in out side of the arrays size then JVM will rise an exception like
"ArrayIndexOutOfBoundsException".

EX:
class Test
{
public static void main(String[] args)
{
int [] a={1,2,3,4,5};
System.out.println(a[10]);
}
}

If we run the above program then JVM will rise an exception with the following details.
Exception Name : java.lang.ArrayindexOutOfBoundsException
Exception Description: 10
Exception Location: Test.java: 6
278
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.ClassCastException:
In java applications, we are able to keep sub class object reference value in super class reference
variable, but, we are unable to keep super class object reference value in sub class reference
variable. If we are trying to keep super class object reference value in sub class reference variable
then JVM will rise an exception like "java.lang.ClassCastException".

EX:
class A
{
}
class B extends A
{
}
class Test
{
public static void main(String[] args)
{
A a=new A();
B b=(B)a;
}
}

If we run the above code then JVM will rise an exception with the following details.
Exception Name: java.lang.ClassCastException
Exception Description: A can not be cast to B
Excepttion location: Test.java: 12

5.ClassNotFoundException:
In java applications, if we want to load a particular class bytecode to the memory with out creating
object then we will use the following method from java.lang.Class class.

public static Class forName(String class_Name)throws ClassNotFoundException

EX: Class c=Class.forName("A");

When JVM encounter the above instuction, JVM will search for A.class file at current location, at java
predefined library and at the locations refered by "classpath" environment variable, if the required
A.class file is not identified at all the locations then JVM will rise ClassNotFoundException.
279
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
static
{
System.out.println("Class Loading");
}
}
class Test
{
public static void main(String[] args) throws Exception
{
Class c=Class.forName("AAA");
}
}

If we run this code the JVM will provide the following exception details.
1.Exception Name: java.lang.ClassNotFoundException
2.Exception Description: AAA
3.Exception Location: Test.java: 12
4.InstantiationException 5.IllegalArgumentException

In java applications, if we load class bytecode by using


"Class.forName(-)" method then to create object explicitly we have to use the following method from
java.lang.Class class.

public Object newInstance()

EX: Object obj=c.newInstance()

When JVM encouter the above code then JVM will search for 0-arg constructor and non-private
constructor in the loaded class. if 0-arg constructor is not availabnle, if parameterized construcvtor is
existed then JVM will rise "java.lang.instantiationException". If non-private constructor is not
available, if private constructor is available then JVM will rise "java.lang.IllegalAccessException".
280
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX1:
class A
{
static
{
System.out.println("Class Loading");
}
A(int i)
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args) throws Exception
{
Class c=Class.forName("A");
Object obj=c.newInstance();
}
}

If run the above code then JVM will provide an exception with the following details.
1.Exception Name : java.lang.InstantiationException
2.Exception Description: A
3.Exception Location:Test.java: 17

EX:
class A
{
static
{
System.out.println("Class Loading");
}
private A()
{
System.out.println("Object Creating");
}
}
class Test
{
281

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


{
Page

Class c=Class.forName("A");
Object obj=c.newInstance();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}

If we run the above code then JVM will rise an exception with the following details
1.Exception Name : java.lang.IllegalAccessException
2.Exception Decrition: Test class can not access the members of class A with the
modifier "private".
3.Exception Location" Test.java: 17

'throw' keyword:
'throw' is a java keyword, it can be used to rise exceptions intentionally as per the developers
application requirement.
Syntax:
throw new Exception_Name("----Exception Description-----");

EX:
class Test
{
public static void main(String[] args)throws Exception
{
String accNo=args[0];
String accName=args[1];
int pin_Num=Integer.parseInt(args[2]);
String accType=args[3];
System.out.println("Account Details");
System.out.println("---------------------");
System.out.println("Account Number :"+accNo);
System.out.println("Account Name :"+accName);
System.out.println("Account Type :"+accType);
System.out.println("Account PIN Number:"+pin_Num);
if(pin_Num>=1000 && pin_Num<=9999)
{
System.out.println("valid PIN Number");
}
else
{
throw new RuntimeException("Invalid PIN Number, enter Valid 4 digit
PIN Number");
}
}
282

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


D:\javaapps>javac Test.java
D:\javaapps>java Test abc123 AAA 1234 Ssavings
--- Account details with out Exception-----

D:\javaapps>java Test abc123 AAA 123 Savings


--- Account details are displayed with Exception-----

---Account details----
Exception in thread "main" java.lang.RuntimeException: Invalid PIN Number, enter valid 4 digit PIN
number
at Test.main(Test.java:17)

There are two ways to handle exceptions .


1.By using 'throws' keyword.
2.By using try-catch-finally block.

1.'throws' keyword:
It is a Java keyword,it can be used to bypass the generated exception from the present method or
constructor to the caller method (or) constructor.

In Java applications, 'throws' keyword will be used in method declarations,not in method body.

In Java applications,”throws” keyword allows an exception class name,it should be either same as
the generated exception or super class to the generated exception.It should not be subclass to the
generated Exception.
'throws' keyword allows more than one exception in method prototypes.

In Java applications,”throws” keyword will be utilized mainly for checked exceptions.

EX:void m1() throws RuntimeException{


throw new ArithmeticException();
}

Status:Valid

EX:void m1() throws FileNotFoundException{


throw new IOException();
}
283

Status:InValid
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
Void m1() throws NullPointerException,ClassNotFoundException{
}

Status:Valid

EX:
Void m1() throws IOException,FileNotFoundException
{
}

Status:Valid , Not Suggestible

If we specify any super exception class along with throws keyword,then it is not necessary to specify
any of its child exception classes along with “throws” keyword.

NOTE:In any Java method,if we call some other method which is bypassing an exception by using
“throws” keyword,then we must handle that exception either by using “throws” keyword in the present
method[Caller Method] prototype or by using “try-catch-finally” in the body of the present
method[Caller method].

EX:
Void m1() throws Exception{
-----
------
}
Void m2(){
try{
m1();
}
catch(Exception e){
e.printStackTrace();
}
}
284
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
void m1() throws Exception{
----
}
void m2() throws Exception{
m1();
}

EX:
import java.io.*;
class A{
void add() throws Exception{
concat();
}
Void concat() throws IOException{
throw new IOException();
}
}
class Test{
public static void main(String args[]) throws Throwable{
A a=new A();
a.add();
}
}

Internal Flow:
If we execute the above program,then JVM will recognize throw keyword in concat() method and
JVM will rise an exception in concat() method, due to throws keyword in concat() method prototype,
Exception will be bypassed to concat() method call that is in add(), due to throws keyword in add()
method Exception will be bypassed to add() method call , that is , in main() method, Due to 'throws'
keyword in main() method Excepotion will be bypassed to main() method call , that is, to JVM, where
JVM will activate "Default Exception Handler" , where Default Exception Handler will display
exception details.

Q)What are the differences between “throw” and “throws” keywords?

Ans:
1.'throw' keyword can be used to rise the exceptions intentionally as Per the application reqirement.
'throws' keyword is able to by pass the exception from the present method to the caller method.
2.'throw' keyword will be utilized in method body.
285

'throws' keyword will be used in method declarations or in method prototype (or) in method header
part.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.'throw' keyword allows only one exception class name.
'throws' keyword allows more than one exception class name.

try-catch-finally:
In Java application “throws” keyword is not really an exception handler,because “throws” keyword
will bypass the exception handling responsibility from present method to the caller method.
If we want to handle the exceptions,the location where exceptions are generated then we have to use
“try-catch-finally”.

Syntax:
try{
----
}
catch(Exception_Name e){
----
}
finally{
----
}

where the purpose of try block is to include a set of exceptions , which may rise an exception.

If JVM identify any exception inside "try" block then JVM will bypass flow of execution to "catch"
block by skipping all the remaining instructions in try block and by passing the generated Exception
object reference as parameter.

If no exception is identified in "try" block then JVM will execute completely "try" block,at the end of
try block, JVM will bypass flow of execution to "finally" block directly.

The main purpose of catch block is to catch the exception from try block and to display exception
details on command prompt.

To display exception details on command prompt,we have to use the following three approaches.

1.e.printStackTrace()
2.System.out.println(e):
3.System.out.println(e.getMessage());

1.e.printStackTrace():
It will display the exception details like Exception Name,Exception Description and Exception
286

Location.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.System.out.println(e):
If we pass Exception object reference variable as parameter to System.out.println(-) method then
JVM will access Exception class toString() method internally,it will display the exception details
like Exception name,Exception description.

3.System.out.println(e.getMessage()):
Where getMessage() method will return a String contains the exception details like only Description
of the exception.

EX:
class Test{
public static void main(String args[]){
try{
throw new ArithmeticException("My Arithmetic Exception");
}
catch(ArithmeticException e){
e.printStackTrace();
System.out.println();
System.out.println(e);
System.out.println();
System.out.println(e.getMessage());
}
finally{
}
}
}
OP:
java.lang.ArithmeticException:My Arithmetic Exception
at Test.main(Test.java:7)

java.lang.ArithmeticException:My Arithmetic Exception

My Arithmetic Exception

Where the main purpose of finally block is to include some Java code , it will be executed
irrespective of getting exception in "try" block and irrespective of executing "catch" block.
287
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)What is the difference between "final","finally" and "finalize" in JAVA?

Ans:
1."final" is a keyword it can be used to declare constant expressions.
There are three ways to use final keyword in java applications.

a)final variable:It will not allow modifications over its value.


b)final methods:It will not allow method overriding.
c)final class:It will not allow inheritance, that is, sub classes.

2.finally block: It is part of try-catch-finally syntax,it will include some instructions,which must be
executed by JVM irrespective of getting exception from try block and irrespective of executing catch
block.

3.finalize(): It is a method in java.lang.Object class,it will be executed just before destroying objects
inorder to give final notification to the user about to destroy objects.

Q)Find the output from the following programs?


class Test{
public static void main(String args[]){
System.out.println("Before Try");
try{
System.out.println("Inside Try");
}
catch(Exception e){
System.out.println("Inside Catch");
}
finally{
System.out.println("Inside Finally");
}
System.out.println("After Finally");
}
}

OP:
Before try
Inside try
Inside finally
After finally
288
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: class Test{
public static void main(String args[]){
System.out.println("Before Try");
try{
System.out.println("Before Exception in try");
float f=100/0;
System.out.println("After Exception in try");
}
catch(Exception e){
System.out.println("Inside Catch");
}
finally{
System.out.println("Inside Finally");
}
System.out.println("After Finally");
}
}
OP: Before try
Before exception in try
Inside catch
Inside finally
After finally
Q)Find the output from the following program?
class A{
int m1(){
try{
return 10;
}
catch(Exception e){
return 20;
}
finally{
return 30;
}
}
}
class Test{
public static void main(String args[]){
A a=new A();
int val=a.m1();
289

System.out.println(val);
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
30

NOTE:finally block provided return statement is the finally return statement for the method

Q)Is it possible to provide "try" block without "catch" block?

Ans:
Yes,it is possible to provide try block with out catch block but by using "finally" Block.

Syntax:
try{
}
finally{
}
EX:
class Test{
public static void main(String args[]){
System.out.println("Before try");
try{
System.out.println("Before Exception inside try");
int i=100;
int j-0;
float f=i/j;
System.out.println("After Exception inside try");
}
finally{
System.out.println("Inside finally");
}
System.out.println("After Finally");
}
}

Status:No Compilation Error.

OP:
Before try
Before exception inside try
Inside finally
Exception in thread “main” java.lang.ArithmeticException:/by zero
290

at Test.main(Test.java:11)
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


REASON: When JVM encounter exception in try block,JVM will search for catch block,if no catch
block is identified,then JVM will terminate the program abnormally after executing finally block.

Q)Is it possible to provide "try" block with out "finally" block?

Ans:
Yes,it is possible to provide "try" block with out "finally" block but by using "catch" block.

Syntax:
try{
-------
--------
}
catch(Exception e){
-------------
-------------
}

Q)Is it possible to provide try-catch-finally

a)inside try block,


b)inside catch block and
c)inside finally block

Ans:
Yes,it is possible to provide try-catch-finally inside try block,inside catch block and inside finally
block.

Syntax-1:
try{
try{
}
catch(Exception e){
}
finally{
}
}
catch(Exception e){
}
finally{
291

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Syntax-2:
try{
}
catch(Exception e){
try{
}
catch(Exception e)
{
}
finally{
}
}
finally{
}

Syntax-3:
try{
}
catch(Exception e){
}
finally{
try{
}
catch(Exception e){
}
finally{
}
}

Q)Is it possible to provide more than one catch block for a single try block?

Ans:
Yes,it is possible to provide more than one catch block for a single try block but with the following
conditions.
1.If no inheritance relation existed between exception class names which are specified along with
catch blocks then it is possible to provide all the catch blocks in any order.If inheritance relation is
existed between exception class names then we have to arrange all the catch blocks as per Exception
classes inheritance increasing order.
2.In general,specifying an exception class along with a catch block is not giving any guarantee to rise
the same exception in the corresponding try block,but if we specify any pure checked exception along
292

with any catch block then the corresponding "try" block must rise the same pure checked exception.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ex1:
try{
}
catch(ArithmeticException e){
}
catch(ClassCastException e){
}
catch(NullPointerException e){
}

Status:Valid Combination

Ex2:
try{
}
catch(NullPointerException e){
}
catch(ArithmeticException e){
}
catch(ClassCastException e){
}

status:Valid Combination

Ex3:
try{
}
catch(ArithmeticException e){
}
catch(RuntimeException e){
}
catch(Exception e){
}

Status:Valid 293
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ex4:
try{
}
catch(Exception e){
}
catch(RuntimeException e){
}
catch(ArithmeticException e){
}

status: Invalid

Ex5:
try{
throws new ArithmeticException("My Exception");
}
catch(ArithmeticException e){
}
catch(IOException e){
}
catch(NullPointerException e){
}

Status:Invalid

Ex6:
try{
throw new IOException("My Exception");
}
catch(ArithmeticException e){
}
catch(IOException e){
}
catch(NullPointerException e){
}

status:Valid
294
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Custom Exceptions/User Defined Exceptions:
Custom Exceptions are the exceptions,which would be defined by the developers as per their
application requirements.
If we want to define user defined exceptions then we have to use the following steps:

1.Define User defined Exception class:


To declare user-defined Exception class,we have to take an user-defined class,which must be extended
from java.lang.Exception class.
Class MyException extends Exception
{
}
2.Declare a String parametrized constructor in User-Defined Exception class and access String
parametrized super class constructor by using "super" keyword:

class MyException extends Exception{


MyException(String err_Msg){
super(err_Msg);
}}

3.Create and Rise exception in Java application as per the application requirement:
try{
throw new MyException("My Custom Exception");
}
catch(MyException me){
me.printStackTrace();
}

class InsufficientFundsException extends Exception


{
InsufficientFundsException(String err_Msg)
{
super(err_Msg);
}
}
class Account
{
String accNo;
String accName;
String accType;
int balance;
295

Account(String accNo, String accName, String accType, int balance)


Page

{
this.accNo=accNo;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


this.accName=accName;
this.accType=accType;
this.balance=balance;
}
}
class Transaction
{
public void withdraw(Account acc, int wd_Amt)
{
try
{
System.out.println("Transaction Details");
System.out.println("-------------------------");
System.out.println("Account Number :"+acc.accNo);
System.out.println("Account Name :"+acc.accName);
System.out.println("Account Type :"+acc.accType);
System.out.println("Transaction Type :WITHDRAW");
System.out.println("Withdraw Amount :"+wd_Amt);
if(acc.balance>wd_Amt)
{
acc.balance=acc.balance-wd_Amt;
System.out.println("Total Balance :"+acc.balance);
System.out.println("Transaction Status:SUCCESS");
}
else
{
System.out.println("Total Balance :"+acc.balance);
System.out.println("Transaction Status:FAILURE");
throw new InsufficientFundsException("Funds are not Sufficient in
your Account, please enter valid Withdraw Amout");
}
}
catch (InsufficientFundsException e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println("**********ThanQ, Visit Again*********");
}
296

}
}
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
Account acc1=new Account("abc123", "Durga", "Savings", 10000);
Transaction tx1=new Transaction();
tx1.withdraw(acc1, 5000);
System.out.println();
Account acc2=new Account("xyz123", "Anil", "Savings", 10000);
Transaction tx2=new Transaction();
tx2.withdraw(acc2, 15000);
}
}

JAVA7 Features in Exception Handling:


1.Multi Catch block
2.Try-with-Resources/Automatic Resources Management/Auto close able Resources

1.Multi Catch block:


Consider the below syntax:
try{
}
catch(Exception e){
}

If we specify "Exception" class along with catch block then it able to catch and handle all the
exceptions which are either same as Exception or child classes to Exception, this approach will not
handling exceptions individually, it will handle all the exceptions in the common way.

If we want to handle to the Exceptions separately then we have to use multiple catch blocks for a
single try block.

try{
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ClassCastException e){
}

If we use this approach then no.of catch blocks are increased.


In Java applications,if we want to handle all the exceptions separately and by using a single catch
block then we have to use "JAVA7" provided multi- catch block
297
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Syntax:
try{
}
catch(Exception1 | Exception2 |....|Exception-n e){
}
where Exception1,Exception2....must not have inheritance relation otherwise Compilation error
will be raised.

EX:
class Test{
public static void main(String args[]){
try{
/* int a=10;
int b=0;
float c=a/b;
*/
/*java.util.Date d=null;
System.out.println(d.toString());
*/
int[] a={1,2,3,4,5};
System.out.println(a[10]);
}
catch(ArithmeticException | NullPointerException | ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}

Try-With-Resources/Auto Closeable Resources:

In general,in Java applications,we may use the resources like Files,Streams,Database Connections....as
per the application requirements.

If we want to manage the resources along with try-catch-finally in Java applications then we have to
use the following conventions.

1.Declare all the resources before "try" block.


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

The main intention to declare the resources before "try" block is to make available resources variables
298

to "catch" block and to "finally" block to use.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we want to close the resources in "finally" block then we have to use close() methods, which are
throwing some exceptions like IOException,SQLException depending on the resource by using
"throws" keyword,to handle these exceptions we have to use "try-catch-finally" inside "finally" block.

//Declare the resources


File f=null;
BufferedReader br=null;
Connection con=null;
try{
//create the resources
f=new File("abc.txt");
br=new BufferedReader(new InputStreamReader(System.in));
con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");
-----
-----
}
catch(Exception e){
}
finally{
//close the resources
try{
f.close();
br.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}

To manage the resources in Java applications,if we use the above convention then developers have to
use close() methods explicitly,Developers have to provide try-catch-finally inside "finally" block,this
convention will increase no.of instructions in Java applications.
To overcome all the above problems,JAVA7 version has provided a new Feature in the form of "Try-
With-Resources" or "Auto Closeable Resources".

In the case of "Try-With-Resources",just we have to declare and create the resources along with
"try"[not inside try block,not before try block] and no need to close these resources inside the finally
block,why because,JVM will close all the resources automatically when flow of execution is coming
out from "try" block.
In the case of "Try-With-Resources",it is not required to close the resources explicitly,it is not required
299

to use close() methods in finally block explicitly,so that it is not required to use "finally" block in try-
catch-finally syntax.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Synatx:
try(Resource1;Resource2;........Resource-n){
-------
------
}
catch(Exception e){
-----
-----
}

Where all the specified Resources classes or interfaces must implement "java.io.AutoCloseable"
interface.

Where if we declare resources as AutoCloseable resources along with "try" then the resources
reference variables are converted as "final" variables.

EX:
try(File f=new File("abc.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Connection con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");)
{
-------
-------
}
catch(Exception e){
e.printStackTrace();
}

NOTE:In Java,all the predefined Stream classes,File class,Connection interface are


extends/implemented "java.io.AutoCloseable" interface predefinedly.

300
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Multi Threadding
Q)What is the difference between Process, Procedure and Processor?

Ans:
process is a flow of execution to perform a particular task.

Procedure is a set of instructions to represent a particular task.

Processor is an H/W component to generate no of processes inorder to execute applications.

At starting point of the computers we have Single Process Mechanism or Single Tasking to execute
applications.

In Single Process Mechanism, System is able to allow only one task at a time to load into the memory
even our system main memory is capable to manage all the tasks.

In Single Process mechanism, System is able to allow only one process to execute all the tasks which
are available in our application, it will follow sequenetial kind of execution , it will increase
application execution time and it will reduce application performance.

To overcome the above problems we have to use Multi Process Mechanim or multi tasking.IN Multi
tasking system is able to allow to load more than one task at a time in main memory and it able to
allow more than one process to execute application, it will follow parallel execution , it will reduce
application execution time and it will improve application performance.

To execute applications by using Multi Tasking or Multi Process Mechanism we have to use the
following components.

1.Main Memory: To load all the tasks.


2.Process Waiting Queue: To keep track of all process
3.Process Context Block: to manage status of all the processes execution.
4.Process Schedular: It will take process from Process Waiting Queue and it will assign time
stamps to each and every process inorder to execute.
301
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above multi processing system, controlling is swiched from one process contex to another
process context called as "Context Switching".
There are two types of Context Switchings.

1.Heavy Weight Context Switching:


It is the context switching between two heavy weight components, it will take more memory and more
execution time , it will reduce application performance.

EX: Cotext switching between two Processes.

2.Light Weight Context Switching:


It is the context switching between two light weight components, it will take less memory and less
execution time and it will improve application performance.
EX: Context switching between two threads.

Q)What is the difference between Process and Thread?

Ans:
Process is heavy weight , to handle it System has to consume more memory and more execution time,
it will reduce application performance.

Thread is light weight, to handle it system has to consume less memory and less execution time, it will
improve application performance.

There are two thread models to execute applications.


1.Single Thread Model
2.Multi Thread Model

1.Single Thread Model:


It will allow only one thread to execute application, it will follow sequential exexcution, it will
increase application execution time and it will reduce application performance.

2.Multi Thread Model:


It will allow more than one thread to execute application, it will follow parallel execution , it will
reduce application execution time and it will improve application performance.

Java is following Multi Thread Model to execute applications and it will provide very good
environment to create and execute more than one thared at a time.

In java applications, to create Threads JAVA has provided the following predefined library in the
302

form of java.lang package.


Page

Q)What is thread and in how many ways we are able to create threads in java?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
Thread is a flow of execution to perfrom a particulaer task.
As per the predefined library provided by JAVA , there are two ways to create threads in java
applications.

1.Extending Thread class:


In this approach , we have to declarre a class , it must be extended from java.lang.Thread class.

class MyThread extends Thread


{
--implementation----
}

2.Implementing Runnable interface:


In this approach, we have to declare a class, it mus implement java.lang.Runnable interface.

class MyThread implements Runnable


{
---implementation----
}

Threads Design in Java:


There are two approaches to create threads in java applications.
a)Extending Thread class
b)Implementing Runnable interface

a)Extending Thread class


1)Declare an user defined class.
2)Extend java.lang.Thread class to user defined class
3)Override Thread class run() method in user defined thread class with the implementation
repersenting a particular task which we want to perfrom by creating a thread.
4)In main class, in main() method, create object for user defined class.

303
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5)Acess Thread class provided start() method on user defined thread class object reference variable.

The main intention of start() method is to create new thread and to access run() method by passing the
generated thread.

public void start()

EX:

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("User Thread :"+i);
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
mt.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread :"+i);
}
}
}

304
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)In java applications, to create threads we have already first approach[Extending thread class] then
what is the requirement to go for Second Approach[ implementing Runnable interface]?

Ans:
In java applications, to create threads if we use first approach then we have to declare an user defined
class and it must be extended from java.lang.Thread class, in this context, it is not possible to extend
other classes , if we extend any other class like Frame,.. along with Thread class then it will represent
Multiple Inheritance, it is not possible in java .

class MyClass extends Frame, Thread{


---
}

To overcome the above problem, we have to use second approach to create thread , that is,
implementing Runnable interface.

class MyClass extends Frame implements Runnable{


----
}

2)Implementing Runnable interface:


a)Declare an user defined class.
b)Implement java.lang.Runnable interface.
c)Provide implementation part in run() method which we want to execute by creating a thread.
d)In main class, in main() method, create a thread and access user defined thread class run()
method.
To perform the above step we have to use the following cases.
class MyThread implements Runnable{
public void run(){
---
}
}

case-1:
MyThread mt=new MyThread();
mt.start();

Status: Compilation Error.

Reason: start() method was not declared in MyThread class and in its super class java.lang.Object
305

class,
start() method is existed in java.lang.Thread class.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Case-2:
MyThread mt=new MyThread();
mt.run();

Status: No Compilation Error, but, only Main thread access MyThread class run() method like a
normal java method, no multi threadding environment.

Case-3:
MyThread mt=new MyThread();
Thread t=new Thread();
t.start();

Status: No Compilation Error, start() method creates new thread and it access Thread class run()
method, not MyThread class run() method.

Case-4:
MyThread mt=new MyThread();
Thread t=new Thread(mt);
t.start();

Status: No Compilation Error, start() method creates new thread and it will bypass new thread to
MyThread class run() method.

Thread Lifecycle:
The collective information of a thread right from its starting point to ending point is called as "Thread
Life Cycle".

In java applications, Threads are able to have the following states as part of their lifecycle.

1.New/Born State:
When we create Thread class object in java applications then Thread will come to New/Born state.

2.Ready/Runnable State:
When we access start() method Thread Schedular has to assign system resources like memory and
time, here before assigninig system resources and after calling start() method is called as
Ready/Runnable state.

3.Running State:
In java applications, after calling start() method and after getting system resources like memory and
execution time is called as "Running State".
306
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: We can send a thread from Running state to Runnable state directly by accessing yield()
method , but, it is not supported by Windows operating system, because, it will peform its functinoality
on the basis of Threads priority values, priority based operations are not supported by windows
operating system.

4.Dead/Destroy State:
In java applications, when we access stop() method over Running thread then that thread will come
to Dead/Destroy state.

5.Blocked State:
In java applications, we are able to keep a thread in Blocked state from Running state in the
following situations.
a)When we access sleep(--) method with a particular sleep time.
b)When we access wait() method.
c)When we access suspend() method.
d)When we perform IO Operations.

In java applications, we are able to bring a thread from Blocked state to Ready / Runnable state in the
following situations.
a)When sleep time is over.
b)If any other thread access notify() / notifyAll() methods.
c)If any other thread access resume() method.
d)When IO Operations are completed.

Thread class Library:

Consrtuctors:
1.public Thread()
--> This constructor can be used to create thread class object with the following properties.

Thread Name: Thread-0


Thread Priority: 5
Thread group Name : main

EX: Thread t=new Thread();


System.out.println(t);

OP: Thread[Thread-0, 5, main]


307
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.public Thread(String name)
-->This constructor can be used to create Thread class object with the specified name.

EX: Thread t=new Thread("Core Java");


System.out.println(t);

OP: Thread[Core Java,5,main]

3.public Thread(Runnable r)
-->This constructor can be used to create Thread class object with the specified Runnable reference.

EX: Runnable r=new Thread();


Thread t=new Thread(r);
System.out.println(t);

OP: Thread[Thread-1,5,main]

4.public Thread(Runnable r, String name)


-->This constructor can be used to create Thread class object with the specified Runnable reference
and with the specified name.

EX: Runnable r=new Thread();


Thread t=new Thread(r, "Core Java");
System.out.println(t);

OP: Thread[Core Java,5,main]

5.public Thread(ThreadGroup tg, Runnable r)


--> This constuctor can be used to create Thread class object with the specified ThreadGroup name and
with the specified thread name.

NOTE: To provide ThreadGroup name we have to use a predefined class like java.lang.ThreadGroup,
to create ThreadGroup class object we have to use the following Constructor.

public ThreadGroup(String name)

EX:ThreadGroup tg=new ThreadGroup("Java");


Runnable r=new Thread();
Thread t=new Thread(tg, r)
System.out.println(t);
308

OP: Thread[Thread-1,5,Java]
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6.public Thread(ThreadGroup tg, String name)
-->This constructor can be used to create Thread class object with the specified ThreadGroup name
and with the specified Thread name.

EX: ThreadGroup tg=new ThreadGroup("Java");


Thread t=new Thread(tg, "Core Java");
System.out.println(t);

OP:Thread[Core Java,5,Java]

7.public Thread(ThreadGroup tg, Runnable r, String name)


--> This constuctor constuctor can be used to create Thread class object with the specified
ThreadGroup name, with the Runnable reference and with the thread name.

EX: ThreadGroup tg=new ThreadGroup("Java");


Runnable r=new Thread();
Thread t=new Thread(tg, r, "Core Java");

OP: Thread[Core Java, 5, Java]

Methods:
1.public void setName(String name)
-->It can be used to sett a particular name to the Thread explicitly.

2.public String getName()


-->It can be used to get thread name explicitly.

EX: class Test


{
public static void main(String[] args)
{
Thread t=new Thread();
System.out.println(t.getName());
t.setName("Core Java");
System.out.println(t.getName());
}
}
309
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.public void setPriority(int priority)
-->It can be used to set a particular priority value to the Thread, but, here the priority value must be
provided in the range from 1 to 10, if we provide any other value then JVM will rise an exception
like java.lang.IllegalArgumentException.

To represent Thread priority values, java.lang.Thread class has provided the following constants.

public static final int MIN_PRIORITY=1;


public static final int NORM_PRIORITY=5;
public static final int MAX_PRIORITY=10;

4.public int getPriority()


-->It can be used to get priority value of the Thread.

EX:
class Test
{
public static void main(String[] args)
{
Thread t=new Thread();
System.out.println(t.getPriority());
t.setPriority(7);
System.out.println(t.getPriority());
t.setPriority(Thread.MAX_PRIORITY-2);
System.out.println(t.getPriority());
//t.setPriority(15);-->IllegalArgumentException
}
}

5.public static int activeCount()


--> It will return the no of threads which are in active.

EX:
class Test
{
public static void main(String[] args)
{
Thread t=new Thread();
t.start();
System.out.println(Thread.activeCount());
310

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6.public boolean isAlive()
--> This method can be used to check whether a thread is in live or not.
EX: class Test
{
public static void main(String[] args)
{
Thread t=new Thread();
System.out.println(t.isAlive());
t.start();
System.out.println(t.isAlive());
}
}

7.public static thread currentThread()


--> It can be used to get Thread object reference which is in active at present.
EX: class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName());
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread mt1=new MyThread();
MyThread mt2=new MyThread();
MyThread mt3=new MyThread();

mt1.setName("AAA");
mt2.setName("BBB");
mt3.setName("CCC");

mt1.start();
mt2.start();
mt3.start();
311

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


8.public static void sleep(long time)throws InterruptedException
--> This method can be used to keep a running thread into sleeping state upto the specified sleep
time.
In general, we will use sleep() method in run() method of user defined thread class, where to handle
InterruptedException we must use try-catch-finally syntax only, we must not use "throws" keyword in
run() method prototype, because, we are overriding Thread class or Runnable interface predefined
run() method.

9.public void join()throws InterruptedException


-->This method will pause a thread to complete a thread on which we accessed join() method , after
completion of the respective thread, paused thread will continue its execution part automatically.

Daemon Threads
These threads are running internally to provided services to some other thread and it will be terminated
along with the threads which are taking services.

To make a thread as daemon thread we have to use the following method.

public void setDaemon(boolean b)


--> If 'b' value is true then thread will be daemo thread.
--> If 'b' value is false then thread will not be daemon thread.

EX: mt.setDaemon(true);

To check whether a thread is daemon thread or not we have to use the following method.

public boolean isDaemon()

EX: In Java, Garbage Collector is a thread running internally inside JVM and it will provide Garbage
Collection services to JVM and it will be terminated along with JVM automatically.

Synchronization:
In java applications, if we execute more than one thraed on a single data item then there may be a
chance to get data inconsistency, it may generate wrong results in java applications.

IN java applications, to provide data consistency in the above situation we have to use
"Synchronization".

"Synchronization" is a mechanism , it able to allow only one thread at a time , it will not allow more
than one at a time, it able to allow other threads after completion of the present thread.
312
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In java applicatinos, synchronization is going on the basis of Locking mechanisms, If we send
multiple threads at a time to synchroized area then Lock Manager will assign lock to a thread which
is having highest priority, once a thread gets loc from Lock manager then that thread is eligible to
enter in synchronized area, once a thread is available in synchronized area then Lock Manager will
not assign lock to other threads, when Thread completes its execution in synchronized area then that
thread has to submit lock back to Lock Manager, once Lock is given back to Lock manager then
Lock Manager will assign that lock to another thread which is having next priority.

In java applications, to ptovide synchronization JAVA has provided a keyword in the form of
"synchronized".

In java applications, we are able to achieve "synchronization" in the following two ways.

1.synchronized method
2.synchronized block

1.synchronized method:
It is a normal java method, it willallow only one thread at a time to execute instructions, it will not
allow more than one thread at a time, it will allow other threads after completion of the present
thread execution.

EX:
class A
{
synchronized void m1()
{
for(int i=0;i<10;i++)
{
String thread_Name=Thread.currentThread().getName();
System.out.println(thread_Name);
}
}
}
class MyThread1 extends Thread
{
A a;
MyThread1(A a)
{
this.a=a;
}
313

public void run()


{
Page

a.m1();
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
class MyThread2 extends Thread
{
A a;
MyThread2(A a)
{
this.a=a;
}
public void run()
{
a.m1();
}
}
class MyThread3 extends Thread
{
A a;
MyThread3(A a)
{
this.a=a;
}
public void run()
{
a.m1();
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
MyThread1 mt1=new MyThread1(a);
MyThread2 mt2=new MyThread2(a);
MyThread3 mt3=new MyThread3(a);

mt1.setName("AAA");
mt2.setName("BBB");
mt3.setName("CCC");

mt1.start();
mt2.start();
314

mt3.start();
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)In java applications, we have already synchronized methods to achieve synchronization then what is
the requirement to use synchronized block?

Ans:
In java applications, if we use synchronized method to achieve synchronization then it will provide
synchronization through out the method irrespective of the actual requirment.If we need
synchronization upto a block inside the synchronized method then it will provide unneccessary
sychronization fpor the remianing part of the method, it will increase execution time and it will
reduuce application performance.

In the above context, to provide synchronization upto the required part then we have to use
synchronized block.

Synchronized block:
It is a set of instructions, it able to allow only one thread at a time to execute instructions, it will not
allow more than one thread at a time, it will allow other threads after completion of the present thread
execution.

Syntax:
synchronized(Object o)
{
-----
-----
}

EX:
class A
{
void m1()
{
String thread_Name=Thread.currentThread().getName();
System.out.println("Before Synchronized Block :"+thread_Name);
synchronized(this)
{
for(int i=0;i<10;i++)
{
String thread_Name1=Thread.currentThread().getName();
System.out.println("Inside Synchronized Block :"+thread_Name1);
}
}
315

}
}
Page

class MyThread1 extends Thread


{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


A a;
MyThread1(A a)
{
this.a=a;
}
public void run()
{
a.m1();
}
}
class MyThread2 extends Thread
{
A a;
MyThread2(A a)
{
this.a=a;
}
public void run()
{
a.m1();
}
}
class MyThread3 extends Thread
{
A a;
MyThread3(A a)
{
this.a=a;
}
public void run()
{
a.m1();
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
MyThread1 mt1=new MyThread1(a);
316

MyThread2 mt2=new MyThread2(a);


MyThread3 mt3=new MyThread3(a);
Page

mt1.setName("AAA");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


mt2.setName("BBB");
mt3.setName("CCC");

mt1.start();
mt2.start();
mt3.start();
}
}

Inter thread Communication:


The process of providing communication between more than one thread is called as " Inter Thread
Communication".

To perform Inter Thread Communication we have to use the following methods.

1.wait()
2.notify()
3.notifyAll()

Where wait() method can be used to keep a thread in waiting state.

Where notify() method can be used to give a notification to a thread which is available in waiting state.

Where notifyAll() method can be used to give a notification to all the threads which are available i
waiting state.

The above methods are provided by JAVA in java.lang.Object class.

If we want to use these methods in java applications then we must provide "Synchronization".

IN general, Inter Thread Communication will provide solutions for the problems like "Producer-
Consumer" problems.

In Propducer-Consumer problem, producer and cosumer are two threads, where producer has to
produce an item and consumer has to consume that item, the same sequence has to be provided infinite
no of times, where Producer must not produce an item with out consuming previous item by consumer
and consumer must not consume an item with out producing that item by producer.
317
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
boolean flag=true;
int count=0;
public synchronized void produce()
{
try
{
while(true)
{
if(flag == true)
{
count=count+1;
System.out.println("Producer Produced Item"+count);
flag=false;
notify();
wait();
}
else
{
wait();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public synchronized void consume()
{
try
{
while(true)
{
if(flag == true)
{
wait();
}
318

else
{
Page

System.out.println("Consumer Consumed Item"+count);


flag=true;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


notify();
wait();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class Producer extends Thread
{
A a;
Producer(A a)
{
this.a=a;
}
public void run()
{
a.produce();
}
}
class Consumer extends Thread
{
A a;
Consumer(A a)
{
this.a=a;
}
public void run()
{
a.consume();
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
319

Producer p=new Producer(a);


Consumer c=new Consumer(a);
Page

p.start();
c.start();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}

Dead Lock:
Dead Lock is a situation , where more than one thread is depending on each other in circular
dependency.
In java applications, once we are getting deadlock then program will struct in the middle, so that, it
will not have any recovery mechanisms, it will have only prevention mechanisms.

EX:

class Register_Course extends Thread


{
Object course_Name;
Object faculty_Name;
Register_Course(Object course_Name, Object faculty_Name)
{
this.course_Name=course_Name;
this.faculty_Name=faculty_Name;
}
public void run()
{
synchronized(course_Name)
{
System.out.println("Register_Course Thread holds course_Name resource
and waiting for faculty_Name resource.....");
synchronized(faculty_Name)
{
System.out.println("Register_Course is success, because,
Register_Course thread holds both course_Name and faculty_Name resources");
}
}
}
}
class Cancel_Course extends Thread
{
Object course_Name;
Object faculty_Name;
Cancel_Course(Object course_Name, Object faculty_Name)
{
320

this.course_Name=course_Name;
this.faculty_Name=faculty_Name;
Page

}
public void run()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
synchronized(faculty_Name)
{
System.out.println("Cancel_Course Thread holds faculty_Name resource
and waiting for course_Name resource.....");
synchronized(course_Name)
{
System.out.println("Cancel_Course is success, because,
Cancel_Course thread holds both faculty_Name and course_Name resources");
}
}
}
}

class Test
{
public static void main(String[] args)
{
Object course_Name=new Object();
Object faculty_Name=new Object();
Register_Course rc=new Register_Course(course_Name, faculty_Name);
Cancel_Course cc=new Cancel_Course(course_Name, faculty_Name);
rc.start();
cc.start();
}
}

321
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


IOStreams
In any programming language,in any application,providing input to the Applications and getting output
from the Applications is essential.

In case of C and C++ applications,we are able to perform input and output operations by using some
predefined library in the form of printf(),scanf(),cin>>,cout<<,......

Similarly in Java Applications,to perform input and output operations we have to use streams.

Java has represented all the streams in the form of predefined classes in "java.io" package.

Stream:
Stream is medium or channel,it will allow the data in continuous flow from input devices to java
program and from Java program to output devices
.
In Java IOStreams are divided into following ways:
1.Byte oriented Streams.
2.Character-Oriented Streams

1.Byte-Oriented Streams:
These are Streams, which will allow the data in the form of bytes from input devices to Java
program and from java program to output devices.
The length of the data in byte-oriented streams is 1 byte.

There are two types of Byte-Oriented Streams

1.InputStream
2.OutputStream

1.InputStream:
It is a byte-oriented Stream,it will allow data in the form of bytes from input devices to Java
Applications.

EX:
ByteArrayInputStream
FilterInputStream
DataInputStream
ObjectInputStream
322

FileInputStream
StringBufferInputStream
BufferedInputStream….
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.OutputStream:
It is a byte-oriented Stream,it will allow the data in the form of bytes from Java applications to
output devices.

EX:
ByteArrayOutputStream
FilterOutputStream
DataOutputStream
FileOutputStream
PrintStream
BufferedOutputStream..

NOTE: All the ByteOrientedStream classes are terminated with "Stream" word.
NOTE: The length of data items in Byte Oriented Streams is 1 byte.

2.Character-Oriented Streams:
These are the Streams,which will allow the data in the form of characters from input devices to java
program and form java program to output devices.

There are two bytes of character-oriented streams


1.Reader
2.Writer
1.Reader:
It is a character-oriented stream,it will allow the data in the form of characters from input devices to
java program.
EX:
CharArrayReader
FilterReader
BufferedReader
FileReader
InputStreamReader….

2.Writer:
It is a character-oriented stream,it will allow the data in the form of characters from java program to
output devices.

EX:
CharArrayWriter
FilterWriter
FileWriter
323

PrintWriter
BufferedWriter….
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE:All the predefined Classes of character-oriented streams are terminated with either Reader or
Writer.

NOTE: The length of the data in characters-oriented stream is 2 bytes.

FileOutPutStream:
It is byte-oriented Stream,it can be used to transfer the data from Java program to a particular target
file.
To transfer the data from Java program to a particular target file by using FileOutPutstream we have
to use the following Steps.

1.Create FileOutPutStream between Java programme and target file:


If we want to create FileOutPutStream class object then we have to use the following constructors
public FileOutPutStream(String target_File)
public FileOutPutStream(String target_File,boolean b)

EX:
FileOutPutStream fos=new FileOutPutStream("abc.txt");
-->It will override the existed data in the target file at each and every write operation.
FileOutPutStream fos=new FileOutPutStream("abc.txt",true);
-->It will not override the existed data in the target file,it will append the specified new data to
the existed data in the target file.
When JVM encounter the above instruction,JVM will perform the following tasks.
a)JVM will take the specified target file.
b)JVM will search for the specified target file at the respective location.
c)If the specified target file is available then JVM will establish FileOutPutStream from java
program to target file.
d)If the specified target file is not available then JVM will create a file with the target file name and
establish FileOutPutStream from Java program to target file.

2)Declare the data and convert into byte[]:


String data="Hello";
byte[] b=data.getBytes();
3)Write Byte Array data into FileOutPutStream:
To write byte[] data into FileOutPutStream,we have to use the following method.
public void write(byte[] b) throws IOException

EX:
fos.write(b);
4)Close FileOutPutStream:
324

fos.close();
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.FileInputStream:
It is a byte-oriented Stream,it can be used to transfer the data from a particular source file to Java
Program.
If we want to transfer the data from source file to java programme by using FileInputStream,we have
to use the following Steps:
1.Create FileInputStream class Object:
To create FileInputStream class object,we have to use the following constructor from
java.io.FileInputStream class.
public FileInputStream(String file_name) throws FileNotFoundException

EX:
FileInputStream fis=new FileInputStream("abc.txt");
When JVM encounter the above instruction then JVM will perform the following actions.
1.JVM will take the specified source file name.
2.JVM will search for the specified source file at the respective location.
3.If the source file is not available at the respective location then JVM will raise an excpetion
like "java.io.FileNotFoundException".
4.If the required source file is available then JVM will establish FileInputStream from source file
to JAVA program.
5.After creating FileInputStream,JVM will transfer the data from source file to FileInputStream
in the form bytes.
2.Get the size of the data from FileInputStream and prepare byte[] with the data size:
To get the size of the data from FileInputStream,we have to use the following method
public int available()

EX:
int size=fis.available();
byte[] b=new byte[size];
3.Read the data from FileInputStream into byte[]:
To read the data from FileInputStream into byte[],we have to use the following method.
public void read(byte[] b)throws IOException

EX:
fis.read(b);
4.Convert data from byte[] to String:
String data=new String(b);
System.out.println(data);
5.close FileInputStream:
fis.close();
325
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Write a Java program to display a particular file content on command prompt by taking filename as
command line input?

import java.io.*;
class DisplayEx{
public static void main(String args[]) throws Exception{
String file_Name=args[0];
FileInputStream fis=new FileInputStream(file_Name);
int size=fis.available();
byte b[]=new byte[size];
fis.read();
String data=new String(b);
System.out.println(data);
fis.close();
}
}

Write a Java program to count no of words available in a particular text file and how many times the
word "Durga" is repeated?

import java.io.*;
import java.util.*;
class Word_Count_Ex{
public static void main(String args[]) throws Exception{
FileInputStream fis=new FileInputStream("abc.txt");
int size=fis.available();
byte b[]=new byte[size];
fis.read();
String data=new String(b);
StringTokenizer st=new StringTokenizer(data);
int tokens=st.countTokens();
System.out.println("No of words :"+tokens);
int count=0;
while(st.hasMoreTokens()){
String token=st.nextToken();
if(token.equals("Durga")){
count=count+1;
}
}
System.out.println("'Durga' is repeated :"+count);
326

fis.close();
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Write a Java program to copy an image from a source file to a particular target file?
import java.io.*;
public class Image_Copy_Ex{
public static void main(String args[]){
FileInputStream fis=new FileInputStream();
int size=fis.available();
byte[] b=new byte[size];
fis.read(b);
FileOutPutStream fos=new FileOutPutStream("abc.jpg");
fos.write(b);
fis.close();
fos.close();
}
}

FileWriter:
This character-oriented Stream can be used to transfer the data from Java Application to a particular
target File.
If we want to transfer the data from java application to a particular target file by using FileWriter
then we have to use the following steps:
1.Create FileWriter object:
To create FileWriter class object,we have to use the following constructor.
public FileWriter(String target_File)

EX: FileWriter fw=new FileWriter("abc.txt");


-->It will override the existed content with the new content at each and every write operation.
public FileWriter(String target_File,boolean b)

EX: FileWriter fw=new FileWriter("abc.txt",true);


-->It will append new content to the existed content available in the file at each and every write
operation.
When JVM encounter the above instructions,JVM will take the specified file and JVM search for
the specified file at the respective location,if the required target file is available then JVM will
establish FileWriter from Java application
to the target file.If the required target file is not available at the respective location then JVM
will create a new file with the same specified file name and establish FileWriter from Java
application to the target file.
2.Declare the data which we want to transfer and convert that data into char[]:
String data="Hello";
char[] ch=data.toCharArray();
327

3.Write char[] data into FileWriter:


To write char[] data into FileWriter,we have to use the following method.
Page

public void write(char[] ch)throws IOException

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: fw.write(ch);
4.Close FileWriter:
fw.close();

EX:
import java.util.*;
public class FileWriterEx{
public static void main(String args[])throws Exception{
FileWriter fw=new FileWriter("abc.txt",true);
String data="DurgaSoftwareSolutions";
char[] ch=data.toCharArray();
fw.write(ch);
fw.close();
}
}

FileReader:
This character-oriented stream can be used to transfer the data from a particular source file to Java
program.
If we want to transfer the data from a particular source file to Java program by using FileReader
then we have to use the following steps:
1.Create FileReader class Object:
To create FileReader class object,we have to use the following constructor.
public FileReader(String file_Name)throws FileNotFoundException

EX:
FileReader fr=new FileReader("abc.txt");
when JVM encounter the above instruction,JVM will perform the following steps.
a)JVM will take source file name from FileReader constructor.
b)JVM will check whether the specified file is available or not at the respective location.
c)If the specified source file is not available at the respective location then JVM will rise an
exception like "java.io.FileNotFoundException".
d)If the specified file is existed at the respective location then JVM will establish FileReader
from source file to Java program.
e)After creating FileReader,JVM will transfer the content of source file to FileReader object in
the form of characters.
2.Read data from FileReader:
To read data from FileReader,we have to use the following steps.
a)Read character by character from FileReader in the form of ASCII values.
b)Convert that ASCII values into the respective characters.
328

c)Append the converted characters to a String variable.


Repeat the above steps upto all the characters which are available in the respective source file or
Page

upto the end-of-file character i.e "-1".


To read an ASCII value from FileReader,we have to use the following method.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public int read() throws IOException
3.Close FileReader:
fr.close();

EX:
import java.util.*;
public class FREx{
public static void main(String args[])throws Exception{
FileWriter fr=new FileWriter("abc.txt");
String data="";
int val=fr.read();
while(val!=-1){
data=data+(char)val;
val=fr.read();
}
System.out.println(data);
fr.close();
}
}

Write a JAVA programme to copy a document from one file to another file by using character
oriented Streams?
import java.io.*;
public class FileCopyEx{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("hibernatecgf.xml");
String data="";
int val=fr.read();
while(val!=-1){
data=data+(char)val;
val=fr.read();
}
char[] ch=data.toCharArray();
FileWriter fw=new FileWriter("abc.xml");
fw.write(ch);
fr.close();
fw.close();
}
}
329
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Approaches to provide dynamic input:
There are three approaches to provide dynamic input in java applications.
1.BufferedReader
2.Scanner
3.Console

1.BufferedReader:
If we want to take dynamic input by using BufferedReader in java applications then we have to use
the following statement.

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

where "in" is static variable,it will refer a predefined "InputStream" object which is connected with
command prompt.
If we provide data on command prompt then that data will be transfered to InputStream object in
the form of binary data.

where "InputStreamReader can be used to convert the data from binary representation to character
representation.

where BufferedReader can be used to improve the performance of Java application while
performing input operation.

To read the data from BufferedReader,we will use the following method
1.readLine()
2.read()

Q)What is the difference between readLine() method and read() method?

Ans:
readLine() method will read a line of text from command prompt[BufferedReader] and it will return
that data in the form of String.

public String readLine() throws IOException

read() method will read a single character from command prompt[BufferedReader] and it will return
that character in the form of its ASCII value.

public int read()throws IOException


330
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.io.*;
public class BufferedReaderEx{
public static void main(String args[])throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Text :");
String data1=br.readLine();
System.out.println("Enter the same text again :");
int data2=br.read();
System.out.println("First Entered :"+data1);
System.out.println("Second Entered :"+data2+"--->"+(char)data2);
}
}

Consider the following programme:


import java.io.*;
public class BufferedReaderEx{
public static void main(String args[])throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("First value :");
String val1=br.readLine();
System.out.println("Second value :");
String val2=br.readLine();
System.out.println("Addition :"+val1+val2);
}
}

If we provide 10 and 20 as dynamic input to the above programme then the above programme will
display "1020" value instead of 30 that is the above programme has performed String concatenation
instead of performing Arithmetic Addition because br.readLine() method has return 10 and 20 values
in the form String data.

In the above programme,if we want to perform Arithmetic operations over dynamic input then we have
to convert String data into the respective primitive data,for this we have to use Wrapper Classes.

ThereFore,BufferedReader dynamic input approach is depending on wrapper classes while reading


primitive data as dynamic input.
331
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.io.*;
public class BufferedReaderEx{
public static void main(String args[])throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("First value :");
String val1=br.readLine();
System.out.println("Second value :");
String val2=br.readLine();
int f_Val=Integer.parseInt(val1);
int s_Val=Integer.parseInt(val2);
System.out.println("Addition :"+(f_Val+s_Val));
}
}

Scanner:
This class is provided by Java in java.util package along with JDK5.0 Version.
In java applications, if we use BufferedReader to dynamic input then we must use wrapper classes
while reading primitive data as dynamic Input.
In java applications, if we use "Scanner" to read dynamic input then it is not required to use
wrapper classes while reading primitive data as dynamic input, scanner is able to provide
environment to read primitive data directly from command prompt.

If we want to use scanner in Java applications then we have to use the following steps.

1.Create Scanner class Object:


To create Scanner class Object,we have to use the following constructor
public Scanner(InputStream is)

EX: Scanner s=new Scanner(System.in);

2.Read dynamic Input:


To read String data as Dynamic input,we have to use the following method.
public String next()
To read primitive data as Dynamic input,we have to use the following method.

public xxx nextXXX()


where xxx may be byte,short,int,float...............
332
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
public class ScannerEx
{
public static void main(String[] args)throws Exception
{
Scanner s=new Scanner(System.in);
System.out.print("Employee Number :");
int eno=s.nextInt();
System.out.print("Employee Name :");
String ename=s.next();
System.out.print("Employee Salary :");
float esal=s.nextFloat();
System.out.print("Employee Address :");
String eaddr=s.next();

System.out.println("Employee Details");
System.out.println("---------------------");
System.out.println("Employee Number :"+eno);
System.out.println("Employee Name :"+ename);
System.out.println("Employee Salary :"+esal);
System.out.println("Employee Address :"+eaddr);
}
}
EX:
import java.util.*;
public class ScannerEx1
{
public static void main(String[] args)throws Exception
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Text Data :");
String data1=s.nextLine();
System.out.print("Enter The same text data again :");
String data2=s.next();
System.out.println("First Entered :"+data1);
System.out.print("Second Entered :"+data2);

}
}
333
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Console:
This class is provided by Java in java.io package along with JAVA6 Version.

In Java applications,to take dynamic input,if we use BufferedReader and Scanner then we are able to
get the following drawbacks:

1.We have to consume 2 instructions for each and every dynamic input[s.o.pln(..) and readLine() or
nextXXX() methods]

2.These are not providing security for the data like password data,pin numbers.....

To overcome the above problems,we have to use "Console" dynamic input approach.

If we want to use Console in Java applications then we have to use the following Steps:

1.Create Console object:


To get Console object,we have to use the following method from "System" class.
public static Console console()

EX:
Console c=System.console();
2.Read dynamic Input:
To read String data,we have to use the following method.
public String readLine(String msg)
To read password data,we have to use the following method.
public char[] readPassword(String msg)

EX:
import java.io.*;
public class ConsoleEx{
public static void main(String args[])throws Exception{
Console c=System.console();
String uname=c.readLine("User Name :");
char[] pwd=c.readPassword("PassWord :");
String upwd=new String(pwd);
if(uname.equals("durga")&&upwd.equals("durga")){
System.out.println("Valid User");
}
else{
System.out.println("InValid User");
334

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Serialization and Deserialization:
If we design Java applications by distributing application logic over multiple [JVMS] then that Java
application is called as Distributed Application.

In general, in Distributed applications, it is frequent requirement to transfer an object [Distributed


Object] from one machine to another machine.

In Java, Object is a block of memory, it is not possible to transfer the object through network, where
we have to transfer object data from one machine to another machine through network.

To transfer an Object through network from one machine to another machine, first we have to
separate the data from an object at local machine and convert the data from system representation to
network representation then transfer the data to network.

At remote machine, we have to get the data from network and convert the data from system
representation to System representation and reconstruct an object on the basis of data.
----Diagram--------------

The process of converting the data from System representation to network representation is called
as "Marshalling".

The process of converting the data from Network representation to System representation is called
as "UnMarshalling".

The Process of separating the data from an Object is called as "Serialization".

The process of reconstructing an object on the basis of data is called as "Deserialization".

To perform Serialization and Deserialization in Java applications, JAVA has given two predefined
byte-oriented streams like java.io.ObjectOutputStream for Serialization java.io.ObjectInputStream
for Deserialization

In Standalone applications,if we want to perform Serialization and Deserialization over an object


then we have to take a file[text file] to store serialized data.
335
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Steps to Perform Serialization:
1.Create Serializable Object:
To create Serializable Object we have to implement java.io.Serializable marker interface to the
respective class.
Serializable interface is marker interface,it will make eligible any object for Serialization and
Deserialization.

EX:
class Employee implements Serializable{
int eno=111;
String ename="AAA";
float esal=5000;
}
Employee e1=new Employee();

2.Prepare FileOutPutStream with a particular target File:


FileOutPutStream fos=new FileOutPutStream("abc.txt");

3.Create ObjectOutPutStream:
To create ObjectoutputStream,we have to use the following constructor.
public ObjectOutputStream(FileOutputStream fos)

EX:
ObjectOutputStream oos=new ObjectOutputStream(fos);
4.Write Serializable object to ObjectOutputStream:
To write Serializable object to ObjectOutputStream,we have to use the following method.
public void writeObject(Object obj)throws NotSerializableException

EX: oos.writeObject(e1);

Steps To perform DeSerialization:

1.Create FileInputStream object:


FileInputStream fis=new FileInputStream("emp.txt");

2.Create ObjectInputStream:
To create ObjectInputStream class object,we have to use the Following constructor.
public ObjectInputStream(FileInputStream fis)
336
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: ObjectInputStream ois=new ObjectInputStream(fis);
3.Read DeSerialized Data from ObjectInputStream:
To read DeSerialized object from ObjectInputStream,we have to use the following method.
public Object readObject()

EX: Employee e2=(Employee)ois.readObject();

EX: import java.io.*;


class Employee implements Serializable
{
int eno;
String ename;
float esal;
String eaddr;

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


{
this.eno=eno;
this.ename=ename;
this.esal=esal;
this.eaddr=eaddr;
}

public void getEmpDetails()


{
System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number :"+eno);
System.out.println("Employee Name :"+ename);
System.out.println("Employeed Salary :"+esal);
System.out.println("Employee Address :"+eaddr);
}
}
class SerializationEx
{
public static void main(String[] args)throws Exception
{
FileOutputStream fos=new FileOutputStream("emp.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Employee emp1=new Employee(111, "Durga", 50000, "Hyd");
337

System.out.println("Employee Details before Serialization");


emp1.getEmpDetails();
Page

oos.writeObject(emp1);
System.out.println();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


FileInputStream fis=new FileInputStream("emp.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Employee emp2=(Employee)ois.readObject();
System.out.println("Employee Details After Deserialization");
emp2.getEmpDetails();
}
}

-->In Object serialization, static members are not allowed.


-->If we serialize any object having static variables then compiler will not rise any error and JVM will
not rise any exception but static variables will not be listed in the serialized data in the text file.
-->In object serialization,if we do not want to allow any variable in serialization and deserialization
then we have to declare that variable as "transient" variable.
transient int eno=111;

EX: import java.io.*;


class User implements Serializable
{
String uname;
transient String upwd;
String uemail;
long umobile;
public static final int MIN_AGE=18;
public static final int MAX_AGE=25;

User(String uname, String upwd, String uemail, long umobile)


{
this.uname=uname;
this.upwd=upwd;
this.uemail=uemail;
this.umobile=umobile;
}
}
class Test
{
public static void main(String[] args)throws Exception
{
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
User u=new User("abc", "abc123", "abc@duurgasoft.com", 998877);
338

oos.writeObject(u);
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->In Java applications, if we serialize an object which is not implementing java.io.Serializable
interface then JVM will rise an exception like "java.io.NotSerializableException".
import java.io.*;
class A{
int i=10;
int j=20;
}
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
A a=new A();
oos.writeObject(a);
}}

Status:"java.io.NotSerializableException".[Exception]

-->In Java applications, if we implement Serializable interface to the super class then automatically all
the sub class objects are eligible for Serialization and Deserialization.

EX:
import java.io.*;
class A implements Serializable{
int i=10;
int j=20;
}
class B extends A{
int k=30;
int l=40;
}
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
B b=new B();
oos.writeObject(b);
}
}
339
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->In Java applications, if we implement Serializable interface in sub class then only sub class
properties are allowed in Serialization and deserialization, the respective super class members are not
allowed in the Serialization and deserialization.

EX:
import java.io.*;
class A {
int i=10;
int j=20;
}
class B extends A implements Serializable{
int k=30;
int l=40;
}
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
B b=new B();
oos.writeObject(b);
}
}

-->In Java applications,while Serializing an object if any associated object is available then JVM will
serialize the respective associated object also but the respective associated object must implement
Serializable interface otherwise JVM will rise an exception like "java.io.NotSerializableException".

EX:
import java.io.*;
class Branch implements Serializable{
String bid;
String bname;
Branch(String bid,String bname){
this.bid=bid;
this.bname=bname;
}
}
class Account implements Serializable{
String accNo;
String accName;
340

Branch branch;
Account(String accNo,String accName,Branch branch){
Page

this.accNo=accNo;
this.accName=accName;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


this.branch=branch;
}
}
class Employee implements Serializable{
String eid;
String ename;
Account acc;
Employee(String eid,String ename,Account acc){
this.eid=eid;
this.ename=ename;
this.acc=acc;
}
}
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Branch branch=new Branch("B-111","S R Nagar");
Account acc=new Account("abc123","Durga",branch);
Employee emp=new Employee("E-111","Durga",acc);
oos.writeObject(emp);
}
}
Externalization:
As part of object serialization and deserialization we are able to separate the data from Object and
stored in a text file and we are able to retrieve that object data from text file to Object in Java
application.

In Java applications, to perform serialization and deserialization Java has given


"ObjectOutputStream" and "ObjectInputStream" two byte-oriented Streams.

In Java applications, to perform Serialization just we have to send Serializable object to


ObjectOutputStream,it will perform serialization internally, where Developers are not having
controlling over serialization process.

In Java applications, to perform deserialization just we have to create ObjectInputStream and we


have to read deserialized object,where ObjectInputStream will perform deserialization
internally,where developers are not having controlling over deserialization process.

In the above context to have controlling over serialization and deserialization processes inorder to
341

provide the services like security, data compression,data decompression, data encoding.....over
serialized and deserialized data we have to go for "Externalization".
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we want to perform Externalization in java applications,we have to use the following steps.

1)Prepare Externalizable object


2)Perform Serialization and Deserialization over Externalizable object.

1)Prepare Externalizable object:


In Java applications,if we want to create Serializable object then the respective class must
implement java.io.Serializable interface.
Similarly, if we want to prepare Externalizable object then the respective class must implement
java.io.Externalizable interface.
java.io.Externalizable is a sub interface to java.io.Serializable interface.

java.io.Serializable interface is a marker interface, which is not having abstract methods but
java.io.Externalizable interface is not marker interface,which includes the following methods.

public void writeExternal(ObjectOutput oop)throws IOException


public void readExternal(ObjectInput oip)throws IOException,ClassNotFoundException

where writeExternal(--) method will be executed just before performing serialization in


ObjectOutputStream,
where we have to perform manipulations on the data which we want to serialize.

where readExternal(--) method will be executed immediately after performing Deserializationin


ObjectInputStream,where we can perform manipulations over the deserialized data.
where ObjectOutput is stream,it will carry manipulated data for Serialization.

To put data in ObjectOutput,we have to use the following methods.


public void writeXXX(xxx data)
where xxx may be byte,short,int,UTF[String]..........
where ObjectInput will get serialized data from text file to perform manipulations.

To read data from ObjectInput we have to use the following method


public void readXXX(xxx data)
where xxx may be byte,short,int,UTF[String]..........

If we want to prepare Externalizable object we have to use the following steps.


a)Declare an user defined class
b)Implement java.io.Externalizable interface.
c)Implement the methods writeExternal(--) and readExternal(--)
of Externalizable interface at the user defined class.
342

class Employee implements Externalizable{


public void writeExternal(ObjectOutput oop)throws IOException{
Page

---implementation---
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public void readExternal(ObjectInput oip)throws IOException,ClassNotFoundException{
---implementation----
}
}
Employee emp=new Employee();

2.Perform Serialization and Deserialization over Externalizable object by using


ObjectOutputStream and ObjectInputStream:
same as Serialization and DeSerialization

EX:
import java.util.*;
import java.io.*;
class Employee implements Externalizable{
String eid;
String ename;
String email;
String emobile;
//It will be used to construct object while performing deserialization in Externalization process
public Employee(){
}
Employee(String eid,String ename,String email,String emobile){
this.eid=eid;
this.ename=ename;
this.email=email;
this.emobile=emobile;
}
public void writeExternal(ObjectOutput oop)throws IOException{
try{
StringTokenizer st1=new StringTokenizer(eid,"-");
st1.nextToken();
int no=Integer.parseInt(st1.nextToken());
StringTokenizer st2=new StringTokenizer(email,"@");
String mail=st2.nextToken();
StringTokenizer st3=new StringTokenizer(emobile,"-");
st3.nextToken();
String mobile=st3.nextToken();
oop.writeInt(no);
oop.writeUTF(ename);
oop.writeUTF(mail);
343

oop.writeUTF(mobile);
}
Page

catch(Exception e){
e.printStackTrace();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
}
public void readExternal(ObjectInput oip)throws IOException,ClassNotFoundException{
eid="E-"+oip.readInt();
ename=oip.readUTF();
email=oip.readUTF()+"@durgasoft.com";
emobile="91-"+oip.readUTF();
}
public void getEmpDetails(){
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id : "+eid);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Mail : "+email);
System.out.println("Employee Mobile: "+emobile);
}
}
class ExternalizableEx{
public static void main(String args[])throws Exception{
FileOutputStream fos=new FileOutputStream("emp.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Employee emp1=new Employee("E- 111","Durga","durga@durgasoft.com","91-9988776655");
System.out.println("Employee Data before Serialization");
emp1.getEmpDetails();
oos.writeObject(emp1);
System.out.println();
FileInputStream fis=new FileInputStream("emp.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Employee emp2=(Employee)ois.readObject();
System.out.println("Employee Data After Deserialization"):
emp2.getEmpDetails();
}
}

344
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Files in Java:
File is a storage area to store data.
There are two types of files in Java.

1.Sequential Files
2.RandomAccessFiles

1.Sequential Files:
It will allow the user to retrive data in Sequential manner.
To represent Sequential files,Java has given a predefined class in the form of java.io.File.

To create File class object we have to use the following constructor.


public File(String file_Name)throws FileNotFoundException

EX:File f=new File("c:/abc/xyz/emp.txt");

Creating File class object is not sufficient to create a file at directory structure we have to use the
following method.
public File createNewFile()

To create a Directory, we have to use the following method.

public File mkdir()

To get file / directory name we have to use the following method.


public String getName()

To get file / directory parent location,we have to use the following method.

public String getParent()


To get file / directory absolute path,we have to use the following method.

public String getAbsolutePath()

To check whether the created thing File or not,we have to use the following method.

public boolean isFile()

To check whether the created thing is directory or not we have to use the following method.
345

public boolean isDirectory()


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
File f=new File("c:/abc/xyz/emp.txt");
f.createNewFile();
System.out.println(f.isFile());
System.out.println(f.isDirectory());
File f1=new File("c:/abc/xyz/student");
f1.mkdir();
System.out.println(f.isFile());
System.out.println(f.isDirectory());
System.out.println("File Name :"+f.getName());
System.out.println("Parent Name :"+f.getParent());
System.out.println("Absolute Path :"f.getAbsolutePath());
int size=fis.available();
byte[] b=new byte[size];
fis.read();
String data=new String(b);
System.out.println(data);
}
}

RandomAccessFile:
It is a Storage area,it will allow the user to read data from random positions.
To represent this file,java has given a predefined class in the form of
"java.io.RandomAccessFile".
To create RandomAccessFile class object,we have to use the following constructor.
public RandomAccessFile(String file_name,String access_Privileges)
where access_Privileges may be "r" [Read] or "rw" [Read and Write]

To write data into randomAccessFile,we have to use the following method.


public void writeXXX(xxx value)
where xxx may be byte,short,int,UTF[String],.....

To read data from RandomAccessFile,we have to use the following method

public XXX readXXX()


where xxx may be byte,short,int,UTF[String],.....
346

To move file pointer to a particular position in RandomAccessFile,we have to use the following
method.
Page

public void seek(int position)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
RandomAccessFile raf=new RandomAccessFile("abc.txt","rw");
raf.writeInt(111);
raf.writeUTF("Durga");
raf.writeFloat(5000.0f);
raf.writeUTF("HYD");
raf.seek(0);
System.out.println("Employee Number :"+raf.readInt());
System.out.println("Employee Name :"+raf.readUTF());
System.out.println("Employee Salary :"+raf.readFloat());
System.out.println("Employee Address :"+raf. readUTF ());
}
}

347
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Networking
By using java programming language we are able to prepare the following two types of applications.

1.Standalone Appl
2.Distributed Appl

1.Standalone Application:
If we prepare any java application with out using client-server arch then that java application is
called as "Standalone Application".

To prepare standalone applicatins we can use Core Libraries like java.io, java.util, java.lang,....

2.Distributed Application:
If we prepare any java application on the basis of Client-Server arch then that java application is
called as Distributed application.

To prepare Distributed applications, JAVA has provided the following set iof technologies.

1.Socket Programming
2.RMI
3.CORBA
4.EJBs
5.WebServices

1.Socket Programming:
If we want to prepare distributed applications by using Socket Programming then we have to use
Sockets between machines to transfer data from one machine to another machine.

Socket is a Channel or medium to transfer data from one machine to another machine.

In Socket programming we have to establish Sockets on the basis of System IP Address and Port
Numbers.

348
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)What is the difference between IPAddress and Port Number?

Ans:
IP Address is an unique identity to each and every machine over the network and which is provided by
network manager at the time of network configuration.

Port Number is an unique identity to each and every process being executed with in a single machine
and it would be provided by local operating system.

To prepare distributed applications by using Socket Programming the required predefined library was
provided by JAVA in the form of "java.net" package.

Socket programming Arch:

---- Diagram-------

Steps to prepare Client Application:

1.Create Socket at client machine:


To create Socket class object we have to use the following constructor from java.net.Socket class.

public Socket(String server_IP_Addr, int server_Port_No)

EX: Socket s=new Socket("localhost", 4444);

NOTE: If server socket is available at the same machine then we are able to use "localhost" inplace of
Server_IP_Addr.

2.Get OutputStream from Socket:


To get OutputStream from Socket we have to use the following method from java.net.Socket class.

public OutputStream getOutputStream()

EX: OutputStream os=s.getOutputStream();

3.Create PrintStream with OutputStream:


PrintStream ps=new PrintStream(os);
349
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.Send data to PrintStream:
String data="Hello";
ps.println(data);

NOTE: With the above steps , data will be send to Server, where Server will send response data to
client.

4.Get InputStream from Socket:


To get InputStream from Socket we have to use the following method.

public InputStream getInputSteam()


EX: InputStream is=s.getInputStream();

5.Create BufferedReader with InputStream:


BufferedReader br=new BufferedReader(new InputStreamReader(is));

6.Read data from BufferedReader:


String data=br.readLine();
System.out.println(data);

Steps To prepare Server Application:

1.Get InputStream from Socket:


InputStream is=s.getInputStream();

2.Create BufferedReader with InputStream:


BufferedReader br=new BufferedReader(new InputStreamReader(is));

3.Read data from BufferedReader:


String data=br.readLine();
System.out.println(data);

4.Get OutputStream from Socket:


OutputStream os=s.getOutputStream();

5.Create PrintStream with OutputStream:


PrintStream ps=new PrintStream(os);

6.Send Data to PrintStream:


String data="Hai";
350

ps.println(data);
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: At Server machine, we have to create ServerSocket and it has to accept the request from client
about to assign Socket from server machine inorder to establish connection .

EX: ServerSocket ss=new ServerSocket(4444);


Socket s=ss.accept();

The above application provides one time communication, but, if we want to provide infinite
communication then we have to use infinite loops at both client application and Server application.

Applcation-2:
ClientApp.java

import java.io.*;
import java.net.*;
public class ClientApp
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("localhost", 4444);
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));

InputStream is=s.getInputStream();
BufferedReader br2=new BufferedReader(new InputStreamReader(is));

while(true)
{
String data1=br1.readLine();
ps.println(data1);
String data2=br2.readLine();
System.out.println(data2);

if(data1.equals("bye") && data2.equals("bye"))


{
System.exit(0);
}
}
}
351

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


ServerApp.java

import java.io.*;
import java.net.*;
public class ServerApp
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(4444);
Socket s=ss.accept();
InputStream is=s.getInputStream();
BufferedReader br1=new BufferedReader(new InputStreamReader(is));

OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
BufferedReader br2=new BufferedReader(new InputStreamReader(System.in));

while(true)
{
String data1=br1.readLine();
System.out.println(data1);
String data2=br2.readLine();
ps.println(data2);

if(data1.equals("bye") && data2.equals("bye"))


{
System.exit(0);
}
}
}
}

352
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Collections
Collection is an object, it able to represent a group of other objects.

Q)In java applications, to represent a group of other elements we have already arrays then what is the
requirement to use Collections?
or
Q)What are the differences between Array and Collection?

Ans:
1.Arrays are having fixed size in nature.In case of arrays, we are able to add the elements upto the
specified size only, we are unable to add the elements over its size, if we are trying to add elements
over its size then JVM will rise an exception like "java.lang.ArrayIndexOutOfBoundsException".

EX:
Student[] std=new Student[3];
std[0]=new Student();
std[1]=new Student();
std[2]=new Student();
std[3]=new Student();--> ArrayIndexOutOfBoundsException

Collections are having dynamically Growble nature, even if we add the elements over its size then
JVM will not rise any exception.

EX:
ArrayList al=new ArrayList(3);
al.add(new Student());
al.add(new Student());
al.add(new Student());
al.add(new Student());--> No Exception

2.In java, bydefault, Arrays are able to allow homogeneous elements, if we are trying to add the
elements which are not same Array data type then Compiler will rise an error like "Incompatible
Types".

EX:
Student[] std=new Student[3];
std[0]=new Student();
353

std[1]=new Student();
std[2]=new Customer();--> Incompatible Types Error
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java, bydefault, Collections are able to allow hetergeneous elements, even we add different types of
elements Compiler will not rise any error.

EX:
ArrayList al=new ArrayList(3);
al.add(new Student());
al.add(new Employee());---> No Error
al.add(new Customer();----> No Error

3.Arrays are not having predefined methods to perform searching and sorting operations over the
elements, in case of arrays to perfrom searching and sorting operations developers have to provide
their own logic.

In case of Collections, predefined methods or predefined Collections are defined to perform Searching
and Sorting operations over the elements.

EX: In Collections , TreeSet was provided to perfrom sorting order.


TreeSet ts=new TreeSet();
ts.add("B");
ts.add("E");
ts.add("A");
ts.add("D");
ts.add("C");
ts.add("F");
System.out.println(ts);

OP: [A,B,C,D,E,F]

4.Arrays are able to allow only one type of elements, so Arrays are able to improve Typedness in java
applications and they are able to perform Typesafe operations.

Collections are able to allow different types of elements, so Collections are able to reduce typedness in
java applications and they are unable to perform Typesafe operations.

5.If we know the no of elements in advance at the time of writing java applications then Arrays are
better to use in java applications and they will provide very good performance in java applications, but,
But Arrays are not flexible to design applications.

In java applications, Collections are able to provide less performance, but, They will provide flexibility
354

to design applications.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To repersent Collection objects in java applications , JAVA has provided predefined classes and
interfaces in the form of java.util package called as "Collection Framework".

Q)What are the classes and interfaces are existed in java.util package to repersent Collections?

--- Diagram---

Q)What are the differences between Collection and Map?

Ans:
Collections are able to store all the elements individually, not in the form of Key-value pairs.

EX: To store 10 Employee objects we will use Collection.

Maps are able to store all the elements in the form of Key-value pairs.

EX: To repersent Telephone Directory , where we are representing phone number and Customer Name
we have to use Maps.

Q)What are the differences between List and Set?

Ans:
1.List is index based, it able to allow all the elements as per indexing.

Set is not index based, it able to allow all the elements on the basis of elements hashcode values.

2.List is able to allow duplicate elements.

Set is not allowing duplicate elements.

3.List is able to allow any no of null values.

Set is able to allow only one null value.

4.List is following insertion order.

Set is not following insertion order bydefault.


Note: LinkedHashSet is following insertion order.
355
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5.List is not following sorting order.
Sets are not following sorting order bydefault.
Note: SortedSet, NavigableSet and TreeSet are following Sorting order.

6.List is able to allow heterogeneous elements.

Sets are able to allow hetergeneous elements bydefault.


Note: SortedSett, NavigableSet and TreeSet are allowing only Homogeneous elements.

Collection:
--> It is an interface provided by JAVA along with JDK1.2 version.
--> It able to repersent a group of individual elements as single unit.
--> It has provided the following methods common to every implementation class.

1.public boolean add(Object obj)


-->This method is able to add the specified element to Collection object. If the specified element is
added successfully then add(-) method will return "true" value. If the specified element is not
addedd successfully then add() method will return "false" value.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
System.out.println(hs.add("A"));
hs.add("B");
hs.add("C");
hs.add("D");
System.out.println(hs);
System.out.println(hs.add("A"));
System.out.println(hs);
}
}
OP:
true
[A,B,C,D]
false
[A,B,C,D]
356
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.public boolean addAll(Collection c)
-->This method can be used to add all the elements of the specified Collection to the present
Collection object. If addition operation is success then addAll(-) method will return "true" value, if
addition operation is failure then addAll() method will return "false" value.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("A");
hs.add("B");
hs.add("C");
hs.add("D");
System.out.println(hs);
HashSet hs1=new HashSet();
System.out.println(hs1.addAll(hs));
System.out.println(hs1);
System.out.println(hs1.addAll(hs));
System.out.println(hs1);
}
}
OP:
[D,A,B,C]
true
[D,A,B,C]
false
[D,A,B,C]

3.public boolean remove(Object obj)


--> This method can be used to remove the specified element from the Collection object. If remove
operation is success then remove() method will return true value, if remove operation is failure then
remove() method will return false value.
357
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:

import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
System.out.println(al);
System.out.println(al.remove("B"));
System.out.println(al);
System.out.println(al.remove("B"));
System.out.println(al);
}
}
OP:
[A,B,C,D]
true
[A,C,D]
false
[A,C,D]

4.public boolean removeAll(Collection c)


-->This method can be used to remove all the elements of the specified Collection from the present
Collection object. If remove operation is success then removeAll() method will return true value. If
remove operation is not success then removeAll() method will return false value.

358
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
System.out.println(al);
ArrayList al1=new ArrayList();
al1.add("B");
al1.add("C");
al1.add("D");
System.out.println(al1);
System.out.println(al.removeAll(al1));
System.out.println(al);
System.out.println(al.removeAll(al1));
System.out.println(al);
}
}
OP:
[A,B,C,D,E,F]
[B,C,D]
true
[A,E,F]
false
[A,E,F]

5.public boolean contains(Object obj)


--> This method will check whether the specified element is existed or not in the Collection object.
If the specified element is existed then this method will return "true" value . If the specified element
is not existed then this method will return "false" value.
359
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
System.out.println(al);
System.out.println(al.contains("B"));
System.out.println(al.contains("X"));
}
}
OP:
[A,B,C,D,E,F]
true
false

6.public boolean containsAll(Collection c)


-->This method will check whether all the elements of the specified Collection are available or not
in the present Collection object. If all the elements are existed then containsAll() method will return
true value, if atleast one element is not existed then containsAll() method will return false value.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
360

al.add("E");
al.add("F");
Page

System.out.println(al);
ArrayList al1=new ArrayList();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


al1.add("B");
al1.add("C");
al1.add("D");
System.out.println(al.containsAll(al1));
al1.add("X");
al1.add("Y");
System.out.println(al.containsAll(al1));
}
}
OP: [A,B,C,D,E,F]
true
false

7.public boolean retainAll(Collection c)


-->This method will remove all the elements from the present Collection object except the elements
which are existed in the specified Collection object. if atleast one element is removed then
retainAll() method will return true value. If no elements are removed then retainsAll() method will
return false value.

EX: import java.util.*;


class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
System.out.println(al);
ArrayList al1=new ArrayList();
al1.add("B");
al1.add("C");
al1.add("D");
System.out.println(al1);
System.out.println(al.retainAll(al1));
System.out.println(al);
System.out.println(al.retainAll(al1));
361

System.out.println(al);
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
[A,B,C,D,E,F]
[B,C,D]
true
[B,C,D]
false
[B,C,D

8.public int size()


--> This method can be used to return an integer value representing the no of elements which are
existed in the Collection object.

9.public void clear()


--> This method can be used to remove all elements from Collection objectt.

10.public boolean isEmpty()


--> This method can be used to check whether Collection objectt is empty or not.If the Collection
object is empty then isEmpty() method will return "true" value. If the Collection object is not empty
then isEmpty() method will return "false" value.

11.public Object[] toArray()


--> This method will return all the elements of the Collection object in the form of Object[].

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
System.out.println(al);
System.out.println(al.size());
Object[] obj=al.toArray();
362

for(Object o: obj)
{
Page

System.out.print(o+" ");
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println();
System.out.println(al.isEmpty());
al.clear();
System.out.println(al.isEmpty());
System.out.println(al);
}
}
OP:
[A,B,C,D,E,F]
6
ABCDEF
false
true
[]

List :
-->List is a direct chaild interface to Collection interface
-->List was provided by JAVA along with its JDK1.2 version
-->List is index based, it able to arrange all the elements as per indexing.
-->List is able to allow duplicate elements.
-->List is following insertion order.
-->List is not following Sorting order.
-->List is able to allow any no of null values.
-->List is able to allow heterogeneous elements.

List interface has provided the following methods common to all of its implementation classes.
1.public void add(int index, Object obj)
-->It able to add the specified element at the specified index value.
2.public Object set(int index, Object obj)
-->It able to set the specifiedf element at the specified index value.

Q)What is the difference between add(--) method and set(--) metod?

Ans:
add(--) method is able to perform insert operation. if any element is existed at the specified element
then add() method will insert the specified new element at the specified index value and add() method
will adjust the existed element to next index value. If no element is existed at the specified index then
add() method add the specified element at the specified index.

set(--) method is able to perform replace operation. If any element is existed at the specified index then
363

set() method will remove the existed element and set(-) method will add the specified element to the
specified index and set() method will return the removed element. If no element is existed at the
Page

specified index value then set() method will rise an exception like
java.lang.indexOutOfBoundsException.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.public Object get(int index)
-->It will return anelement available at the specified index value.
4.public Object remove(int index)
-->It will remove and return an element available at the specified index value.
5.public int indexOf(Object obj)
-->It will return an index value where the first occurence of the specified element.
6.public int lastIndexOf(Object obj)
-->It will return an index value where the last occurence of the specified element.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
System.out.println(al);
al.add(1,"X");
System.out.println(al);
al.add(6,"F");
System.out.println(al);
al.set(3,"Y");
System.out.println(al);
//al.set(7,"Z");--->IndexOutOfBoundsException
System.out.println(al.get(4));
System.out.println(al.remove(6));
System.out.println(al);
al.add(6,"X");
al.add(7,"B");
al.add(8,"X");
System.out.println(al);
System.out.println(al.indexOf("X"));
System.out.println(al.lastIndexOf("X"));
}
364

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


ArrayList:
-->It was provided by JAVA along with JDK1.2 version.
-->It is a direct implementation class to List interface.
-->It is index based.
-->It allows duplicate elements.
-->It follows insertion order.
-->It will not follow sorting order.
-->It allows heterogeneous elements.
-->It allows any no of null values.
-->Its internal data structer is "Resizable Array".
-->Its initial capacity is 10 elements.
-->Its incremental capacity ration is
new_Capacity=(Current_Capacity*3/2)+1
-->It is best option for frequent retrival operations.
-->It is not synchronized.
-->No method is synchronized method in ArrayList.
-->It allows more than one thread to access data.
-->It follows parallel execution.
-->It will reduce execution time.
-->It will improve application performance.
-->It will not give guarantee for data consistency.
-->It is not threadsafe.
-->It is not Legacy Collection.

Constructors:
1.public ArrayList()
-->It can be used to create an empty ArrayList object with 10 elements as default capacity value.
EX: ArrayList al=new ArrayList();

2.public ArrayList(int capacity)


-->It can be used to create an empty ArrayList object with the specified capacity.
EX: ArrayList al=new ArrayList(20);

3.public ArrayList(Collection c)
-->It can be used to create an ArrayList object with all the elements of the specified Collection
object.
365
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al1=new ArrayList();
al1.add("AAA");
al1.add("BBB");
al1.add("CCC");
al1.add("DDD");
System.out.println(al1);
ArrayList al2=new ArrayList(al1);
System.out.println(al2);
}
}
OP:
[AAA,BBB,CCC,DDD]
[AAA,BBB,CCC,DDD]
EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
System.out.println(al);
al.add("B");
System.out.println(al);
al.add(new Integer(10));
System.out.println(al);
al.add(null);
al.add(null);
System.out.println(al);
366

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Vector:
-->It was introduced in JDK1.0 version.
-->It is Legacy Collection.
-->It is a direct implementation class to List interface.
-->It is index based.
-->It allows duplicate elements.
-->It follows insertion order.
-->It will not follow sorting order.
-->It allows heterogeneous elements.
-->It allows any no of null values.
-->Its internal data structer is "Resizable Array".
-->Its initial capacity is 10 elements.
-->It is best choice for frequent retrival operations.
-->It is not good for frequent insertions and deletion operations.
-->Its incremental capacity is double the current capacity.
New_capacity=2*Current_Capacity
-->it is synchronized elemenet.
-->All the methods of vector class are synchronized.
-->It allows only one thread at a time.
-->It follows sequential execution.
-->It will increase execution time.
-->It will reduce application performance.
-->It is giving guarantee for data consistency.
-->It is threadsafe.

Constructors:
1.public Vector()
--> It can be used to create an empty Vector object with the initial capacity 10 elements.

EX: Vector v=new Vector();


System.out.println(v.capacity());

OP: 10
2.public Vector(int capacity)

--> It can be used to create an empty vector object with the specified capacity value.

EX: Vector v=new Vector(20);


System.out.println(v.capacity());
367

OP: 20
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.public Vector(int capacity, int incremental_Ratio)
-->This constructor can be used to create an empty Vector object with the specified initial capacity
and with the specified incremental ratio.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector v=new Vector(5,5);
System.out.println(v.capacity());
for(int i=1;i<=6;i++)
{
v.add(i);
}
System.out.println(v.capacity());
for(int i=7;i<=11;i++)
{
v.add(i);
}
System.out.println(v.capacity());
}
}

OP:
5
10
15

368
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.public Vector(Collection c)
-->This constructor can be used to create Vector object with all the elements of the specified
Collection object.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector v=new Vector();
v.add("A");
v.add("B");
v.add("C");
v.add("D");
System.out.println(v);
Vector v1=new Vector(v);
System.out.println(v1);
}
}
OP:
[A,B,C,D]
[A,B,C,D]

Methods:
1.public void addElement(Object obj)
-->It will add the specified element to Vector.

2.public Object firstElement()


-->It will return first element of the Vector.

3.public Object lastElement()


-->It will return last element of the Vector.

4.public Object elementAt(int index)


-->It will return an element available at the specified index.

5.public void removeElement(Object obj)


-->It will remove the specified element from Vector.
369

6.public void removeElementAt(int index)


Page

-->It will remove an element existed at the specified index value.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


7.public void removeAllElements()
-->It will remove all elements from Vector.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector v=new Vector();
v.addElement("A");
v.addElement("B");
v.addElement("C");
v.addElement("D");
v.addElement("E");
System.out.println(v);
System.out.println(v.firstElement());
System.out.println(v.lastElement());
System.out.println(v.elementAt(3));
v.removeElement("D");
System.out.println(v);
v.removeElementAt(2);
System.out.println(v);
v.removeAllElements();
System.out.println(v);
}
}

Q)What are the differences between ArrayList and Vector?


Ans:
1.ArrayList class was introduced in JDK1.2 version.
Vector class was introduced in JDK1.0 version.

2.ArrayList is not Legacy Collection.


Vector is Legacy Collection.

3.ArrayList is not synchronized.


Vector is synchronized.

4.No method is synchronized method in ArrayList.


370

Almost all the methods are synchronized methods in vector.


Page

5.ArrayList allows more than one thread at a time to access data.


Vector allows only one thread at a time to access data.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6.ArrayList follows parallel execution.
Vector follows sequential execution.

7.ArrayList is able to reduce application execution time.


Vector is able to increase application execution time.

8.ArrayList is able to improve application performance.


Vector is able to reduce application performance.

9.ArrayList is not giving guarantee for data consistency.


vector is giving guarantee for data consistency.

10.ArrayList is not threadsafe.


Vector is threadsafe.

11.ArrayList incremental capacity is (Current_Capacity*3/2)+1


Vector incremental capacity is
2*Current_Capacity

12.We are unable to get capacity value of ArrayList, because, no capacity() method in ArrayList class.

We can get capacity value of Vector, because, capacity() method is existed in vector class.

Stack:
It was introduced in JDK1.0 version, it is a Legacy Collection and it is a chaild class to Vector
class. It able to arrange all the elements as per "Last In First Out"
[LIFO] alg.

Constructor:
public Stack()
--> It will create an empty Stack object.

EX: Stack s=new Stack();


371
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Methods:
public void push(Object obj)
--> It will add the specified element to Stack.

public Object pop()


--> It will remove and return top of the stack.

public Object peek()


--> It will return top of the stack.

public int search(Object obj)


--> It will check whether the specified element is existed or not in the Stack, if the specified element
is not existed then it will return '-1' value, if the specified element is existed then it will return its
position.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
s.push("D");
s.push("E");
System.out.println(s);
System.out.println(s.pop());
System.out.println(s);
System.out.println(s.peek());
System.out.println(s);
System.out.println(s.search("B"));
System.out.println(s.search("X"));

}
}
372
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


LinkedList:
-->It was introduced in JDK1.2 version.
-->It is not Legacy Collection.
-->It is a direct implementation class to List interface.
-->It is index based.
-->It allows duplicate elements.
-->It follows insertion order.
-->It is not following sorting order.
-->It allows heterogeneous elements.
-->It allows null values in any number.
-->Its internal data structer is "Double Linked List".;
-->It is best choice for frequent insertions and deletions.
-->It is not synchronized Collection.
-->No method is synchronized in LinkedList.
-->It allows more than one thread to access data.
-->It will follow parallel execution.
-->It will decrese execution time.
-->It will improve application performance.
-->It is not giving guarantee for data consistency.
-->It is not threadsafe.

Constructors:
1.public LinkedList()
-->It will create an empty LinkedList object.

EX: LinkedList ll=new LinkedList();

2.public LinkedList(Collection c)
-->It will create LinkedList object with all the elements of the specified Collection object.

EX:
LinkedList ll1=new LinkedList();
ll1.add("A");
ll1.add("B");
ll1.add("C");
ll1.add("D");
System.out.println(ll1);
LinkedList ll2=new LinkedList(ll1);
System.out.println(ll2);
373

OP: [A, B, C, D]
[A, B, C, D]
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Methods:
1.public void addFirst(Object obj)
-->It will add the specified element as first element to LinkedList.

2.public void addLast(Object obj)


-->It will add the specified element as last element to LinkedList.

3.public Object getFirst()


-->It will return first element from LinkedList.

4.public Object getLast()


-->It will return last element from LinkedList.

5.public void removeFirst()


-->It will remove first element from LinkedList.

6.public void removeLast()


-->It will remove last element from LinkedList.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
ll.add("E");
System.out.println(ll);
ll.addFirst("X");
ll.addLast("Y");
System.out.println(ll);
ll.removeFirst();
ll.removeLast();
System.out.println(ll);
System.out.println(ll.getFirst());
374

System.out.println(ll.getLast());
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Cursors / Iterators in Collections:
In java applications, when we pass Collection object reference variable as parameter to
System.out.println(-) method, then, JVM will execute toString() method internally. Initially
toString() method was implemented in java.lang.Object class, it was implemented in such a way
that to return a String contains "Class_Name@Ref_val" . In java applications, Collection classes are
not depending on Object class toString() method, they are having their own toString() method ,
which are implemented in such a way to return a String contains all the elements of the Collection
object by enclosed with [].

EX: ArrayList al=new ArrayList();


al.add("A");
al.add("B");
al.add("C");
al.add("D");
System.out.println(al);

OP: [A, B, C, D]

As per the requirement, we dont want to display all the Elements at a time on command prompt, we
want to retrive elements one by one individually from Collection objects and we want to display all the
elements one by one on Command prompt.

To achieve the above requirment, Collection Framework has provided the following three Cursors or
Iterators.
1.Enumeration
2.Iterator
3.ListIterator

1.Enumeration:
It is a Legacy Cursor, it is applicable for only Legacy Collections to retirve elements in one by one
fashion.
To retrive elements from Collections by using Enumeration we have to use the following steps.

1.Create Enumeration object:


To create Enumeration object we have to use the following method from Legacy Collections.
public Enumeration elements()
375
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.Retrive elements from Enumeration:
a)Check whether more elements are available or not from Current cursor position by using the
following method.
public boolean hasMoreElements()
--> It will return true value if atleast next element is existed.
-->It will return false value if no element is existed from current cursor position.
b)If atleast next element is existed then read next element and move cursor to next position by using
the following method.
public Object nextElement()

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector v=new Vector();
v.add("A");
v.add("B");
v.add("C");
v.add("D");
v.add("E");
System.out.println(v);
Enumeration e=v.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
}

Drawbacks:
1.Enumeration is applicable for only Legacy Collections.
2.Enumeration is able to allow only read operation while iterating elements.

Iterator:
Iterator is an interface provided JAVA along with its JDK1.2 version.
Iterator can be used to retrive all the elements from Collection objects in one by one fashion.
Iterator is applicable for all the Collection interface implementation classes to retrive elements.
376

Iterator is able to allow both read and remove operatins while iterating elements.
If we want to use Iterator in java applications then we have to use the following steps.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Create Iterator object:
To create Iterator object we have to use the following method from all Collection implementation
classes.
public Iterator iterator()

EX:Iterator it=al.iterator();

2.Retrive elements from Iterator:


To retrive elements from Iterator we have to use the following steps.
a) Check whether next element is existed or not from the current cursor position by using the
following method.
public boolean hasNext()
-->This method will return true if next element is existed.
-->This method will return false if no element is existed from current cursor position.

b)If next element is existed then read next element and move cursor to next position by using the
following method.

public Object next()

NOTE: To remove an element available at current cursor position then we have to use the following
method

public void remove()

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
377

System.out.println(al);
Iterator it=al.iterator();
Page

while(it.hasNext())
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String element=(String)it.next();
System.out.println(element);
if(element.equals("C"))
{
it.remove();
}
}
System.out.println(al);
}
}

Q)What are the differences between Enumeration and Iterator?

Ans:
1.Enumeration is Legacy Cursor, it was introduced in JDK1.0 version.
Iterator is not Legacy Cursor, it was introduced in JDK1.2 version.

2.Enumeration is not Universal Cursor, it is applicable for only Legacy Collections.


Iterator is an universal Cursor, it is applicable for all Collection implementations.

3.Enumeration is able to allow only read operation while iterating elements.


Iterator is able to allow both read operation and remove operation while iterating elements.

ListIterator:
It is an interface provided by JAVA along with JDK1.2 version.

It able to allow to read elements in both forward direction and backward direction.

It able to allow the operations like read, insert, replace and remove while iterating elements .

If we want to use ListIterator in java applications then we have to use the following steps.

1.Create ListIterator Object:


To create ListIterator object we have to use the following method.

public ListIterator listIterator()

EX: ListIterator lit=ll.listIterator();


378
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.Retrive Elements from ListIterator

To retirv elements from ListIterator in Forward direction then we have to use the following methods.

public boolean hasNext()


--> It will check whether next element is existed or not from the current cursor position.

public Object next()


-->It will return next element and it will move cursor to the next position in forward direction.

public int nextIndex()


--> It will return next index value from the current cursor position.

To retirive elements in Backward direction we have to use the following methods.

public boolean hasPrevious()


--> It will check whether previous element is existed or not from the current cursor position, If
previous element is existed then it will return "true" value, if previous element is not existed then it
will return false value.

public Object previous()


-->It will return previous element and it will mo ve cursor to the next previous position.

public int previousIndex()


-->It will return previous index value from the current cursor position.

To perform the operations like remove, insert and replace over the elements we have to use the
following methods.

public void remove()


public void add(Object obj)
public void set(Object obj)

379
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
ll.add("E");
ll.add("F");
System.out.println(ll);
ListIterator lit=ll.listIterator();
System.out.println("Elements in Forward Direction");
while(lit.hasNext())
{
System.out.println(lit.nextIndex()+"--->"+lit.next());
}
System.out.println();
System.out.println("Elements in Backward Direction");
while(lit.hasPrevious())
{
System.out.println(lit.previousIndex()+"--->"+lit.previous());
}
}
}

EX: import java.util.*;


class Test1
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
ll.add("E");
380

ll.add("F");
System.out.println(ll);
Page

ListIterator lit=ll.listIterator();
while(lit.hasNext())

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
String element=(String)lit.next();
if(element.equals("B"))
{
lit.add("X");
}
if(element.equals("D"))
{
lit.set("Y");
}
if(element.equals("E"))
{
lit.remove();
}
}
System.out.println(ll);
}
}

Q)What are the differences between Enumeration, Iterator and ListIterator?

Ans:
1.Enumeration is applicable for only Legacy Collections.

Iterator is applicable for all Collection implementations.

ListIterator is applicable for only List implementations.

2.Enumeration and Iterator are allowd to iterate elements in only Forward direction.

ListIterator is able to allow to iterate elements in both Forward direction and backward direction.

3.Enumeration is able to allow only read operation while iterating elements.

Iterator is able to allow both read and remove operations while iterating elements.

ListIterator is able to allow the operations like insert, replace, remove adn read operations while
iterating elements.
381
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Set:
-->It was introduced in JDK1.2 version.
-->It is a direct chaild interface to Collection interface.
-->It is not index based, it able to arrange all the elements on the basis of elements hashcode
values.
-->It will not allow duplicate elements.
-->It will not follow insertion order.
Note:LinkedHashSet will follow insertion order.
-->It will not follow Sorting order.
Note: SortedSet, NavigableSet and TreeSet are following Sorting order.
-->It able to allow only one null value.
Note: SortedSet, NavigableSet and TreeSet are not allowing even single null value.

HashSet:
-->HashSet is a direct implementation class to Set interface.
-->It was introduced in JDK1.2 version.
-->It is not index based, it able to arrange all the elements on the basis of elements hashcode
values.
-->It will not allow duplicate elements.
-->It will not follow insertion order.
-->It will not follow Sorting order.
-->It able to allow only one null value.
-->Its interal data structer is "Hashtable".
-->its initial capacity is "16" elements and its initial fill_Ratio is 75%.
-->it is not synchronized.
-->Almost all the methods are not synchronized in HashSet
-->It allows more than one thread at a time.
-->It follows parallel execution.
-->It will reduce execution time.
-->It improves performance of the applications.
-->It is not giving guarantee for data consistency.
-->It is not threadsafe.

Constuctors:
1.public HashSet()
--> This constructor can be used to create an empty HashSet object with 16 elements as initial
capacity and 75% fill ratio.

EX: HashSet hs=new HashSet();


382
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.public HashSet(int capacity)
-->This constructor can be used to create an empty HashSet object with the specified capacity as
initial capacity and with the default fill ratio 75%.

EX: HashSet hs=new HashSet(20);

3.public HashSet(int capacity, float fill_Ratio)


-->This constructor can be used to create an empty HashSet object with the specified capacity and
with the specifiedf fill ratio.

EX: HashSet hs=new HashSet(20, 0.85f);

4.public HashSet(Collection c)
--> This constructor can be used to create HashSet object with all the elements of the specified
Collection .

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs1=new HashSet();
hs1.add("A");
hs1.add("B");
hs1.add("C");
hs1.add("D");
hs1.add("E");
System.out.println(hs1);
HashSet hs2=new HashSet(hs1);
System.out.println(hs2);
}
}

OP:
[D,E,A,B,C]
[D,E,A,B,C]
383
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("A");
hs.add("B");
hs.add("C");
hs.add("D");
hs.add("E");
System.out.println(hs);
hs.add("B");
System.out.println(hs);
hs.add(null);
hs.add(null);
System.out.println(hs);
hs.add(new Integer(10));
System.out.println(hs);
}
}

LinkedHashSet:
Q)What are the differences between HashSet and LinkedHashSet?

Ans:
1.HashSet was introduced in JDK1.2 version.
LinkedhashSet was introduced in JDK1.4 version.

2.HashSet is not following insertion order.


LinkedHashSet is following insertion order.

3.The internal data structer of HashSet is "Hashtable".


The internal data structer of LinkedHashSet is "Hashtable" and "LinkedList".
384
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("A");
hs.add("B");
hs.add("C");
hs.add("D");
hs.add("E");
System.out.println(hs);
LinkedHashSet lhs=new LinkedHashSet();
lhs.add("A");
lhs.add("B");
lhs.add("C");
lhs.add("D");
lhs.add("E");
System.out.println(lhs);
}
}
OP:
[D,E,A,B,C]
[A,B,C,D,E]

SortedSet:
-->It was introduced in JDK1.2 version.
-->It is a chaild interface to Set interface.
-->It is not index based.
-->It is not allowing duplicate elements.
-->It is not following insertion order.
-->It follows Sorting order.
-->It allows only homogeneous elements.
-->It will not allow heterogeneous elements, if we are trying to add heterogeneous elements then
JVM will rise an exception like java.lang.ClasscastException.
-->It will not allow null values, if we are trying to add any null value then JVM will rise an
exception like java.lang.NullPointerException.
-->It able to allow only Comparable objects bydefault, if we are trying to add non comparable
385

objects then JVM will rise an exception like java.lang.ClassCastException.


Page

Note:If we are trying to add non comparable objects then we have to use Comparator.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Methods:
1.public Object first()
-->It will return first element from SortedSet.

2.public Object last()


-->It will return last element from SortedSet.

3.public SortedSet headSet(Object obj)


-->It will return SortedSet object with the elements which are less the specified element.

4.public SortedSet tailSet(Object obj)


-->It will return SoredSet object with the elements which are greater than or equals to the specified
element.

5.public SortedSet subSet(Object obj1, Object obj2)


-->It will return SortedSet object with all elements which are greater than or equals to the specified
first element and which are less than the specified second element.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add("D");
ts.add("F");
ts.add("B");
ts.add("E");
ts.add("C");
ts.add("A");
System.out.println(ts);
System.out.println(ts.first());
System.out.println(ts.last());
System.out.println(ts.headSet("D"));
System.out.println(ts.tailSet("D"));
System.out.println(ts.subSet("B","E"));
}
}
386
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NavigableSet
It was introduced in JAVA6 version, it is a chaild interface to SortedSet interface, it is following all the
properties of SortedSet and it has define methods to provide navigations over the elements.

Methods:
1.public Object ceiling(Object obj)
--> It will return lowest element among all the elements which are greater than or equals to the
specified element.

2.public Object higher(Object obj)


--> It will return lowest element among all the elements which are greater than the specified
element.

3.public Object floor(Object obj)


-->It will return highest element among all the elements which are less than or equals to the
specified element.

4.Trpublic Object lower(Object obj)


-->It will return highest element among all the elements which are less than the specified element.

5.public Object pollFirst()


--> It will remove and return first element from NavigableSet.

6.public Object pollLast()


--> It will remove and return last element from NavigableSet.

7.public NavigableSet descendingSet()


-->It will return all elements in the form of NavigableSet in descending order.

387
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add("D");
ts.add("F");
ts.add("B");
ts.add("E");
ts.add("C");
ts.add("A");
System.out.println(ts);
System.out.println(ts.ceiling("D"));
System.out.println(ts.higher("D"));
System.out.println(ts.floor("D"));
System.out.println(ts.lower("D"));
System.out.println(ts.descendingSet());
ts.pollFirst();
ts.pollLast();
System.out.println(ts);
}
}

TreeSet:
-->It was introduced in JDK1.2 version.
-->It is not Legacy Collection.
-->It has provided implementation for Collection, Set, SortedSet and navigableSet interfaces.
-->It is not index based.
-->It is not allowing duplicate elements.
-->It is not following insertion order.
-->It follows Sorting order.
-->It allows only homogeneous elements.
-->It will not allow heterogeneous elements, if we are trying to add heterogeneous elements then
JVM will rise an exception like java.lang.ClasscastException.
-->It will not allow null values, if we are trying to add any null value then JVM will rise an
exception like java.lang.NullPointerException.
-->It able to allow only Comparable objects bydefault, if we are trying to add non comparable
388

objects then JVM will rise an exception like java.lang.ClassCastException.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: If we are trying to add non comparable objects then we have to use java.util.Comparator.
-->Its internal data structer is "Balanced Tree".
-->It is mainly for frequent search operations.

Constructors:
1.public TreeSet()
-->It can be used to create an Empty TreeSet object.

EX: TreeSet ts=new TreeSet();

2.public TreeSet(Comparator c)
-->It will create an empty TreeSet object with the explicit Sorting mechanism in the form of
Comparator

EX: TreeSet ts=new TreeSet(new MyComparator());

3.public TreeSet(SortedSet ts)


-->It will create TreeSet object with all elements of the specified SortedSet.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts1=new TreeSet();
ts1.add("B");
ts1.add("C");
ts1.add("F");
ts1.add("A");
ts1.add("E");
ts1.add("D");
System.out.println(ts1);
TreeSet ts2=new TreeSet(ts1);
System.out.println(ts2);
}
}
389
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.public TreeSet(Collection c)
-->It able to create TreeSet object with all the elements of the specified Collection.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("B");
al.add("C");
al.add("F");
al.add("A");
al.add("E");
al.add("D");
System.out.println(al);
TreeSet ts=new TreeSet(al);
System.out.println(ts);
}
}
EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add("B");
ts.add("C");
ts.add("F");
ts.add("A");
ts.add("E");
ts.add("D");
System.out.println(ts);
ts.add("B");
System.out.println(ts);
//ts.add(null);--> NullPointerException
//ts.add(new Integer(10));-->ClassCastException
390

//ts.add(new StringBuffer("BBB"));->ClassCastException
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


When we add elements to the TreeSet object , TreeSet object will arrange all the elements in a
particular sorting order withthe following algorithm.

1.TreeSet will construct a Tree[Balanced Tree] on the basis of the elements.


To construct Balanced Tree we have to use the following steps.
a)If the element is first element to the TreeSet object then make that element as "Root Node".
b)If the element is not first element then access compareTo(--) method over the present
element by passing previous elements one by one of the balanced Tree right from root node until the
present element is located in Tree.
1.If compareTo(-) method returns -ve value then goto left chaild of the present node and access
again compareTo(-) method by passing left chaild. If no left chaild is existed then make the
present element as left chaild
2.If compareTo(-) method returns +ve value then goto right chails and access again
compareTo(-) by passing right as parameter. if no right chaild is existed then make the present element
as right chaild.
3.If compareTo(-) method return 0 value then discard the present element and declare that the
present element is a duplicate element of the existed element.

2.TreeSet will Retrive all the elements from balanced Tree by following Inorder traversal.

In String class, compareTo(-) method was implemented like below.

str1.compareTo(str2);
1.If str1 come first when compared with str2 as per dictionary order then compareTo() method will
return -ve value.
2.If str2 come first when compared with str1 in dictionary order then compareTo() method will
return +ve value.
3.If str1 and str2 are same or available at same location in dictionary order then compareTo(-)
method will return 0 value.

If we want to add user defined elements like Employee, Student, Customer to TreeSet then we have to
use the following steps.

1.Declare an user defined class.


2.Implement java.lang.Comparable iterface in User defined class.
3.Provide implementation for compareTo(-) method in user defined class.
4.In main class , in main() method , create objects for user defined class and add objects to TreeSet
object..

---Program----
391
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we add non-comparable objects to TreeSet object then JVM will rise an exception like
java.lang.ClassCastException, because, Non-Comparable objects are not providing compareTo(-)
method internally, but, it is required to the TreeSet inorder to provide sorting order over elements.

If we want to add non-Comparable objects to TreeSet object then we must provide sorting logic to
TreeSet object explicitly , for this, we have to use java.util.Comparator interface.

If we want to use Comparator interface in java applications then we have to use the following steps.

1.Declare an User defined class.


2.Implement java.util.Comparator interface in user defined class.
3.Provide implementation for Comparator interface methods in user defined class.
public boolean equals(Object obj)
public int compare(Object obj1, Object obj2)

Note: In User defined class it is not required to implement equals(-) method, because, equals(-)
method will come from default super class Object.
4.Provide User defined Comparator object to TreeSet object

EX: MyComparator mc=new MyComparator();


TreeSet ts=new TreeSet(mc);

EX:
import java.util.*;
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
StringBuffer s1=(StringBuffer)obj1;
StringBuffer s2=(StringBuffer)obj2;

int length1=s1.length();
int length2=s2.length();
int val=0;
if(length1<length2)
{
val=-100;
}
else if(length1>length2)
392

{
val=100;
Page

}
else

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
val=0;
}
return -val;
}
}
class Test
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer("AAA");
StringBuffer sb2=new StringBuffer("BB");
StringBuffer sb3=new StringBuffer("CCCC");
StringBuffer sb4=new StringBuffer("D");
StringBuffer sb5=new StringBuffer("EEEEE");
MyComparator mc=new MyComparator();
TreeSet ts=new TreeSet(mc);
ts.add(sb1);
ts.add(sb2);
ts.add(sb3);
ts.add(sb4);
ts.add(sb5);
System.out.println(ts);
}
}

EX:
import java.util.*;
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Student s1=(Student)obj1;
Student s2=(Student)obj2;

int val=s1.saddr.compareTo(s2.saddr);
return -val;
}
}
class Student
393

{
String sid;
Page

String sname;
String saddr;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Student(String sid, String sname, String saddr)
{
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
}
public String toString()
{
return "["+sid+","+sname+","+saddr+"]";
}
}
class Test
{
public static void main(String[] args)
{
Student std1=new Student("S-111", "Durga", "Hyd");
Student std2=new Student("S-222", "Anil", "Chennai");
Student std3=new Student("S-333", "Rahul", "Banglore");
Student std4=new Student("S-444", "Rameshh", "Pune");
MyComparator mc=new MyComparator();
TreeSet ts=new TreeSet(mc);
ts.add(std1);
ts.add(std2);
ts.add(std3);
ts.add(std4);
System.out.println(ts);
}
}

Q)In Java applications, if we provide both implicit Sorting through Comparable and explicit sorting
through Comparator to the TreeSet object at a time then which Sorting logic would be prefered by
TreeSet inorder to Sort elements?
Ans:
If we provide both implicit Sorting through Comparable and Explicit Sorting through Comparator to
the TreeSet object at a time then TreeSet will take explicit Sorting through Comparator to sort all the
elements.
394
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Customer cust1=(Customer)obj1;
Customer cust2=(Customer)obj2;

int val=cust1.caddr.compareTo(cust2.caddr);
return -val;
}
}
class Customer implements Comparable
{
String cid;
String cname;
String caddr;

Customer(String cid, String cname, String caddr)


{
this.cid=cid;
this.cname=cname;
this.caddr=caddr;
}
public String toString()
{
return "["+cid+","+cname+","+caddr+"]";
}
public int compareTo(Object obj)
{
Customer cust=(Customer)obj;
int val=this.caddr.compareTo(cust.caddr);
return val;
}
}
class Test
{
public static void main(String[] args)
395

{
Customer c1=new Customer("C-111", "Durga", "Hyd");
Page

Customer c2=new Customer("C-222", "Anil", "Chennai");


Customer c3=new Customer("C-333", "Rahul", "Banglore");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Customer c4=new Customer("C-444", "Ramesh", "Pune");
MyComparator mc=new MyComparator();
TreeSet ts=new TreeSet(mc);
ts.add(c1);
ts.add(c2);
ts.add(c3);
ts.add(c4);
System.out.println(ts);
}
}

Queue:
--> It was introduced in JDK5.0 version.
--> It is a direct chaild interface to Collection interface.
--> It able to arrange all the elements as per FIFO [First In First Out],but, it is possible to
change this algorithm as per our requirement.
--> It able to allow duplicate elements.
--> It is not following Insertion order.
--> It is following Sorting order.
--> It will not allow null values, if we add null value then JVM will rise an Exception like
java.lang.NullPointerException.
--> It will not allow heterogeneous elements, if we add heterogeneous elements then JVM will
rise an exception like java.lang.ClassCastException.
--> It able to allow only homogeneous elements.
-->It able to allow comparable objects bydefault, if we add non comparable objects then JVM will
rise an exception like java.lang.ClassCastException.
-->If we want to add non comparable objects then we have to use Comparator.
-->It able to manage all elements prior to process.

Methods:
1.public void offer(Object obj)
-->It can be used to insert the specified element to Queue.
2.public Object peek()
-->It can be used to return head element of the Queue.
3.public Object element()
-->It can be used to return head element of the Queue

Note: If we access peek() method on an empty Queue then peek() will return "nll" value. If we access
element() method on an empty Queue then element() method will rise an exception like
java.util.NoSuchElementException
396

4.public Object poll()


Page

-->It can be used to return and remove head element from Queue.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5.public Object remove()
-->It can be used to return and remove head element from Queue.

Note: If we access poll() method on an empty Queue then poll() method will return "null" value.If we
access remove() method on an empty Queue then remove() method will rise an exception like
"java.util.NoSuchElementException".

EX: import java.util.*;


class Test
{
public static void main(String[] args)
{
PriorityQueue q=new PriorityQueue();
q.offer("A");
q.offer("B");
q.offer("C");
q.offer("D");
q.offer("E");
q.offer("F");
System.out.println(q);
System.out.println(q.peek());
System.out.println(q);
System.out.println(q.element());
System.out.println(q);
/*
PriorityQueue q1=new PriorityQueue();
System.out.println(q1.peek());--> Null
System.out.println(q1.element());--> Exception
*/
System.out.println(q.poll());
System.out.println(q);
System.out.println(q.remove());
System.out.println(q);
/*
PriorityQueue q1=new PriorityQueue();
System.out.println(q1.poll());--> Null
System.out.println(q1.remove());-->Exception
*/
}
397

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


PriorityQueue:
--> It was introduced in JDK5.0 version.
--> It is not Legacy Collection.
--> It is a direct implementation class to Queue interface.
--> It able to arrange all the elements prior to processing on the basis of the priorities.
--> It able to allow duplicate elements.
--> It is not following Insertion order.
--> It is following Sorting order.
--> It will not allow null values, if we add null value then JVM will rise an Exception like
java.lang.NullPointerException.
--> It will not allow heterogeneous elements, if we add heterogeneous elements then JVM will
rise an exception like java.lang.ClassCastException.
--> It able to allow only homogeneous elements.
--> It able to allow comparable objects bydefault, if we add non comparable objects then JVM
will rise an exception like java.lang.ClassCastException.
--> If we want to add non comparable objects then we have to use Comparator.
-->Its initial capacity 11 elements.
-->It is not synchronized .
-->No method is synchronized in PriorityQueue.
-->it allows more than one thread at a time to access data.
-->It follows parallel execution.
-->It able to reduce application execution time.
-->It able to improve application performance.
-->It is not giving guarantee for Data consistancy.
-->It is not threadsafe.

398
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Constructors:
1.public PriorityQueue()
--> It able to create an empty PriorityQueue object

EX: PriorityQueue p=new PriorityQueue();

2.public PriorityQueue(int capacity)


-->It can be used to create an empty Queue with the specified capacity.

EX:PriorityQueue p=new PriorityQueue(20);

3.public PriorityQueue(int capacity,Comparator c)


--> It able to create an empty PriorityQueue with explicit sorting logic throug COmparator and the
specified capacity.

EX: MyComparator mc=new MyComparator();


PriorityQueue p=new PriorityQueue(20,mc);

4.public PriorityQueue(SortedSet ss)


--> It able to create PriorityQueue object with all the elements of the specified SortedSet.

EX: TreeSet ts=new TreeSet();


ts.add("B");
ts.add("E");
ts.add("C");
ts.add("A");
ts.add("D");
System.out.println(ts);
PriorityQueue p=new PriorityQueue(ts);
System.out.println(p);

5.public PriorityQueue(Collection c)
-->It able to create PriorityQueue object with all the elements of the specified Collection.
EX:
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
399

System.out.println(al);
PriorityQueue p=new PriorityQueue(al);
Page

System.out.println(p);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
PriorityQueue p=new PriorityQueue();
p.add("A");
p.add("D");
p.add("B");
p.add("C");
p.add("F");
p.add("E");
System.out.println(p);
p.add("B");
System.out.println(p);
//p.add(null);-->NullPointerException
//p.add(new Integer(10));->ClassCastException
//p.add(new StringBuffer("BBB"));->ClassCastException

}
}

Map:
-->It was introduced in JDK1.2 version.
-->It is not chaild interface to Collection interface.
-->It able to arrange all the elements in the form of Key-value pairs.
-->In Map, both keys and values are objects.
-->Duplicates are not allowed at keys , but values may be duplicated.
-->Only one null value is allowed at keys side, but, any no of null values are allowed at values
side.
-->Both keys and Values are able to allow heterogeneous elements.
-->Insertion order is not followed.
-->Sorting order is not followed.
400
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Methods:
1.public void put(Object key, Object value)
-->It will add the specified key-value pair to Map.

2.public void putAll(Map m)


-->It will add all key-value pairs of the specified map to the present Map object.

3.public Object get(Object key)


-->It will return value of the specified key.

4.public Object remove(Object key)


-->It will remove a key-value pair from Map on the basis of the specified key.

5.public int size()


-->It will return number of key-value pairs of a Map

6.public boolean containsKey(Object key)


-->It will check whether the specified key is existed or not at keys side.

7.public boolean cotainsValue(Object key)


-->It will checkk whether the specified value is avaialble or not at values side.

8.public Set keySet()


-->It will return all keys in the form of a Set.

9.public Collection values()


-->It will return all values in the form of a Collection object.

10.public boolean isEmpty()


-->It will check whether the Map object is empty or not, if the present map object is empty then it
will return true value otherwise it will return false value.

401
Page

EX:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("A","AAA");
hm.put("B","BBB");
hm.put("C","CCC");
hm.put("D","DDD");
hm.put("E","EEE");
System.out.println(hm);
HashMap hm1=new HashMap();
hm1.put("X","XXX");
hm1.put("Y","YYY");
System.out.println(hm1);
hm.putAll(hm1);
System.out.println(hm);
System.out.println(hm.get("B"));
System.out.println(hm.remove("E"));
System.out.println(hm.size());
System.out.println(hm.isEmpty());
System.out.println(hm.containsKey("D"));
System.out.println(hm.containsValue("DDD"));
System.out.println(hm.keySet());
System.out.println(hm.values());
}
}

402
Page

HashMap:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->It was introduced in JDK1.2 version.
-->It is not Legacy
-->It is an implementation class to Map interface.
-->It able to arrange all the elements in the form of Key-value pairs.
-->In HashMap, both keys and values are objects.
-->Duplicates are not allowed at keys , but values may be duplicated.
-->Only one null value is allowed at keys side, but, Any no of null values are allowed at values
side.
-->Both keys and Values are able to allow heterogeneous elements.
-->Insertion order is not followed.
-->Sorting order is not followed.
-->Its internal data structer is "Hashtable".
-->Its initial capacity is 16 elements.
-->It is not synchronized
-->No method is syn chronized in HashMap
-->It allows more than one thread to access data.
-->It follows parallel execution.
-->It will reduce application execution time.
-->It will improve application performance.
-->It is not giving guarantee for data consistency.
-->It is not threadsafe.

403
Page

Constructors:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.public HashMap()
2.public HashMap(int capacity)
3.public HashMap(int capacity, float fill_Ratio)
4.public HashMap(Map m)

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("A","AAA");
hm.put("B","BBB");
hm.put("C","CCC");
hm.put("D","DDD");
hm.put("E","EEE");
System.out.println(hm);
hm.put("B","FFF");
System.out.println(hm);
hm.put("F","CCC");
System.out.println(hm);
hm.put(null,"GGG");
hm.put(null,"HHH");
hm.put("G",null);
hm.put("H",null);
System.out.println(hm);
hm.put(new Integer(10), new Integer(20));
System.out.println(hm);
}
}

404
Page

LinkedHashMap:
Q)What are the differences between HashMap and LinkedHashMap?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
1.HashMap was introduced in JDK1.2 version.
LinkedHashMap was itroduced in JDK1.4 version.

2.HashMap is not following insertion order.


LinkedHashMap is following insertion order.

3.HashMap internal data structer is Hashtable.


LinkedHashMap internal data stucter is
Hashtable+LinkedList

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("A","AAA");
hm.put("B","BBB");
hm.put("C","CCC");
hm.put("D","DDD");
hm.put("E","EEE");
System.out.println(hm);

LinkedHashMap lhm=new LinkedHashMap();


lhm.put("A","AAA");
lhm.put("B","BBB");
lhm.put("C","CCC");
lhm.put("D","DDD");
lhm.put("E","EEE");
System.out.println(lhm);
}
} 405
Page

IdentityHashMap:
Q)What are the differences between HashMap and IdentityHashMap?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ans:
1.HashMap was introduced in JDK1.2 version.
IdentityHashMap was introduced in JDK1.4 version.

2.HashMap and IdentityhashMap are not allowing duplicate keys, to check duplicate keys HashMap
will use equals(-) method, but, IdentityHashMap will use '==' operator.

Note: '==' operator will perform references comparision always, but, equals() method was defined in
Object class initially, later on it was overridden in String class and in all wrapper classes inorder to
perform contents comparision.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Integer in1=new Integer(10);
Integer in2=new Integer(10);
HashMap hm=new HashMap();
hm.put(in1,"AAA");
hm.put(in2,"BBB");// in2.equals(in1)-->true
System.out.println(hm);// {10=BBB}

IdentityHashMap ihm=new IdentityHashMap();


ihm.put(in1, "AAA");
ihm.put(in2, "BBB");// in2 == in1 --> false
System.out.println(ihm);// {10=AAA, 10=BBB}
}
}

406
Page

WeakHashMap:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)What is the difference between HashMap and WeakHashMap?

Ans:
Once if we add an element to HashMap then HashMap is not allowing Garbage Collector to destroy
its objects.

Even if we add an element to WeakHashMap then WeakHashMap is able to allow Garbage


Collector to destroy elements.

EX:
import java.util.*;
class A
{
public String toString()
{
return "A";
}
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
HashMap hm=new HashMap();
hm.put(a1, "AAA");
System.out.println("HM Before GC :"+hm);// {A=AAA}
a1=null;
System.gc();
System.out.println("HM After GC :"+hm);// {A=AA}

A a2=new A();
WeakHashMap whm=new WeakHashMap();
whm.put(a2, "AAA");
System.out.println("WHM Before GC :"+whm);// {A=AAA}
a2=null;
System.gc();
System.out.println("WHM After GC :"+whm);// {}

}
}
407
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: In Java applications, Garbage Collector will destroy objects internally. In java applications, it
is possible to destroy objects explicitly by activating GarbageCollector , for this, we have to use the
following two steps.
1.Nullify the respective object reference.
2.Access System.gc() method, it will access
finalize() method internally just before destroying object.

EX:
class A{
A(){
System.out.println("Object Creating");
}
public void finalize(){
System.out.println("Object Destroying");
}
}
class Test{
public static void main(String[] args) {
A a=new A();
a=null;
System.gc();
}
}

SortedMap:
-->It was introduced in JDK1.2 version.
-->It is a direct chaild interface to Map interface
-->It able to allow elements in the form of Key-Value pairs, where both keys and values are
objects.
-->It will not allow duplicate elements at keys side, but, it able to allow duplicate elements at
values side.
-->It will not follow insertion order.
-->It will follow sorting order.
-->It will not allow null values at keys side. If we are trying to add null values at keys side then
JVM will rise an exception like java.lang.NullPointerException.
-->It will not allow heterogeneous elements at keys side, if we are trying add heterogeneous
elements then JVm will rise an exception like java.lang.ClassCastException.
-->It able to allow only comparable objects at keys side bydefault, if we are trying to add non
comparable objects then JVM will rise an exception like java.lang.ClassCastException.
-->If we want to add non comparable objects then we must use Comparator.
408
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Methods:
public Object firstKey()
public Object lastKey()
public SortedMap headMap(Object key)
public SportedMap tailMap(Object key)
public SortedMap subMap(Object obj1, Object obj2)

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeMap tm=new TreeMap();
tm.put("B", "BBB");
tm.put("E", "EEE");
tm.put("D", "DDD");
tm.put("A", "AAA");
tm.put("F", "FFF");
tm.put("C", "CCC");
System.out.println(tm);
System.out.println(tm.firstKey());
System.out.println(tm.lastKey());
System.out.println(tm.headMap("D"));
System.out.println(tm.tailMap("D"));
System.out.println(tm.subMap("B", "E"));
}
}

NavigableMap:
It was introduuced in JAVA6 version, it is a chaild interface to SortedMap and it has defined
methods to provide navigations over the elements.

Methods:
1.public Object CeilingKey(Object obj)
2.public Object higherKey(Object obj)
3.public Object floorKey(Object obj)
4.public Object lowerKey(Object obj)
5.public NavigableMap descendingMap()
6.public Map.Entry pollFirstEntry()
409

7.public Map.Entry pollLastEntry()


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeMap tm=new TreeMap();
tm.put("A", "AAA");
tm.put("B", "BBB");
tm.put("C", "CCC");
tm.put("D", "DDD");
tm.put("E", "EEE");
tm.put("F", "FFF");
System.out.println(tm);
System.out.println(tm.descendingMap());
System.out.println(tm.ceilingKey("D"));
System.out.println(tm.higherKey("D"));
System.out.println(tm.floorKey("D"));
System.out.println(tm.lowerKey("D"));
System.out.println(tm.pollFirstEntry());
System.out.println(tm.pollLastEntry());
System.out.println(tm);
}
}

TreeMap:
-->It was introduced in JDK1.2 version.
-->It is not Legacy.
-->It is an implementation class to Map, SoortedMap and NavigableMap interfaces.
-->It able to allow elements in the form of Key-Value pairs, where both keys and values are
objects.
-->It will not allow duplicate elements at keys side, But, it able to allow duplicate elements at
values side.
-->It will not follow insertion order.
-->It will follow sorting order.
-->It will not allow null values at keys side. If we are trying to add null values at keys side then
JVM will rise an exception like java.lang.NullPointerException.
-->It will not allow heterogeneous elements at keys side, if we are trying add heterogeneous
elements then JVm will rise an exception like java.lang.ClassCastException.
-->It able to allow only comparable objects at keys side bydefault, if we are trying to add non
410

comparable objects then JVM will rise an exception like java.lang.ClassCastException.


-->If we want to add non comparable objects then we must use Comparator.
Page

-->Its internal data Structer is "Red-Black Tree".


-->It is not synchronized.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->No methods are synchronized in TreeMap.
-->It allows more than one thread to access data.
-->It will follow parallel execution.
-->It will reduce execution time.
-->It will improve application performance.
-->It is not giving guarantee for Data Consistency.
-->It is not threadsafe.
Constructors:
1.public TreeMap()
2.public TreeMap(Comparator c)
3.public TreeMap(SortedMap sm)
4.public TreeMap(Map m)

EX: import java.util.*;


class Test
{
public static void main(String[] args)
{
TreeMap tm=new TreeMap();
tm.put("A", "AAA");
tm.put("B", "BBB");
tm.put("C", "CCC");
tm.put("D", "DDD");
System.out.println(tm);
tm.put("B", "EEE");
System.out.println(tm);
tm.put("E", "CCC");
System.out.println(tm);
//tm.put(null, "EEE");-->NullPointerException
tm.put("F",null);
System.out.println(tm);
//tm.put(new Integer(10), new Integer(20));-->CCE
System.out.println(tm);
tm.put("G", new Integer(20));
System.out.println(tm);
//tm.put(new StringBuffer("BBB"), "GGG");-->CCE
tm.put("H", new StringBuffer("HHH"));
System.out.println(tm);

}
411

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Hashtable:

Q)What are the differences between HashMap and Hashtable?

Ans:
1.HashMap was introduced in JDK1.2 version.
Hashtable was introduced in JDK1.0 version.

2.HashMap is not Legacy.


Hashtable is Legacy.

3.In HashMap, one null value is allowed at keys side and any no of null values are allowed at
values side.
In case of Hashtable, null values are not allowed at both keys and values side.

4.HashMap is not synchronized.


Hashtable is synchronized.

5.No method is synchronized in HashMap.


Almost all the methods are synchronized in Hashtable

6.HashMap allows more than one thread to access data.


Hashtable allows only one thread at a time to access data.

7.HashMap follows parallel execution.


Hashtable follows sequential execution.

8.HashMap will reduuce execution time.


Hashtable will increase execution time.

9.HashMap will improve application performance.


Hashtable will reduce application performance.

10.HashMap will not give guarantee for data consistency.


Hashtable will give guarantee for data consistency

11.HashMap is not threadsafe.


Hashtable is threadsafe.
412
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("A", "AAA");
hm.put("B", "BBB");
hm.put("C", "CCC");
hm.put("D", "DDD");
System.out.println(hm);
hm.put(null, "EEE");
hm.put(null, "FFF");
hm.put("E",null);
hm.put("F", null);
System.out.println(hm);
System.out.println();
Hashtable ht=new Hashtable();
ht.put("A", "AAA");
ht.put("B", "BBB");
ht.put("C", "CCC");
ht.put("D", "DDD");
System.out.println(ht);
//ht.put(null, "EEE");-->NullPointerException
//ht.put("E", null);-->NullPointerException

}
}

Properties:
In java applications, if we have any data which we want to change frequently then we have to
manage that type of data in a properties file, otherwise we have to perform recompilation on every
modification.

The main purpose of properties files in java applications is,


1.To manage labels of the GUI components in GUI appl.
2.To manage locale respective messages in I18N Appl.
3.To manage exception messages in Exception handling.
4.To manage validation messages in Data validations.
413
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
user.properties

uname=User Name
upwd=User password
uname.required=User Name is Required
upwd.required=User Password is required
exception.insufficientfunds=Funds are not sufficient in your Account.

In java applicatioons, to repersent data of a particular properties file we have to use java.util.Properties
class.

To get data from a particular properties file to Properties object we have to use the following steps.
1.Create Properties file with the data in the form of Key-value pairs.
2.Create Properties class object.
3.Create FileInputStream to get data from properties file.
4.Load data from FileInputStream to Properties object by using the following method.
public void load(FileInputStream fis)
5.Get data from Properties object by using the following method.
public String getProperty(String key)

To send data from Properties object to properties file we have to use the following steps.
1.Create Properties class object.
2.Set data to Properties object by using the following method.
public void setProperty(String key, String val)
3.Create FileOutputStream with the target file.
4.Store Properties object data to FileOutputStream by using the following method.
public void store(FileOutputStream fos, String des)

db.properties
driver_Class=sun.jdbc.odbc.JdbcOdbcDriver
driver_URL=jdbc:odbc:dsn_name
db_User=system
db_Password=durga
414
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Test.java
import java.util.*;
import java.io.*;
class Test
{
public static void main(String[] args)throws Exception
{
Properties p=new Properties();
FileInputStream fis=new FileInputStream("db.properties");
p.load(fis);
System.out.println("JDBC Parameters");
System.out.println("--------------------");
System.out.println("Driver_Class :"+p.getProperty("driver_Class"));
System.out.println("Driver_URL :"+p.getProperty("driver_URL"));
System.out.println("DB_User :"+p.getProperty("db_User"));
System.out.println("DB_PAssword :"+p.getProperty("db_Password"));
}
}

Test1.java
import java.util.*;
import java.io.*;
class Test1
{
public static void main(String[] args)throws Exception
{
Properties p=new Properties();
p.setProperty("uname","Durga");
p.setProperty("upwd", "durga123");
p.setProperty("uqual", "M Tech");
p.setProperty("uemail", "durga@durgasoft.com");
p.setProperty("umobile","91-9988776655");

FileOutputStream fos=new FileOutputStream("user.properties");


p.store(fos,"User Details");
}
}
415
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


GUI[Graphical User Interface]
By using Java programming language, we are able to prepare the following two types of applications.

1.CUI Applications
2.GUI Applications

Q)What is the difference between CUI Application and GUI Application?

Ans:
CUI Application is a java application, it would be desinged in such a way that ti take input from
command prompt and to provide output on the same command prompt, where command prompt is
acting as an user interface and it is supporting characters data.

GUI Application is a java application, it would be designed in such a way that to take input from the
collection of Graphics components and to provide output on the same collection of Graphics
components, where the collection of graphics components is acting an user interface and it is
supporting graphics data.

To prepare GUI Applications, JAVA has provided the complete predefined library in the form of the
following three packages.

java.awt
java.applet
javax.swing

AWT[Abstract Windowing Toolkit]

AWT is a toolkit or collection of predefined classes and interfaces to design GUI Applications.

AWT is a framework, it can be used to prepare Desktop applications.

AWT is an API, it can be used to prepare Window based applications.

TO prepare GUI applications, AWT is able to provide support for the following GUI components.

To represent the above GUI components, java.awt package has provided the following predefined
classes.
416
Page

Frame:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Frame is a container , it able to manage some other GUI components.

To repersent Frame in GUI applications, JAVA has provided a seperate predefiend class in the form of
java.awt.Frame.

To create Frame class object we have to use the following constructor from Frame class.

public Frame()
--> It will create a Frame with out title.

public Frame(String title)


--> It will create a Frame with the specified title.

In GUI applications, when we create Frame then Frame will be created with invisible mode, where to
give visibleness to the Frame we will use the following methods.

public void show()


--> It able to show the frame , it unable to hide frame and this method is deprecated method.

public void setVisible(boolean b)


--> If b is true then it will provide visibleness to the Frame, if b is false then it will hide Frame.

In GUI applications, when we create Frame then Frame will be created with 0 width and 0 hight,
where to provide size to the Frame explicitly we have to use the following method.

public void setSize(int width, int hight)

To set a particular title to the Frame explicitly we have to use the following method.

public void setTitle(String title)

To set a particular background color to the frame we have to use the following method.

public void setBackground(Color clr)


417
Page

EX: import java.awt.*;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public class FrameEx
{
public static void main(String[] args)
{
Frame f=new Frame();
//f.show();
f.setVisible(true);
f.setSize(500,500);
f.setTitle("Frame Demo");
f.setBackground(Color.green);
}
}

In GUI applications, above approach is not suggestible to create Frames, because, we are unable to
perfrom customizations over the Frame. To implement customizations over the Frame we have to
create user defined Frames.
To create User defined frames we have to use the following steps.
1.Declare an user defined class.
2.Extend User defined class from java.awt.Frame class.
3.Declare a 0-arg constructor in user defined class.
4.Provide all Frame properties in User defined class constructor.
5.In main class, in main() method, create object for user defined Frame class.

EX: import java.awt.*;


class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Custom Frame Example");
this.setBackground(Color.red);
}
}
class CustomFrameEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
418

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we want to display textual data on frame then we have to override paint(-) method provided by
Frame class.
public void paint(Graphics g)
To define Font properties , java has provided a predefined class in the form of java.awt.Font , to craete
object for Font class we have to use the following copnstructor.
public Font(String font_Type, int font_Style, int font_Size).

To set foreground color to the Frame we have to use the following methode from java.awt.Frame class.
public void setForeground(Color clr)
To set Font properties to the Graphics object we have to use the following method.
public void setFont(Font f)

NOTE: When we create user defined Frame class object, JVM has to access superr class 0-arg
constructor, that is, Frame class 0-arg constructor, where in Frame class 0-arg constructor JVM will
access repaint(-) method, where repaint() method will access paint() method.

EX:
import java.awt.*;
class LogoFrame extends Frame
{
LogoFrame()
{
this.setVisible(true);
this.setSize(700,400);
this.setTitle("Paint Example");
this.setBackground(Color.green);
}
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD+Font.ITALIC, 35);
g.setFont(f);
this.setForeground(Color.red);
g.drawString("DURGA SOFTWARE SOLUTIONS", 100,100);
}
}
class PaintEx
{
public static void main(String[] args)
{
LogoFrame lf=new LogoFrame();
419

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Event Handling / Event Delegation Model:
In GUI applications, we may use the GUI components like Buttons, Check boxes, radio Buttons,....
When we click on button or select item in check box,.. the respective GUI components are able to
rise the respective events, here GUI components are not capable to handle the generated events. In
this context, to handle the generated events we have to use another component internally that is
Listener.

In GUI applications, Listers will take events from GUI components , handle them , perform the
required actions by executing listener methods and return the result back to GUI application. Here ,
the process delegating events from GUI components to Listeners inorder to handle is called as
"Event Delegation Model" or Event Handling.

To implement Event handling in GUI applications, JAVA has provided the following predefined
library as part of
"java.awt.event" package.

Procedure to implement Event Handling in GUI Applications:


1.Declare container class as sub class to java.awt.Frame class.
2.Declare a 0-arg constructor in container class.
3.Create the required GUI component in container class constructor.
4.Select Listener on the basis of GUI Component.
5.Declare an impementaton class for Listener interface.
6.Provide implementation for all Listener interface methods in Listener implementation class as
per the requirement.
7.Add Lisyener to the resapective GUI Component by using the following method.
public void adXXXListener(XXXListener l)
Where XXXListener may be ActionListener, ItemListener,...

NOTE: In GUI Applications, in general, we will take container class as implementation class for
Listener interfase, in the same container class Listener interface methods must be implemented.

420
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class MyFrame extends Frame// Conmtainer class
{
MyFrame()// Constuctor
{
Button b=new Button("Submit");// GUI Comp.
b.addActionListener(new MyActionListenerImpl());
} // Adding Listener to GUI Component
}

class MyActionListenerImpl implements ActionListener


{// Listener Implementation class and Listener methods impl
public void actionPerformed(ActionEvent ae)
{
----implementation-----
}
}

EX:
import java.awt.*;
import java.awt.event.*;
class WindowListenerImpl implements WindowListener
{
public void windowOpened(WindowEvent we)
{
System.out.println("WindowOpened");
}
public void windowClosed(WindowEvent we)
{
System.out.println("WidnowClosed");
}
public void windowClosing(WindowEvent we)
{
System.out.println("WidnowClosing");
System.exit(0);
}
public void windowIconified(WindowEvent we)
{
System.out.println("WidnowIconified");
}
421

public void windowDeiconified(WindowEvent we)


{
Page

System.out.println("windowDeiconified");
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public void windowActivated(WindowEvent we)
{
System.out.println("WidnowActivated");
}
public void windowDeactivated(WindowEvent we)
{
System.out.println("WindowDeactivated");
}
}
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Window Events Example");
this.setBackground(Color.green);
this.addWindowListener(new WindowListenerImpl());
}
}
class WindowEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}

In Window Events, if we want to provide only window closing option to the frame then we have to use
only
windowClosing() method in the above implementation. To provide only windowClosing() method if
we implement WindowListener interface then we must provide implementation for all the methods of
WindowListener interface, this approach will increase unneccessary methods implementations in GUI
Applications.

To overcome the above problem, to avoid unneccessary methods implementations AWT has provided
an adapter class in the form of "java.awt.event.WindowAdapter abstract class.

java.awt.event.WindowAdapter abstract class is a direct implementation abstract class to


WindowListener interface and it has provided empty implementation [ { } ] for all the methods of
422

WindowListener interface.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we want to use WindowAdapter abstract class in GUI Applications then we have to declare an user
defined class and it must extend java.awt.event.WindowAdapter abstract class , where we have to
override the requred method.

EX:
import java.awt.*;
import java.awt.event.*;
class WindowListenerImpl extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Window Events Example");
this.setBackground(Color.green);
this.addWindowListener(new WindowListenerImpl());
}
}
class WindowEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}

To provide window closing option to the frame if we use the above approach then we have to provide
a seperate class for implementing windowClosing(-) method, it will increase no of classes in GUI
applications, here to remove this type of unneccessary classes we have to use anonymous inner class of
WindowAdapter abstract class as parameter to addWindowListener(-) method directly.
423
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Window Events Example");
this.setBackground(Color.green);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
class WindowEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}

EX:
import java.awt.*;
import java.awt.event.*;
class MouseListenerImpl implements MouseListener
{
public void mousePressed(MouseEvent me)
{
System.out.println("Mouse Pressed["+me.getX()+","+me.getY()+"]");
}
public void mouseReleased(MouseEvent me)
{
System.out.println("Mouse Released["+me.getX()+","+me.getY()+"]");
424

}
public void mouseClicked(MouseEvent me)
Page

{
System.out.println("Mouse Clicked["+me.getX()+","+me.getY()+"]");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
public void mouseEntered(MouseEvent me)
{
System.out.println("Mouse Entered["+me.getX()+","+me.getY()+"]");
}
public void mouseExited(MouseEvent me)
{
System.out.println("Mouse Exited["+me.getX()+","+me.getY()+"]");
}
}
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Mouse Events Example");
this.setBackground(Color.yellow);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

this.addMouseListener(new MouseListenerImpl());
}
}
class MouseEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}
425
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: import java.awt.*;
import java.awt.event.*;
class KeyListenerImpl implements KeyListener
{
public void keyPressed(KeyEvent ke)
{
System.out.println("KeyPressed["+ke.getKeyChar()+"]");
}
public void keyTyped(KeyEvent ke)
{
System.out.println("KeyTyped["+ke.getKeyChar()+"]");
}
public void keyReleased(KeyEvent ke)
{
System.out.println("KeyReleased["+ke.getKeyChar()+"]");
}
}
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Key Events Example");
this.setBackground(Color.green);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
this.addKeyListener(new KeyListenerImpl());
}
}
class KeyEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
426

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Layout Mechanisms:
The main purpose of Layout mechanism is to arrange all the GUI components in container in a
particular order.

There are five layout mechanisms in AWT.


1.FlowLayout
2.BorderLayout
3.GridLayout
4.GridbagLayout
5.CardLayout

To set a particular Layout mechanism to the Container we have to use the following method.

public void setLayout(XXXLayout l)


Where XXXLayout may be FlowLayout, BorderLayout,.....

1.FlowLayout:
It able to arrange all the GUI components in rows manner.
To repersent this Layout mechanism AWT has provided a predefined class in the form of
java.awt.FlowLayout.

To set flow layout to the Frame we have to use the following instruction.

f.setLayout(new FlowLayout());

2.BorderLayout:
It able to arrange GUI components along with borders of the containers.

To repersent this Layout mechanism AWT has provided a predefined class in the form of
java.awt.BorderLayout .

To set this layout mechanism, we have to use the following instruction.

f.setLayout(new BorderLayout());

To repersents the locations in container , BorderLayout class has provided the constants like EAST,
NORTH, SOUTH, WEST, CENTER.

In case of Border layout , if we want to add the elements to the container we have to use the
427

following method.
Page

public void add(int location, Component c)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: f.add(BorderLayout.CENTER, new WelcomePanel());

3.GridLayout:
It able to arrange all the GUI components in rows and columns wise in the form of grids.

To represent this layout mechanism, AWT has provided a predefined class in the form of
java.awt.GridLayout.

To set Grid layout mechanism we have to use the following instruction.

f.setLayout(new GridLayout(4,4));
Where 4 , 4 is no of rows and no columns.

If we want to use GridLayout in GUI applications then we must follow the following rules.
1.All the GUI components must have equals size.
2.We must not leave any empty grid in between GUI components.

4.GridbagLayout:
This layout mechanism is almost all same as GridLayout, but, it able to allow empty grids between
the components and it able to allow the GUI components having variable sizes.

To represent this layout mechanism, AWT has provided a predefined class in the form of
java.awt.GridbagLayout.

To use this layout mechanism we have to use the following instruction.

f.setLayout(new GridbagLayout(3,3));

5.Card Layout:
It able to arrange all the elements in the form of cards which are available in overlapped manner.

To represent this layout , AWT has provided a predefined class in the form of java.awt.cardLayout.

To use this layout mechanism we have to use the following code.

f.setLayout(new CardLayout(4));
Where 4 is no of cards.
428
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Label:
It is an output GUI component, it able to display a line of data on Frame.

To represent Label GUI component AWT has provided a predefined class in the form of
java.awt.Label.

To create Object for Label class we ahev to use the following constructors.

public Label()
public Label(String label)
public Label(String label, int alignment)
Where alignment may be the constants like LEFT, RIGHT, CENTER from Label class.

Button:
It is an output GUI component, it able to generate ActionEvent inorder to perform a particular
Action.

To repersent this GUI component AWT has provided a predefined class in the form of
"java.awt.Button".

To create Button class objects we have to use the following constructors.

public Button()
public Button(String label)

To set label to the button and to get label from Button we have to use the following methods.

public void setLabel(String label)


public String getLabel()

To get clicked button label among the multiple buttons we have to use the following method.

public String getActionCommand()

429
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.awt.*;
import java.awt.event.*;
class ColorsFrame extends Frame implements ActionListener
{
Button b1, b2, b3;
ColorsFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Colors Frame");
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

b1.setBackground(Color.red);
b2.setBackground(Color.green);
b3.setBackground(Color.blue);

this.add(b1);
this.add(b2);
this.add(b3);

}
public void actionPerformed(ActionEvent ae)
{
String label=ae.getActionCommand();
430

if(label.equals("Red"))
{
Page

this.setBackground(Color.red);
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


if(label.equals("Green"))
{
this.setBackground(Color.green);
}
if(label.equals("Blue"))
{
this.setBackground(Color.blue);
}
}
}
class ButtonEx
{
public static void main(String[] args)
{
ColorsFrame cf=new ColorsFrame();
}
}

TextField:
It is an input GUI coponent, it able to take a single line of data from User.

To repersent this GUI component , AWT has provided a predefined class in the form of
"java.awt.TextField".

To create TextField class object we have to use the following constructors.

public TextField()
public TextField(int size)
public TextField(String def_msg, int size)

To set data to the TextField and to get data from Text field we have to use the following methods.

public void setText(String text)


public String getText()
431
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


TextArea:
It is an input GUI component, it able to take multiple lines of data from user.

To represent this GUI component, AWT has provided a predefined class in the form of
"java.awt.TextArea".

To create TextArea class object AWT has provided the following constructors.

public TextArea()
public TextArea(int rows, int columns)
public TextArea(String def_Message, int rows, int cols)

To set data to Text Area and to get data from Text Area we have to use the following methods.

public void setText(String text)


public String getText()

NOTE:If we want to prepare Password field in GUI applications then we have to take a text filed,
where we have to hide data with a particular character called as Echo Character, where to set a
particular Echo Character we have to use the following method.

public void setEchoChar(char c)

EX:
import java.awt.*;
import java.awt.event.*;
class UserFrame extends Frame implements ActionListener
{
Label l1, l2, l3, l4, l5;
TextField tf1, tf2, tf3, tf4;
TextArea ta;
Button b;

String uname="";
String upwd="";
String uemail="";
String umobile="";
String uaddr="";

UserFrame()
432

{
this.setVisible(true);
Page

this.setSize(500,500);
this.setTitle("User Frame");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

l1=new Label("User Name");


l2=new Label("Password");
l3=new Label("User Email");
l4=new Label("User Mobile");
l5=new Label("User Address");

tf1=new TextField(20);
tf2=new TextField(20);
tf2.setEchoChar('*');
tf3=new TextField(20);
tf4=new TextField(20);

ta=new TextArea(3,15);
b=new Button("Registration");
b.addActionListener(this);

Font f=new Font("arial", Font.BOLD,15);


l1.setFont(f);
l2.setFont(f);
l3.setFont(f);
l4.setFont(f);
l5.setFont(f);
tf1.setFont(f);
tf2.setFont(f);
tf3.setFont(f);
tf4.setFont(f);
ta.setFont(f);
b.setFont(f);

this.add(l1); this.add(tf1);
433

this.add(l2); this.add(tf2);
this.add(l3); this.add(tf3);
Page

this.add(l4); this.add(tf4);
this.add(l5); this.add(ta);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


this.add(b);

}
public void actionPerformed(ActionEvent ae)
{
uname=tf1.getText();
upwd=tf2.getText();
uemail=tf3.getText();
umobile=tf4.getText();
uaddr=ta.getText();
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD, 20);
g.setFont(f);
g.drawString("User Name :"+uname,50,250);
g.drawString("Password :"+upwd,50,300);
g.drawString("User Email :"+uemail,50,350);
g.drawString("User Mobile :"+umobile,50,400);
g.drawString("User Address :"+uaddr,50,450);
}
}
class TextFieldEx
{
public static void main(String[] args)
{
UserFrame uf=new UserFrame();
}
}

434
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Checkbox:
It is an input GUI component, it can be used to select an item represented by the present Checkbox.

To represent this GUI component AWT has provided a predefined class in the form of
"java.awt.Checkbox".

To create Checkbox class objects we have to use the following constructors

public Checkbox()
public Checkbox(String label)
public Checkbox(String label, boolean state)
public Checkbox(String label, CheckboxGroup cg, boolean state)

To set label to the Checkbox and to get label from Check box we have to use the following methods.

public void setLabel(String label)


public String getLabel()

To get current state of the check box and to set a particular state to check box we have to use the
following methods.

public void setState(boolean b)


public boolean getState()

Radio:
It is an input GUI component, it able to allow to select an item.

In general, Checkboxes are able to allow multiple selections , but, Radio button is able to allow single
selection.

To create radio buttons we have to use Checkbox class object with CheckboxGroup object reference.

EX:
CheckboxGroup cg=new CheckboxGroup();
Checkbox cb1==new Checkbox("Male", cg, false);
Checkbox cb2==new Checkbox("Female", cg, false);
435
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To set label to checkbox and to get label from Checkbox we have to use the following methods.

public void setLabel(String label)


public String getLabel()

To set a particular state to the checkbox and to get current state from checkbox we have to use the
following methods.

public void setState(boolean b)


public boolean getState()

EX:
import java.awt.*;
import java.awt.event.*;
class UserFrame extends Frame implements ItemListener
{
Label l1, l2;
Checkbox cb1, cb2, cb3, cb4, cb5;
String uqual="";
String ugender="";

UserFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Check Box Example");
this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{

System.exit(0);
}
});

l1=new Label("User Qualifications");


l2=new Label("User Gender");
cb1=new Checkbox("BSC",null, false);
436

cb2=new Checkbox("MCA",null, false);


cb3=new Checkbox("PHD",null, false);
Page

CheckboxGroup cg=new CheckboxGroup();


cb4=new Checkbox("Male",cg, false);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


cb5=new Checkbox("Female",cg, false);

cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
cb4.addItemListener(this);
cb5.addItemListener(this);

Font f=new Font("arial", Font.BOLD, 15);


l1.setFont(f);
l2.setFont(f);
cb1.setFont(f);
cb2.setFont(f);
cb3.setFont(f);
cb4.setFont(f);
cb5.setFont(f);

this.add(l1);
this.add(cb1);
this.add(cb2);
this.add(cb3);
this.add(l2);
this.add(cb4);
this.add(cb5);
}
public void itemStateChanged(ItemEvent ie)
{
if(cb1.getState() == true)
{
uqual=uqual+cb1.getLabel()+" ";
}
if(cb2.getState() == true)
{
uqual=uqual+cb2.getLabel()+" ";
}
if(cb3.getState() == true)
{
uqual=uqual+cb3.getLabel()+" ";
}
if(cb4.getState() == true)
437

{
ugender=cb4.getLabel();
Page

}
if(cb5.getState() == true)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
ugender=cb5.getLabel();
}
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD, 30);
g.setFont(f);
g.drawString("Qualifications :"+uqual, 50, 300);
g.drawString("Gender :"+ugender, 50, 350);
uqual="";
}
}
class CheckBoxEx
{
public static void main(String[] args)
{
UserFrame uf=new UserFrame();
}
}

List:
It is an input GUI component, It able to repersent more than one element to select.

To represent this GUI component AWT has provided a predefined class java.awt.List

To create List class object we have to use the following constructors.

public List()
public List(int size)
public List(int size, boolean b)

To add an item to List we have to use the following method.


public void add(String item)

To get the selected item from List we have to use the following method.
public String getSelectedItem()

To get the selected items from List we have to use the following method.
438

public String[] getSelectedItems()


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Choice:
List is able to allow more than one item selection but Choice is able to allow only one item
selection.
To represent this GUI component AWT has provided a predefined class in the form of
java.awt.Choice.
To create Object for Choice class we have to use the following constructor.
public Choice()
To add an item to Choice object we have to use the following method.
public void add(String item)

To get the selected item from Choice we have to use the following method.

public String getSelectedItem()

EX:
import java.awt.*;
import java.awt.event.*;
class UserFrame extends Frame implements ItemListener
{
Label l1, l2;
List l;
Choice ch;
String utech="";
String uprof="";

UserFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("List Example");
this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
439

l1=new Label("User Technologies");


l2=new Label("User Profession");
Page

l=new List(4,true);
l.add("C");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


l.add("C++");
l.add("JAVA");
l.add(".NET");
l.add("Oracle");
l.addItemListener(this);

ch=new Choice();
ch.add("Student");
ch.add("Employee");
ch.add("Teacher");
ch.addItemListener(this);

this.add(l1); this.add(l);
this.add(l2); this.add(ch);

}
public void itemStateChanged(ItemEvent ie)
{
String[] items=l.getSelectedItems();
for(int i=0;i<items.length;i++)
{
utech=utech+items[i]+" ";
}
uprof=ch.getSelectedItem();
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD, 30);
g.setFont(f);
g.drawString("Technologies :"+utech, 50, 300);
g.drawString("Profession :"+uprof, 50, 350);
utech="";
}
}
class ListEx
{
public static void main(String[] args)
{
UserFrame uf=new UserFrame();
440

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Menu:
This GUI component is able to provide a list of items to select.

To repesent Menu in GUI applicatins, AWT has provided a set of predefined classes like
java.awt.MenuBar, java.awt.Menu and java.awt.MenuItem.

To use menu in GUI applications we have to use the following steps.

1.Create MenuBar and Add MenuBar to Frame.


2.Create Menu and add Menu to MenuBar.
3.Create MenuItems and add MenuItems to Menu.

EX:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{
MenuBar mb;
Menu m;
MenuItem mi1, mi2, mi3;
String item="";

MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Menu Example");
this.setBackground(Color.green);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

mb=new MenuBar();
this.setMenuBar(mb);

m=new Menu("File");
441

mb.add(m);
Page

mi1=new MenuItem("New");
mi2=new MenuItem("Open");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


mi3=new MenuItem("Save");
m.add(mi1);
m.add(mi2);
m.add(mi3);

mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
item=ae.getActionCommand();
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD, 30);
g.setFont(f);
g.drawString("Selected Item :"+item, 50, 300);
}
}
class MenuEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}

Scrollbar:
It able to move frame top to bottom or left to right inorder to visible the components.

To represent Scroll bar AWT has provided a predefined class in the from of java.awt.Scarollbar.

To prepare Scrollbar class object we have to use the following constgructor.

public Scrollbar(int type)


Where type may be VERTICAL or HORIZONTA constants from Scrollbar class.
442
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: Scrollbar is able to rise AdjustmentEvent and which is handled by AdjustmentListener by
executing adjustmentValueChanged(--) method.

EX:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements AdjustmentListener
{
Scrollbar sb;
int position;

MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Scrollbar Example");
this.setLayout(new BorderLayout());
this.setBackground(Color.green);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

sb=new Scrollbar(Scrollbar.VERTICAL);
sb.addAdjustmentListener(this);

this.add(BorderLayout.EAST, sb);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
position=sb.getValue();
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD, 30);
g.setFont(f);
443

g.drawString("Position :"+position, 50, 300);


}
Page

}
class ScrollBarEx

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}

Applets:
Applet is a container, it able to manage some other GUI components.

To represent Applet, JAVA has provided a predefined class in the from of java.applet.Applet .

If we want to use Applets in GUI applications then we have to use the following steps.

1.Create Applet class


2.Create Applet Configuration File
3.Execute Applet

1.Create Applet class


a)Declare an user defined class
b)Extend java.applet.Applet class to user defined class.
c)In user defined Applet class, override Applet lifecycle methods like

public void init()


public void start()
public void stop()
publc void destroy()

2.Create Applet Configuration File

The main intentin of Applet configuratino file is to declare Applet class and its location and to
declare size of the Applet,.....

Applet configuratin file is an html file , which includes, <applet> tag.

Syntax:
<applet code="---" width="--" height="--">
</applet>
Where "code" attribute will take the name and location of the Applet class.
Where "width" and "hight" attributes are used to take applet size.
444
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.Execute Applet:
There are two approaches to execute Applets.
1.Use "appletviewer" command on command prompt.

EX: D:\java830>appletviewer MyApplet.html

2.Use browser to execute Applet:


In this case, open Applet configuration file in browser.

NOTE:In general, Applets are executed by following Applet lifecycle only, Applets are not having
main() method to execute.

---Diagram-----

LogoApplet.java
import java.awt.*;
import java.applet.*;
public class LogoApplet extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("arial", Font.BOLD, 30);
g.setFont(f);
g.drawString("DURGA SOFTWARE SOLUTIONS",100,100);
}
}

LogoApplet.html
<applet code="LogoApplet" width="700" height="500">
</applet>

On Command Prompt
D:\java830>javac LogoApplet.java
D:\java830>appletviewer LogoApplet.html 445
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


SWING:
Swing is a package in java , it able to provide all GUI components to prepare GUI applications.

Q)What are the differences between AWT and SWING?


Ans:
1.AWT GUI components are platform dependent GUI components.

SWING GUI Components are platform Independent GUI Components.

2.AWT GUI Components are able to follow the local operating system provided Look And Feel, it
is fixed upto the present operating syste,.

SWING GUI components are having Pluggable Look And Feel nature irrespective of the operating
system which we used.

3.AWT GUI components are Heavy Weight GUI components, they will more execution time and
much meory.

Swing GUI compoents are light weight GUI components, they will take less memory and less
execution time.

4.AWT GUI compnents are able to provide less performance in GUI applications.

SWING GUI components are able to provide very good performance in GUI applicatins.

5.AWT GUI components are PEER GUI components, for every GUI component a seperate
duplicate component is created at Operating System.

SWING GUI components are not PEER Gui components , no seperate duplicate component will be
created at Operating System .

6.AWT is not following MVC[Model-View-Controller] design pattern internally todesign GUI


applications.

SWING is following MVC design pattern to design GUI applications.

7.AWT is not providing tool tip text support.

SWING is providing Tool Tip Text Support


446

8.In AWT, we are able to add all the GUI components to Frame directly.
Page

In SWING, we are able to add all the GUI components to the Panes .

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: There are four types of Panes in SWING
1.RootPane
2.LayeredPane
3.ContentPane
4.GlassPane.
In SWING we will use mainly ContentPane to manage GUI components , where to get CntentPane we
have to use the following method.

public Container getContentPane()

To repersent all GUI components in SWING , javax.swing package has provided the following
predefined classes.
NOTE:
To clode Frames in AWT we have to use WindowListener implementation class or WindowAdapter
abstract class or Anonymous inner class of WindowAdapter abstract class. In case of SWING to
provide window closing option to the Frame we have to use the following instuction .

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

EX:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class RegistrationFrame extends JFrame implements ActionListener
{
JLabel l1,l2,l3,l4,l5,l6,l7;
JTextField tf;
JPasswordField pf;
JCheckBox cb1,cb2,cb3;
JRadioButton rb1,rb2;
JList l;
JComboBox cb;
JTextArea ta;
JButton b;

Container c;
String uname="",upwd="",uqual="",ugen="",utech="",uprof="",uaddr="";
RegistrationFrame()
{
447

this.setVisible(true);
this.setSize(500,600);
Page

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=getContentPane();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


c.setBackground(Color.cyan);
//this.setForeground(Color.red);
c.setLayout(null);
l1=new JLabel("User Name");
l1.setBounds(50,100,100,10);
l2=new JLabel("Password");
l2.setBounds(50,150,100,10);
l3=new JLabel("Qualification");
l3.setBounds(50,200,100,10);
l4=new JLabel("Gender");
l4.setBounds(50,250,100,10);
l5=new JLabel("Technologies");
l5.setBounds(50,300,100,10);
l6=new JLabel("Proffession");
l6.setBounds(50,350,100,10);
l7=new JLabel("Address");
l7.setBounds(50,400,100,10);

tf=new JTextField(20);
tf.setBounds(150,90,100,30);
tf.setToolTipText("This Is Text Field");

pf=new JPasswordField(20);
pf.setBounds(150,140,100,30);
pf.setToolTipText("This Is Password Field");

cb1=new JCheckBox("BSC");
cb1.setBounds(150,190,60,30);
cb2=new JCheckBox("MCA");
cb2.setBounds(220,190,60,30);
cb3=new JCheckBox("PHD");
cb3.setBounds(290,190,60,30);

rb1=new JRadioButton("Male");
rb1.setBounds(150,240,80,30);
rb2=new JRadioButton("Female");
rb2.setBounds(250,240,80,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
448

String[] techs={"C","C++","JAVA"};
Page

l=new JList(techs);
l.setBounds(150,280,60,60);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String[] prof={"Student","Business","Teacher"};
cb=new JComboBox(prof);
cb.setBounds(150,340,80,30);

ta=new JTextArea(5,25);
ta.setBounds(150,380,100,40);

b=new JButton("Registration");
b.setBounds(50,450,110,40);
b.addActionListener(this);

c.add(l1);c.add(tf);
c.add(l2);c.add(pf);
c.add(l3);c.add(cb1);c.add(cb2);c.add(cb3);
c.add(l4);c.add(rb1);c.add(rb2);
c.add(l5);c.add(l);
c.add(l6);c.add(cb);
c.add(l7);c.add(ta);
c.add(b);
}
public void actionPerformed(ActionEvent ae)
{
uname=tf.getText();
upwd=pf.getText();
if(cb1.isSelected()==true)
{
uqual=uqual+cb1.getLabel()+" ";
}
if(cb2.isSelected()==true)
{
uqual=uqual+cb2.getLabel()+" ";
}
if(cb3.isSelected()==true)
{
uqual=uqual+cb3.getLabel()+" ";
}
if(rb1.isSelected()==true)
{
ugen=rb1.getLabel();
449

}
if(rb2.isSelected()==true)
Page

{
ugen=rb2.getLabel();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
Object[] techs=l.getSelectedValues();
for(int i=0;i<techs.length;i++)
{
utech=utech+techs[i]+" ";
}
uprof=(String)cb.getSelectedItem();
uaddr=ta.getText();

class DisplayFrame extends JFrame


{
DisplayFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setBackground(Color.pink);

}
public void paint(Graphics g)
{
Font f=new Font("arial",Font.BOLD,25);
g.setFont(f);
g.drawString("User Name :"+uname,50,100);
g.drawString("Password :"+upwd,50,150);
g.drawString("Qualification :"+uqual,50,200);
g.drawString("User Gender :"+ugen,50,250);
g.drawString("Technologies :"+utech,50,300);
g.drawString("Proffession :"+uprof,50,350);
g.drawString("Address :"+uaddr,50,400);
}
}
DisplayFrame df=new DisplayFrame();
}
}
class RegistrationApp
{
public static void main(String[] args)
{
RegistrationFrame rf=new RegistrationFrame();
450

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JColorChooser:
It is a swing specific GUI component, it able to display grids of colors to select.

To repersent this GUI component, SWING has provided a predefined class in the form of
javax.swing.JColorChooser.

T0 cereate JColorChooser class object we have to use the following constructor.

public JColorChooser()

To get the current SelectionModel from JColorChooser we have to use the following method.

public SelectionModel getSelectionModel()

In GUI applications, JColorChooser is able to rise ChangeEvent and it will be handled by


ChangeListener by executing the following method.

pblic void stateChanged(ChangeEvent ce)

To get the selected color from JColorChooser we have to use the following method.

public Color getColor()

EX:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class ColorChooserFrame extends JFrame implements ChangeListener
{
JColorChooser cc;
Container c;
ColorChooserFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();

cc=new JColorChooser();
451

cc.getSelectionModel().addChangeListener(this);
c.setLayout(new FlowLayout());
Page

c.add(cc);
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public void stateChanged(ChangeEvent ce)
{
Color clr=cc.getColor();
JFrame f=new JFrame();
f.setVisible(true);
f.setSize(300,300);
f.getContentPane().setBackground(clr);
}
}
class ColorChooserEx
{
public static void main(String[] args)
{
ColorChooserFrame cc=new ColorChooserFrame();
}
}

JFileChooser:
It is a swing specific GUI component, it able to display all the file system which is available in our
system harddisk inorder to select.

To represent this GUI component, SWING has provided a predefined class in the form of
javax.swing.JFileChooser.

To create JFileChooser class object we have to use the following constructor.

public JFileChooser()

To get Selected file from JFileChooser we have to use the following method.

public File getSelectedFile()

In GUI applications, JFileChooser is able to rise ActionEvent and it would be handled by


ActionListener by executing "actionPerformed(ActionEvent ae)".
452
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
class FileChooserFrame extends JFrame implements ActionListener
{
JLabel l;
JTextField tf;
JButton b;
Container c;
JFileChooser fc;
FileChooserFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("File Chooser Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setBackground(Color.pink);
c.setLayout(new FlowLayout());

l=new JLabel("Select File");


tf=new JTextField(20);
b=new JButton("Browse");
b.addActionListener(this);
c.add(l);c.add(tf);c.add(b);
}
public void actionPerformed(ActionEvent ae)
{
class FileDialogFrame extends JFrame implements ActionListener
{
FileDialogFrame()
{
this.setVisible(true);
this.setSize(500,500);
fc=new JFileChooser();
fc.addActionListener(this);
this.getContentPane().add(fc);
}
453

public void actionPerformed(ActionEvent ae)


{
Page

File f=fc.getSelectedFile();
String path=f.getAbsolutePath();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


tf.setText(path);
this.setVisible(false);
}
}
FileDialogFrame ff=new FileDialogFrame();
}
}
class FileChooserEx
{
public static void main(String[] args)
{
FileChooserFrame f=new FileChooserFrame();
}
}

JTable: It is a SWING specific GUI component, it able to display data in rows and columns.
To rpersent this GUI component, SWING has provided a predefined class in the form of
javax.swing.JTable.
To create JTable class object we have to use the following constructor.
public JTable(Object[][] body, Object[] header)

EX: import javax.swing.*;


import javax.swing.table.*;
import java.awt.*;
class TableEx
{
public static void main(String[] args)
{
String[] header={"EID","ENAME","ESAL","EADDR"};
Object[][]
body={{"e1","AAA","5000","Hyderabad"},{"e2","BBB","6000","Secbad"},{"e3","CCC","7000
","Vijayawada"},{"e4","DDD","8000","Warngal"}};
JFrame f=new JFrame();
f.setVisible(true);
f.setSize(500,500);
Container c=f.getContentPane();
c.setLayout(new BorderLayout());
JTable t=new JTable(body,header);
JTableHeader th=t.getTableHeader();
c.add(th,BorderLayout.NORTH);
454

c.add(t,BorderLayout.CENTER);
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Internationalization[I18N]
Designing Java applications w.r.t the local users is called as Internationalization.

Java is able to provide very good Internationalization support due to UNICODE representations in
java.

UNICODE is one of the character representations following by JAVA, it able to represent all the
alphabet from all the natural languages.

In java applications, if we want to provide Internationalization services , first, we have to represent a


group of local users in java programs, to represent group of local users, first we have to devide all the
users in no of groups .

To devide users into no of groups , we have to use the following parameters:

1.Language:It will be represented in the form of two lower case letters


EX: en, hi, it,.......

2.Country: It will be represented in the hfrom of two upper case letters.


EX: US, IN, IT,......

3.System Varient[OS]: It will be represented in the form of three lower case letters.
EX: win, lin, uni,......

To represent a group of Local users in java applications, JAVA has provided a predefined class in the
form of "java.util.Locale" .

To create Objects for java.util.Locale class we have to use the following consrtructors.

public Locale(String lang)


public Locale(String lang, String country)
public Locale(String lang, String country, String Sys_Var)

EX: Locale l=new Locale("en");


Locale l=new Locale("en", "US");
Locale l=new Locale("it","IT","win");
455
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java is able to provide Internationalization support in the form of the following three services.

1.Number Formations
2.Date Foamtions
3.Message Formations

1.Number Formations:
From language to language, country to country number representations are varied. Torepresent
numbers w.r.t a particular Locale JAVA has provided a predefined class in the from of
"java.text.NumberFormat"

To represent number w.r.t a particular Locale by using NumberFormat class we have to use the
following steps.

1.Create Locale class object:


Locale l=new Locale("en", "US", "win");

2.Create NumberFormat class object:


To create NumberFormat class object we have to use the following static Factory Method from
java.text.NumberFormat class.

public static NumberFormat getInstance(Locale l)


EX: NumberFormat nf=NumberFormat.getInstance(l);

3.Format a particular Number w.r.t a particular Locale:


To format a number w.r.t a particular Local we have to use the following method from
java.text.NumberFormat class.

public String format(xxx num)


Where xxx may be byte, short, int,.....

EX: String data=nf.format(123456.2345f);

456
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
import java.text.*;
class I18NEx
{
public static void main(String[] args)throws Exception
{
Locale l=new Locale("it","IT","win");
NumberFormat nf=NumberFormat.getInstance(l);
System.out.println(nf.format(1234567.3456));
}
}

Date Formations:
From language to language, country to country Date representations are varied. To represent Dates
w.r.t a particular Locale JAVA has provided a predefined class in the from of
"java.text.DateFormat"

To represent Date w.r.t a particular Locale by using DateFormat class we have to use the following
steps.

1.Create Locale class object:


Locale l=new Locale("en", "US", "win");

2.Create DateFormat class object:


To create DateFormat class object we have to use the following static factory method from
java.text.DateFormat class.

public static DateFormat getDateInstance(int date_Style, Locale l)


Where date_Style may be 0,1,2 and 3.
EX: DateFormat df=DateFormat.getDateinstance(0, l);

3.Format current System Date w.r.t a particular Locale:


To format current System Date w.r.t a particular Locale we have to use the following method from
java.text.DateFormat class.

public String format(Date d)


EX: String date=df.format(new Date());
457
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
import java.util.*;
import java.text.*;
class I18NEx
{
public static void main(String[] args)throws Exception
{
Locale l=new Locale("it","IT","win");
DateFormat df=DateFormat.getDateInstance(3,l);
System.out.println(df.format(new Date()));
}
}

3.Message Formations:
From language to language , from country to country, messages repersentations are varied, if we
want to represent message w.r.t a particular Locale then we have to use java.util.ResourceBundle
class provided by JAVA.

To represent messages w.r.t a particular Locale by using ResourceBundle class we have to use the
following steps.

1.Prepare properties files for each and every locale:


In properties files we have to provide locale respective messages in the form of Key-Value pairs,
where keys must be in english but values must be in local respective messages.

We have to provide properties files names in the following format.

File_name_<lang>_<country>_<sys_Var>.properties

EX1: abc_en_US.properties

welcome=Welcome to en US Users.

EX2: abc_it_IT.properties

welcome=Welcomeo Toe it IT Userse.

EX3: abc_hi_IN.properties

welcome=Aap ka swagath hai.


458
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.In Java program, Create Locale object:
Locale l=new Locale("en", "US");

3.Prepare ResourceBundle class Object:


The main intention of ResourceBundle object is to store the content of a particular properties file.

To create ResourceBundle Object we have to use the following method.

public static ResourceBundle getBundle(String base_Name, Locale l)

EX: ResourceBundle rb=ResourceBundle.getBundle("abc",l);

4.Get Message from ResourceBundle:


To get Message from ResourceBundle object we have to use the following method.

public String getString(String key)

String message=rb.getString("welcome");

EX:
abc_en_US.properties

welcome=Welcome to en US Users.

abc_it_IT.properties

welcome=Welcomeo Toe it IT Userse.

abc_hi_IN.properties

welcome=Aap ka swagath hai.

I18NEx.java
import java.util.*;
class I18NEx
{
public static void main(String[] args)throws Exception
{
Locale l=new Locale("hi","IN");
ResourceBundle rb=ResourceBundle.getBundle("abc",l);
459

System.out.println(rb.getString("welcome"));
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Reflection API
1.Introduction
2.Class
3.Method
4.Field
5.Constructor

Reflection:
The process of analyzing all the capabilities of a particular class at runtime is called as
"Reflection".

 Reflection API is a set of predefined classes provided by Java to perform reflection over a
particular class.
 Reflection API is not useful in projects development,reflection API is useful in products
development like Compilers,JVM's,Server's,IDE's,FrameWork's.....
 Java has provided the complete predefined library for Reflection API in the form of "java.lang"
package and "java.lang.reflect" package.

Java.lang
Class
java.lang.reflect
Field
Method
Constructor
Package
Modifier
---
---
Java.lang.Class:
 This class can be used to represent a particular class metadata which includes class name,super
class details,implemented interfaces details,access modifiers......
 To get the above class metadata,first we have to create Class Object for the respective class.
 There are three ways to create object for java.lang.Class
460
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Using forName(--) method:
 forName() method is defined in java.lang.Class to load a particular class bytecode to the
memory and to get metadata of the respective loaded class in the form of Class object.
 public static Class forName(String class_Name) throws ClassNotFoundException

class c=Class.forName("Employee");
when JVM encounter the above instruction,JVM will perform the following actions.
a)JVM will take provided class from forName() method.
b)JVM will search for its .class file at current location,at java predefined library and at the
locations refefered by "classpath" environment variable.
c)If the required .class file is not available at all the above locations then JVM will rise an
exception like "java.lang.ClassNotFoundException".
d)If the required .class file is available at either of the above locations then JVM will load its
bytecode to the memory.
e)After loading its bytecode to the memory,JVM will collect the respective class metadata and
stored in the form of java.lang.Class object.

2.Using getClass() method:


 In Java applications,if we create object for any class then JVM will load the respective class
bytecode to the memory,JVM will get metadata of the respective class and stored in the form
of java.lang.Class object.
 In the above context,to get the generated Class object,we have to use the following method
from java.lang.Object class.
 public Class getClass()

EX:
Employee e=new Employee();
Class c=e.getClass();

3.Using .class file name:


 In Java,every .class file is representing a java.lang.Class Object,it will manage the metadata of the
respective class.

EX:
Class c=Employee.class
 To get name of the class,we have to use the following method.
461

public String getName()


 To get super class metadata in the form of Class object,we have to use the following method.
Page

public Class getSuperclass()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


 To get implemented interfaces metadata in the form of Class[] we have to use the following
method.

public Class[] getInterfaces()


 To get the sepcified access modifiers list,we have to use the following method.

public int getModifiers()

EX:
int val=c.getModifiers()
String modifiers=Modifier.toString(val);
import java.lang.reflect.*;
public abstract class Employee implements java.io.Serializable,java.lang.Cloneable{
}
class Test{
public static void main(String args[]) throws Exception{
Class c1=Clas.forName("Employee");
System.out.println(c1.getName());
Employee e=new Employee();
Class c2=e.getClass();
System.out.println(c2.getName());
Class c3=Employee.class;
System.out.println(c3.getName());
Class c=Class.forName("Employee");
System.out.println("Class Name :"+c.getName());
System.out.println("Super Class :"+c.getSuperclass().getName());
Class[] cls=c.getInterfaces();
System.out.println("Interfaces :");
for(int i=0;i<cls.length;i++){
Class cl=cls[i];
System.out.println(cl.getName()+" ");
}
System.out.println();
int val=c.getModifiers();
System.out.println("Modifers :"+Modifier.toString(val));
}
}
462
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java.lang.reflect.Field:
 This class can be used to get the metadata of a particular variable which contains the name of the
variable,data type of the variable,access modifiers of the variable and value of the variable.
 If we want to get all the variables metadata of a particular class first we have to get java.lang.Class
object.After getting Class object,we have to get all the variables metadata in the form Field[].
 To get all the variables metadata in the form of Field[],we have to use the following two methods.

public Field[] getFields()


 This method will return all the variables metadata which are declared as public in the respective
class and in the super class.

public Field[] getDeclaredFields()


 This method will return all the variables metadata which are available in the respective class only
irrespective of public declaration.
 To get name of the variable,we have to use the following method.

public String getName()


 To get datatype of the variables,we have to use the following method.

public Class getType()


 To get value of the variable,we have to use the following method.

public Object get(Field f)


 To get access modifiers of a variable,we have to use the following method.

public int getModifiers()


public static String toString(int val)

import java.lang.reflect.*;
class Employee{
public static String eid="E-111";
public static String ename="Durga";
public static String eaddr="Hyd";
}
class Test{
public static void main(String args[])throws Exception{
Class c=Employee.class;
Field[] flds=c.getDeclaredFields();
463

for(int i=0;i<flds.length;i++){
Field f=flds[i];
System.out.println("Field Name :"+f.getName());
Page

System.out.println("data Type :"+f.getType().getName());

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


System.out.println("value :"+f.get(f));
int val=f.getModifiers();
System.out.println("Modifiers :"+Modifier.toString(val));
System.out.println("----------------------------------------");
}
}
}

Java.lang.Method:
 This class can be used to represent the metadata of a particular method,which includes method
name,return type,parameter types,access modifiers and exception types
 If we want to get all the methods metadata in the form of method[],first we have to get
java.lang.Class object then we have to use either of the following methods.

public Method[] getMethods()


 It can be used to get all the methods metadata which are declared as public in the respective class
and in the super class.

public Method[] getDecalredMethods()


 It can be used to get all the methods metadata which are available in the respective class
irrespective of public declaration.
 To get method name,we have to use the following method.

public String getName()


 To get method return type,we have to use the following method.

public Class getReturnType()


 To get parameter data types,we have to use the following method.

public Class[] getParameterTypes()


 To get Exception types which are specified along with "throws" keyword then we have to use the
following method.

public Class[] getExceptionTypes()


 To get Access modifier of a particular class,we have to use the following method. 464
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public int getModifers()
public static String toString(int value)
import java.lang.reflect.*;
class Employee{
public void create(String eid,String ename,String eaddr)throws
ClassNotFoundException,NullPointerException{
}
public void search(String eid)throws ClassCastException
{}
public void delete(String eid)throws ClassCastException,ClassNotFoundException
{}
}
class Test{
public static void main(String args[])throws Exception{
Class c=Employee.class;
Method[] mthds=c.getDeclaredMethods();
for(int i=0;i<mthds.length;i++){
Method m=mthds[i];
System.out.println("Method Name :"+m.getName());
System.out.println("Return Tyep :"+m.getreturnType());
int val=m.getModifiers();
System.out.println("Modifiers :"+modifier.toString(val));
Class[] cls=m.getParameterTypes();
System.out.println("Parametes :");
for(int j=0;j<cls.length;j++){
Class cl=cls[j];
System.out.println(cl.getName()+" ");
}
System.out.println();
Class[] cls1=m.getExceptionTypes();
System.out.println("Exception Types :");
for(int j=0;j<cls1.length;j++){
Class cl1=cls1[j];
System.out.println(cl1.getName()+" ");
}
System.out.println();
System.out.println("-----------------------------");
}
}
465

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java.lang.reflect.Constructor:
 This class can be used to get metadata of a particular constructor.
 To get all the constructors metadata of a particular class first we have to get Class object then
we have to use the following methods.

public Constructor[] getConstructors()


 It will return only public constructors details from the respective class.

public Constructor[] getDeclaredConstrctors()


 It will return all the constructors metadata of the respective class irrespective of their public
declaration.
 Constructor class has provided the following methods to get constructor data.

public String getName()


public Class[] getParameterTypes()
public Class[] getExceptionTypes()
public int getModifiers()
public static String toString(int val)
program is same as java.lang.reflect.Method program with the above methods

import java.lang.reflect.*;
class Employee{
public Employee(String eid,String ename,String eaddr)throws
ClassNotFoundException,NullPointerException{
}
public Employee(String eid,String ename)throws ClassCastException{
}
public Employee(String eid)throws ClassCastException,ClassNotFoundException{
}
}
class Test{
public static void main(String args[])throws Exception{
Class c=Employee.class;
Constructor[] con=c.getDeclaredConstructors();
for(int i=0;i<con.length;i++){
Constructor constructor =con[i];
System.out.println("Constructor Name :"constructor.getName());
int val=constructor.getModifiers();
466

System.out.println("Modifiers :"+Modifier.toString(val));
Class[] cls=constructor.getParameterTypes();
System.out.println("Parametes :");
Page

for(int j=0;j<cls.length;j++){

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Class cl=cls[j];
System.out.println(cl.getName()+" ");
}
System.out.println();
Class[] cls1=constructor.getExceptionTypes();
System.out.println("Exception Types :");
for(int j=0;j<cls1.length;j++){
Class cl1=cls1[j];
System.out.println(cl1.getName()+" ");
}
System.out.println();
System.out.println("-----------------------------");
}
}
}

467
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Annotations
1.Introduction
2.Comment Vs Annotations
3.XML Vs Annotations
4.Types of Annotations
5.Standard Annotations
6.Custom Annotations

Annotation:
Annotation is a Java Feature provided by JDK 5.0 version,it can be used to represent metadata in
Java applications.

Q)In java applications,to describe metadata we have already Comments then what is the
requirement to go for Annotations?

Ans:In Java applications,if we provide metadata by using comments then "Lexical Analyzer" will
remove comments metadata from Java program as part of Compilation.
As per the application requirement,if we want to bring metadata upto .java file,upto .class file and
upto RUNTIME of our application then we have to use "Annotations".

Q)In Java applications,to provide metadata at runtime of Java applications we are able to use XML
documents then what is the requirement to go for "Annotations"?

Ans:In Java applications,if we provide metadata by using XML documents then we are able to get the
following problems.
1.Every time we have to check whether XML documents are located properly or not.
2.Every time we have to check whether XML documents are formatted properly or not.
3.Every time we have to check whether we are using right parsing mechanism or not to access
the data from XML document.
4.First Developers must aware XML tech.
To Overcome all the above problems,we have to use Java alternative that is "Annotation".
468
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: Servlet Configuration with XML document:
web.xml
<web-app>
<servlet>
<servlet-name>ls</servlet-name>
<servlet-class>LoginServlet</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>ls</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

Servlet Configuration with Annotation


@WebServlet("/login")
public class LoginServlet extends HttpServlet{
}

XML-Based Tech Annotation Based Tech


JDK1.4 JDK5.0
JDBC3.0 JDBC4.0
Servlets2.5 Servlets3.0 Struts1.x
Struts2.x
JSF1.x JSF2.x
Hiberante3.2.4 Hibernate3.5
EJBs2.x EJBs3.x
Spring2.x Spring3.x

NOTE:Annotations are not the complete alternative for XML tech,with in a Java application we
can use annotations as an alternative for XML documents but when we go for distributed
applications where applications are designed on different tech.standards there annotations are
not possible,only we have to use XML tech.

 To process the annotations,Java has provided a predefined tool in the form of "Annotation
Processing tool"[APT},it was managed by Java upto JAVA7 version,it was removed from Java in
JAVA8 version.
469
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Syntax to declare annotation:
@interface Annotation_Name{
data_Type member_Name() [default] value;
}

Syntax to use Annotation:


@Annotation_Name(member_name1=value1,member_Name2=value2.........)
 In Java,all the annotations are interfaces by default.
 In Java,the common and default super type for all the annotations is
"java.lang.annotation.Annotation".
 As per the no.of members inside annotations,there are three types of annotations.

1.Marker Annotations:
It is an annotation with out members.

EX:
@interface Override{
}

2.Single-Valued Annotation:
It is an Annotation with exactly one single member

EX:
@interface SuppressWarnings{
String value();
}

3.Multi-Valued Annotation:
It is an annotation with more than one member.

EX:
@interface WebServlet{
int loadOnStartup();
String[] urlPatterns();
-----
}
470
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In Java Annotations are divided into the following two types as per their nature.
1.Standard Annotations
2.Custom Annotations

1.Standard Annotations:
These are predefined Annotations provided by Java along with Java software.
There are two types of Standard Annotations
1.General Purpose Annotations
2.Meta Annotations

1)General Purpose Annotations:


These Annotations are commonly used Annotations in Java applications
These Annotations are provided by Java as part of java.lang package.

EX:
@Override
@Deprecated
@SuppressWarnings
@FunctionalInterface [JAVA 8]

2)Meta Annotations:
These Annotations can be used to define another Annotations.
These Annotations are provided by Java as part of java.lang.annotation package.

EX:
@Inherited
@Documented
@Target
@Retention

1.@Override:
 In Java applications if we want to perform method overriding then we have to provide a method
in subclass with the same prototype of super class method.
 While performing method Overriding,if we are not providing the same super class method at sub
class method then compiler will not rise any error and JVM will not rise any exception,JVM will
provide super class method output.

 In the above context,if we want to get an error about to describe failure case of method
471

overriding from compiler then we have to use @Override


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class JdbcApp
{
public void getDriver(){
System.out.println("Type-1 Driver");
}
}
class New_JdbcApp extends JdbcApp
{
@Override
public void getdriver(){
System.out.println("Type-4 Driver");
}
}
class Test
{
public static void main(String args[]){
JdbcApp app=new New_JdbcApp();
app.getDriver();
}
}
 If we compile the above programme then compiler will rise an error like "method does not
override or implement a method from a SuperType".

NOTE:If we compile the above programme,compiler will recognize @Override


annotation,compiler will take sub class method name which is marked with @Override
annotation,compiler will comparesub class method name with all the super class method
names.If any method name is matched then compiler will not rise any error.If no super class
method name is matched with sub class method name then compiler will rise an error.

@Deprecated:
 The main intention of this annotation is to make a method as deprecated method and to provide
deprecation message when we access that deprecated method.
 In general,Java has provided Deprecation support for only predefined methods,if we want to get
deprecation support for the user defined methods we have to use @Deprecated annotation.

NOTE:Deprecated method is an outdated method introduced in the initial versions of Java and
having alternative methods in the later versions of Java.
472
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


class Employee{
@Deprecated
public void gen_Salary(int basic,float hq){
System.out.println("Salary is calculated on the basis of basic amount,hq");
}
public void gen_Salary(int basic,float hq,int ta,float pf){
System.out.println("Salary is calculated on the basis of basic amount,hq,ta,pf");
}
}
class Test{
public static void main(String args[]){
Empoloyee emp=new Employee();
emp.gen_Salary(25000,20.0f);
}
}
NOTE: If we compile the above code then compiler will provide the following deprecation message
"Note:java uses or overrides a deprecated API"

@SuppressWarnings(--):
In Java applications,when we perform unchecked or unsafe operations then compiler will rise some
warning messages.In this context,to remove the compiler generated warning messages we have to
use @SuppressWarnings("unchecked") annotation.

EX:
import java.util.*;
class Bank{
@SuppressWarnings("unchecked")
public ArrayList listCustomers(){
ArrayList al=new ArrayList();
al.add("chaitu");
al.add("Mahesh");
al.add("Jr NTR");
al.add("Pavan");
return al;
}
}
class Test{
public static void main(String args[]){
Bank b=new Bank();
List l=b.listCustomers();
473

System.out.println(l);
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


@FunctionalInterface:
 In Java,if we provide any interface with out abstract methods then that interface is called as
"Marker Interface".
 In Java,if we provide any interface with exactly one abstract method then that interface is
called as "Functional Interface".
 To make any interface as Functional Interface and to allow exactly one abstract method in any
interface then we have to use "@FunctionalInterface" annotation.

NOTE:This annotation is a new annotation provided by JAVA8 version.

@FunctionalInterface
interface Loan{
void getLoan();
}
class GoldLoan implements Loan{
public void getLoan(){
System.out.println("GoldLoan");
}
}

class Test{
public static void main(String args[]){
Loan l=new GoldLoan();
l.getLoan();
}
}

474
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


@Inherited:
In general all the annotations are not inheritable by default.
If we want to make/prepare any annotation as Inheritable annotation then we have to declare that
annotation as Inheritable annotation then we have to declare that annotation with
@Inherited annotation.

EX: @interface Persistable


{
}
@Persistable
class Employee
{
}
class Manager extends Employee{
}
In the above example,only Employee class objects are Persistable i.e eligible to store in database.
@Inherited
@interface Persistable
{
}
@Persistable
class Employee{
}
class Manager extends Employee{

NOTE:In the above example,both Employee class objects and manager class objects are
Persistable i.e eligible to store in database.

475
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


@Documented:
In Java,by default all the annotations are not documentable.
In Java applications,if we want to make any annotation as documentable annotation then we have
to prepare the respective annotation with @Documented annotation.

EX:
@interface Persistable
{
}
@Persistable
class Employee
{
}
javadoc Employee.java

If we prepare html documentation for Employee class by using "javadoc" tool then @Persistable
annotation is not listed in the html documentation.
@Documented
@interface Persistable
{
}
@Persistable
class Employee
{
}

If we prepare html documentation for Employee class by using "javadoc" tool then @Persistable
annotation will be listed in the html documentation.

@Target:
The main intention of this annotation is to define a list of target elements to which we are applying
the respective annotation.

Synatx:
@Target(--list of constants from ElementType enum---)
Where ElementType enum contains FIELD,CONSTRUCTOR,METHOD,TYPE[Classes,abstract
classes,interfaces]
476
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
@Target(ElementType.TYPE,ElementType.FIELD,ElementType.METHOD)
@interface persistable
{
}
@Persistable
class Employee
{
@Persistable
Account acc;

@Persistable
public Address getAddress(){}
}

@Retention:
The main intention of the annotation is to define life time of the respective annotation in Java
application.

Syntax:
@Retention(---a constant from RestentionPolicy enum---)
Where RestentionPolicy enum contains the constants like SOURCE,CLASS,RUNTIME
@Retention(RetentionPolicy.RUNTIME)
@interface Persistable
{
}
@Persistable
class Employee
{
}

477
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Custom Annotations:
 These are the annotations defined by the developers as per their application requirements.
 To use custom annotations in java applications,we have to use the following steps.

1)Declare user defined Annotation:


Bank.java
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Bank
{
String name() default "ICICI Bank";
String branch() default "S R Nagar";
String phone() default "040-123456";
}

2)Utilize User defined Annotations in Java applications:


Account.java
@Bank(name="Axis Bank",phone="040-987654")
public class Account{
String accNo;
String accName;
String accType;
public Account(String accNo,String accName,String accType){
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}
public void getAccountDetails(){
System.out.println("Account Details");
System.out.println("----------------");
System.out.println("Account Number:"+accNo);
System.out.println("Account Name :"+accName);
System.out.println("Account Type :"+accType);
}
}
478
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3)Access the data from User-Defined Annotation in main Application:
1)If the annotation is class level annotation then use the following steps:
a)Get java.lang.Class object of the respective class
b)Get Annotation object by using getAnnoataion(Class c) method

2)If the annotation is Field level annotation then use the following steps:
a)Get java.lang.Class object of the respective class
b)Get java.lang.reflect.Field class object of the respective variable from java.lang.Class by using
getField(String field_name) method
c)Get Annotation object by using getAnnotation(Class c) method from java.lang.reflect.Field
class.

3)If the annotation is Method level annotation then use the following steps:
a)Get java.lang.Class object of the respective class
b)Get java.lang.reflect.Method class object of the respective Method from java.lang.Class by
using getMethod(String method_name) method
c)Get Annotation object by using getAnnotation(Class c) method from java.lang.reflect.Method
class.

MainApp.java
import java.lang.annotation.*;
import java.lang.reflect.*;
public class MainApp{
public static void main(String args[])throws Exception{
Account acc=new Account("abc123","Durga","Hyd");
acc.getAccountDetails();
System.out.println();
Class c=acc.getClass();
Annotation ann=c.getAnnotation(Bank.class);
Bank b=(Bank)ann;
System.out.println("Bank Details");
System.out.println("------------");
System.out.println("Bank Name :"+b.name());
System.out.println("Branch Name :"+b.branch());
System.out.println("Phone "+b.phone());
}
}

NOTE:class Level Annotation


479
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Method Level Annotation
Course.java:
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Course{
String cid() default "C-111";
String cname() default "Java";
int ccost() default 5000;
}

Student.java:
public class Student{
String sid;
String sname;
String saddr;
public Student(String sid,String sname,String saddr){
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
}
@Course(cid="C-222",cname=".NET")
public void getStudentDetails(){
System.out.println("Student Details");
System.out.println("---------------");
System.out.println("Student Id :"+sid);
System.out.println("Sudent Name :"+sname);
System.out.println("Student Address:"+saddr);
}
}

ClientApp.java
import java.lang.annotation.*;
import java.lang.reflect.*;
public class ClientApp{
public static void main(String args[])throws Exception{
Student std=new Student("S-111","Durga","Hyd");
std.getStudentDetails();
480

System.out.println();
Class cl=std.getClass();
Page

Method m=cl.getMethod("getStudentDetails");
Annotation ann=m.getAnnotation(Course.clas);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Course c=(Course)ann;
System.out.println("Course Details");
System.out.println("---------------");
System.out.println("Course Id :"+c.cid());
System.out.println("Course Name :"+c.cname());
System.out.println("Course Cost :"+c.ccost());
}
}

481
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


RMI [Remote Method Invocation]
To prepare Distributed applications,if we use Socket programming then we have to prepare
ServerSocket, Client Side Socket, InputStreams, OutputStreams,..... at local machine and Remote
machine explicitly, it will increase burden to the developers.

To overcome the above problems, SUN Microsystems has provided an alternative distributed tech to
prepare distributed applications, that is, RMI.

In case of RMI, the complete distributed applications infrastructer like Server socket, socket, input
streams and OutputStreams,.... are provided by RMI internally, developers are not required to provide
distributed applications infrastructer explicitly.

RMI will use the following two components internally to provide Distributed applicatins infrastructer.
1.Stub
2.Skeleton

1.Stub:
It is a special component in RMI, it will be existed at Local Machine, it will provide Client side
socket, Input and Output Streams and it is capable to perform Serialization and Deserialization,
Marshalling and Unmarshalling and it able to recieve remote method calls from local machine and
it will send remote method call to network, it able to recieve return values from remote method call
from network and it will send that return values to client application.

2.Skeleton:
It is a special component in RMI, it will be existed at Remote machine, it will provide server socket,
InputStreams and OutputSTream, it is capable to perform Serialization and Deserialization ,
Marshalling and Unmarshalling and it able to reacieve remote method call from Network, it able to
access remote methods and it able to carry return values of remote methods to network.

NOTE: To expose Remote objects in network, RMI will use a seperate Registry Software called as
"RMIRegistry.

RMI Arch:
---------
--- Diagram-----
482
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1.Create Remote object and keep Remote object in RMIRegistry "along with logical name"
inorder to expose Remote object in network.
2.At Local machine, perform lookup operation in RMIRegistry on the basis of logical name.
3.RMIRegistry will return Remote object reference value to local machine or Client
Application.
4.Access Remote method by using Remote object reference.
5.When we access Remote method, Remote method call will be send to Stub.
6.Stub will perform the required "Serialization" and "Marshalling" over the remote method call.
7.Stub will send remote method call to Network.
8.Network will transfer remote method call to Remote machine.
9.Skeleton will take remote method call from network.
10.Skeleton will perfrom the required "Unmarshalling" and "Deserialization" over the remote
method call.
11.Skeleton will access remote method.
12.Skeleton will get return value of remote method.
13.Skeleton will perform the required "Serialization" and "Marshalling" over the return value.
14.Skeleton will send return value to Network.
15.Network will carry return value to Local machine.
16.Stub will take return value from network.
17.Stub will perform the required "Unmarshalling" and "Deserialization" over the return value.
18.Stub will send return value to Client application.

Steps to prepare RMI Application:


1.Create Remote interface
2.Create Remote interface implementation class
3.Create Registry program
4.Create Client Application
5.Execute RMI Application

1.Create Remote interface:


The main intention of Remote interface is to declare all remote services in the form of abstract
methods.

STEPS:
a)Declare an user defined interface.
b)Extend java.rmi.Remote interface to user defined interface.
c)Declare remote methods in the form of abstract methods.
d)Throws out java.rmi.RemoteException at each and every remote metod.
483
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
public interface MyRemote extends java.rmi.Remote
{
public String myRemoteService1()throws java.rmi.RemoteException;
public String myRemoteService2()throws java.rmi.RemoteException;
-----
}

2)Create Remote interface implementation class:


The main intention of Implementation class for Remote interface is to provide implementation to
service methods.

STEPS:
a)Declare an user defined class.
b)Extend java.rmi.server.UnicastRemoteObject abstract class to user defined class inorder to make
network enable.
c)Implement User defined Remote interface in user defined class.
d)Declare public and 0-arg constructor in user defined class with throws java.rmi.RemoteException.
e)Provide implementation for Service methods.

EX:
public class MyRemoteImpl extends java.rmi.server.UnicastRemoteObject implements MyRemote
{
public MyRemoteImpl()throws java.rmi.RemoteException
{
}
public String myRemoteService1()throws java.rmi.RemoteException
{
----
}
public String myRemoteService2()throws java.rmi.RemoteException
{
----
}
----
}
484
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.Create Registry program:
The main intention of Registry program is to create Remote object and to keep Remote object in
RMIRegistry with a particular logical name.

STEPS:
a)Declare an user defined class with main() method.
b)In main() method, create Objectt for Remote interface implementation class.
C)Bind Remote object with a logical name in RMIRegistry by using the following method
from java.rmi.Naming class.
public static void bind(String logical_Name, Remte r) throws RemoteException

EX: public class MyRegistry


{
public static void main(String[] args)throws Exception
{
MyRemote mr=new MyRemoteImpl();
java.rmi.Naming.bind("my_rem", mr);
}
}

4.Create Client Application:


The main intention of Client Application is to get Remote object from RMIRegistry and to access
remote methods from Local machine.

STEPS:
a)Declare an user defined class with main() method.
b)In main() method, get Remote object from RMIRegistry by using the following method from
java.rmi.Naming class.
public static Remote lookup(String logical_Name)
c)Access Remote methods.

EX: class ClientApp


{
public static void main(String[] args)
{
MyRemote mr=(MyRemote)java.rmi.Naming.lookup("my_rem");
mr.myRemoteService1();
mr.myRemoteService2();
----
485

----
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5.Execute RMI Application:
a)Compile all resources[.java files]
D:\java830>javac *.java
b)Start RMIRegistry
D:\java830>start RMIRegistry
c)Execute Registry program
D:\java830>start java MyRegistry
d)Execute Client Application
D:\java830>java ClientApp

Application1:
D:\java830\rmi\app1

HelloRemote.java
HelloRemoteImpl.java
HelloRegistry.java
ClientApp.java

HelloRemote.java

import java.rmi.*;
public interface HelloRemote extends Remote
{
public String sayHello(String name)throws RemoteException;
}

HelloRemoteImpl.java

import java.rmi.*;
import java.rmi.server.*;
public class HelloRemoteImpl extends UnicastRemoteObject implements HelloRemote
{
public HelloRemoteImpl()throws RemoteException
{
}
public String sayHello(String name)throws RemoteException
{
return "Hello..."+name+"!";
}
486

}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


HelloRegistry.java

import java.rmi.*;
public class HelloRegistry
{
public static void main(String[] args)throws Exception
{
HelloRemote hr=new HelloRemoteImpl();
Naming.bind("hello", hr);
System.out.println("HelloRemote Object is binded with the logical 'hello' in
RMIRegistry");
}
}

ClientApp.java

import java.rmi.*;
public class ClientApp
{
public static void main(String[] args)throws Exception
{
HelloRemote hr=(HelloRemote)Naming.lookup("hello");
String msg=hr.sayHello("Durga");
System.out.println(msg);
}
}

Application2:
D:\java830\rmi\app2

CalculatorRemote.java
CalculatorRemoteImpl.java
CalculatorRegistry.java
ClientApp.java 487
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


CalculatorRemote.java:

import java.rmi.*;
public interface CalculatorRemote extends Remote
{
public int add(int i, int j)throws RemoteException;
public int sub(int i, int j)throws RemoteException;
public int mul(int i, int j)throws RemoteException;
}

CalculatorRemoteImpl.java

import java.rmi.*;
import java.rmi.server.*;
public class CalculatorRemoteImpl extends UnicastRemoteObject implements CalculatorRemote
{
public CalculatorRemoteImpl()throws RemoteException
{
}
public int add(int i, int j)throws RemoteException
{
return i+j;
}
public int sub(int i, int j)throws RemoteException
{
return i-j;
}
public int mul(int i, int j)throws RemoteException
{
return i*j;
}
}

488
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


CalculatorRegistry.java

import java.rmi.*;
public class CalculatorRegistry
{
public static void main(String[] args)throws Exception
{
CalculatorRemote cr=new CalculatorRemoteImpl();
Naming.bind("cal", cr);
System.out.println("CalculatorRemote object is binded with the logical name 'cal'
in RMIRegistry");
}
}

ClientApp.java

import java.rmi.*;
public class ClientApp
{
public static void main(String[] args)throws Exception
{
CalculatorRemote cr=(CalculatorRemote) Naming.lookup("cal");
System.out.println("ADD :"+cr.add(10,5));
System.out.println("SUB :"+cr.sub(10,5));
System.out.println("MUL :"+cr.mul(10,5));
}
}

489
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Regular Expressions
Regular Expression is an expression which represents a group of Strings according to a particular
pattern.

EX:
1.We can write a Regular Expression to represent all valid mail ids.
2.We can write a Regular Expression to represent all valid mobile numbers.

The main important application areas of Regular Expression are:


1.To implement validation logic.
2.To develop Pattern matching applications.
3.To develop translators like compilers, interpreters etc.
4.To develop digital circuits.
5.To develop communication protocols like TCP/IP, UDP etc.

To repersent and use Regular Expressions in Java applications, JAVA has provided predefined library
in the form of a package like "java.util.regex" in JDK1.4 version.

To prepare and Use Regular Expressions in java applications we have to use the following actions.

1.Create java.util.regex.Pattern class object with a Regular Expression:


A Pattern object represents "compiled version of Regular Expression".

To create Regular Expression in the form Pattern object we have to use the following method from
java.util.regex.Pattern class.

public static Pattern compile(String reg_Ex)

EX: Pattern p=Pattern.compile("ab");

2.Create java.util.regex.Matcher class object with a string which we want to compare with
Regular expression:
A Matcher object can be used to match character sequences against a Regular Expression.

We can create a Matcher object by using matcher() method of Pattern class.

public Matcher matcher(String target);


490

EX: Matcher m=p.matcher("abbbabbaba");


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.Get Matched Strings from Matcher object:
To get details about the Matches identified in Matcher object we have to use the following methods.

1.public boolean find();


--> It attempts to find next match and returns true if it is available otherwise returns false.

2.public int start();


-->Returns the start index of the match.

3.public int end();


-->Returns the offset(equalize) after the last character matched.(or)
Returns the "end+1" index of the matched.

4.public String group();


-->Returns the matched Pattern.

EX:
importjava.util.regex.*;
classRegularExpressionDemo{
public static void main(String[] args){
int count=0;
Pattern p=Pattern.compile("ab");
Matcher m=p.matcher("abbbabbaba");
while(m.find()){
count++;
System.out.println(m.start()+"------"+m.end()+"------"+m.group());
}
System.out.println("The no of occurences :"+count);
}
}

OP:
0------2------ab
4------6------ab
7------9------ab
The no of occurrences: 3
491
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To prepare Regular Expressions , we have to use the following elements.

1.Character Classes
2.Quantifiers

Character classes:
Character classes are used to specify alphabets and digits in Regular Expressions.

1.[abc]--------------Either 'a' or 'b' or 'c'


2.[^abc] ------------Except 'a' and 'b' and 'c'
3.[a-z] -------------Any lower case alphabet symbol
4.[A-Z] -------------Any upper case alphabet symbol
5.[a-zA-Z] ----------Any alphabet symbol
6.[0-9] -------------Any digit from 0 to 9
7.[a-zA-Z0-9] -------Any alphanumeric character
8.[^a-zA-Z0-9] ------Any special character

Predefined character classes:


\s----space character
\d----Any digit from o to 9[o-9]
\w----Any word character[a-zA-Z0-9]
. ----Any character including special characters.
\S----any character except space character
\D----any character except digit
\W----any character except word character(special character)

EX:
importjava.util.regex.*;
class RegularExpressionDemo{
public static void main(String[] args){
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("a1b7@z#");
while(m.find()) {
System.out.println(m.start()+"-------"+m.group());
}
}
}
OP:
492
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX: importjava.util.regex.*;
classRegularExpressionDemo{
public static void main(String[] args){
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("a1b7 @z#");
while(m.find()) {
System.out.println(m.start()+"-------"+m.group());
}
}
}

Quantifiers:
Quantifiers can be used to specify no of characters to match.
a- ----------------------Exactly one 'a'
a+ ----------------------At least one 'a'
a* ----------------------Any no of a's including zero number
a? ----------------------At most one 'a'

EX: importjava.util.regex.*;
class RegularExpressionDemo{
public static void main(String[] args){
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("abaabaaab");
while(m.find()){
System.out.println(m.start()+"-------"+m.group());
}
}
}

Pattern class split() method:


Pattern class contains split() method to split the given string against a regular expression.

EX 1:importjava.util.regex.*;
class RegularExpressionDemo{
public static void main(String[] args){
Pattern p=Pattern.compile("\\s");
String[] s=p.split("Durga software solutions");
for(String s1:s){
System.out.println(s1);
493

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX 2:
importjava.util.regex.*;
class RegularExpressionDemo{
public static void main(String[] args){
Pattern p=Pattern.compile("\\."); //(or)[.]
String[] s=p.split("www.dugrajobs.com");
for(String s1:s){
System.out.println(s1);
}
}
}

String class split() method:


String class also contains split() method to split the given string against a regular expression.
Example:
importjava.util.regex.*;
classRegularExpressionDemo{
public static void main(String[] args){
String s="www.durgajobs.com";
String[] s1=s.split("\\.");
for(String s2:s1){
System.out.println(s2);
}
}
}

NOTE: String class split() method can take regular expression as argument where as pattern class
split() method can take target string as the argument.

StringTokenizer:
This class present in java.util package.
It is a specially designed class to perform string tokenization. 494
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX 1:
importjava.util.*;
classRegularExpressionDemo
{
public static void main(String[] args)
{
StringTokenizerst=new StringTokenizer("Durga Software Solutions");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
The default regular expression for the StringTokenizer is space.
Example 2:
importjava.util.*;
classRegularExpressionDemo
{
public static void main(String[] args)
{
StringTokenizerst=new StringTokenizer("1,99,988",",");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

Requirement:
Write a regular expression to represent all valid identifiers in java language.
Rules:
The allowed characters are:
1.a to z, A to Z, 0 to 9, -,#
2.The 1st character should be alphabet symbol only.
3.The length of the identifier should be at least 2.
495
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Program:
importjava.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("[a-zA-Z][a-zA-Z0-9-#]+"); (or)
Pattern p=Pattern.compile("[a-zA-Z][a-zA-Z0-9-#][a-zA-Z0-9-#]*");
Matcher m=p.matcher(args[0]);
if(m.find()&&m.group().equals(args[0]))
{
System.out.println("valid identifier");
}
else
{
System.out.println("invalid identifier");
}
}
}
Requirement:
Write a regular expression to represent all mobile numbers.
1.Should contain exactly 10 digits.
2.The 1st digit should be 7 to 9.

Program: importjava.util.regex.*;
classRegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
//Pattern p=Pattern.compile("[7-9][0-9]{9}");
Matcher m=p.matcher(args[0]);
if(m.find()&&m.group().equals(args[0]))
{
System.out.println("valid number");
}
else
{
496

System.out.println("invalid number");
}
Page

}
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Analysis:
10 digits mobile:
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] (or)
[7-9][0-9]{9}

OP:
E:\javaapps>javac RegularExpressionDemo.java
E:\javaapps>java RegularExpressionDemo 9989123456
Valid number

E:\javaapps>java RegularExpressionDemo 6989654321


Invalid number
10 digits (or) 11 digits:
(0?[7-9][0-9]{9})

OP:
E:\javaapps>javac RegularExpressionDemo.java

E:\javaapps>java RegularExpressionDemo 9989123456


Valid number

E:\javaapps>java RegularExpressionDemo 09989123456


Valid number

E:\javaapps>java RegularExpressionDemo 919989123456


Invalid number
10 digits (0r) 11 digit (or) 12 digits:
(0|91)?[7-9][0-9]{9} (or)
(91)?(0?[7-9][0-9]{9})

E:\javaapps>javac RegularExpressionDemo.java
E:\javaapps>java RegularExpressionDemo 9989123456
Valid number
E:\javaapps>java RegularExpressionDemo 09989123456
Valid number
E:\javaapps>java RegularExpressionDemo 919989123456
Valid number
E:\javaapps>java RegularExpressionDemo 69989123456
Invalid number
497
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Requirement:
Write a regular expression to represent all Mail Ids.

Program:
importjava.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("
[a-zA-Z][a-zA-Z0-9-.]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+");
Matcher m=p.matcher(args[0]);
if(m.find()&&m.group().equals(args[0]))
{
System.out.println("valid mail id");
}
else
{
System.out.println("invalid mail id");
}
}
}

OP:
E:\javaapps>javac RegularExpressionDemo.java
E:\javaapps>java RegularExpressionDemo sunmicrosystem@gmail.com
Valid mail id
E:\javaapps>java RegularExpressionDemo 999sunmicrosystem@gmail.com
Invalid mail id
E:\javaapps>java RegularExpressionDemo 999sunmicrosystem@gmail.co9
Invalid mail id

Requirement:
Write a program to extract all valid mobile numbers from a file. 498
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Program:
importjava.util.regex.*;
import java.io.*;
classRegularExpressionDemo
{
public static void main(String[] args)throws IOException
{
PrintWriter out=new PrintWriter("output.txt");
BufferedReaderbr=new BufferedReader(new FileReader("input.txt"));
Pattern p=Pattern.compile("(0|91)?[7-9][0-9]{9}");
String line=br.readLine();
while(line!=null)
{
Matcher m=p.matcher(line);
while(m.find())
{
out.println(m.group());
}
line=br.readLine();
}
out.flush();
}
}

Requirement:
Write a program to extract all Mail IDS from the File.

NOTE: In the above program replace mobile number regular expression with MAIL ID regular
expression.

Requirement:
Write a program to display all .txt file names present in E:\javaapps folder.

499
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Program:
importjava.util.regex.*;
import java.io.*;
classRegularExpressionDemo
{
public static void main(String[] args)throws IOException
{
int count=0;
Pattern p=Pattern.compile("[a-zA-Z0-9-$.]+[.]txt");
File f=new File("E:\\javaapps");
String[] s=f.list();
for(String s1:s)
{
Matcher m=p.matcher(s1);
if(m.find()&&m.group().equals(s1))
{
count++;
System.out.println(s1);
}
}
System.out.println(count);
}
}

OP:
input.txt
output.txt
outut.txt
3

Write a regular expressions to represent valid Gmail mail id's :


[a-zA-Z0-9][a-zA-Z0-9-.]*@gmail[.]com

Write a regular expressions to represent all Java language identifiers :


Rules :
1.The length of the identifier should be atleast two.
2.The allowed characters are
a-z
A-Z
500

0-9
#
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3.The first character should be lower case alphabet symbol k-z , and second character should be a digit
divisible by 3
Ans:
[k-z][0369][a-zA-Z0-9#$]*

Write a regular expressions to represent all names starts with 'a'

[aA][a-zA-Z]*
To represent all names starts with 'A' ends with 'K'
[aA][a-zA-Z]*[kK]

501
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Garbage Collection

1.Introduction
2.Approaches to make an Object Eligible for Garbage Collection
3.Approaches for requesting garbage Collector to Run Garbage Collector
4.Finalization
5.Java Heap Memory and its Memory Areas
6.Garbage Collection in Young Generation
7.Garbage Collection in Old generation
8.Types Of Garbage Collectors for Old generation\

Introduction:
-->In old languages like C++ programmer is responsible for both creation and destruction of
objects. Usually programmer is taking very much care while creating object and neglect destruction
of useless objects .Due to his negligence at certain point of time for creation of new object sufficient
memory may not be available and entire application may be crashed due to memory problems.
-->But in java programmer is responsible only for creation of new object and his not responsible for
destruction of objects.
-->Sun people provided one assistant which is always running in the background for destruction at
useless objects. Due to this assistant the chance of failing java program is very rare because of
memory problems.
-->This assistant is nothing but garbage collector. Hence the main objective of GC is to destroy
useless objects.

The ways to make an object eligible for GC:


-->Even through programmer is not responsible for destruction of objects but it is always a good
programming practice to make an object eligible for GC if it is no longer required.
-->An object is eligible for GC if and only if it does not have any references.
The following are various possible ways to make an object eligible for GC:

1.Nullifying the reference variable:


If an object is no longer required then we can make eligible for GC by assigning "null" to all its
reference variables.
Student std1=new Student();
Student std2=new Student();
-----
-----
502

std1=null;
std2=null;
-----
Page

-----

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2.Reassign the reference variable:
If an object is no longer required then reassign all its reference variables to some other objects then
old object is by default eligible for GC.

Student std1=new Student();


Student std2=new Student();
---
---
std1=new Student();
----
----
std2=std1;
---
----

3. Objects created inside a method:


Objects created inside a method are by default eligible for GC once method completes.

EX 1:
class Test{
public static void main(String[] args){
m1();
}
static void m1(){
Student std1=new Student();
Student std2=new Student();
}
}

503
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.Island Of Isolation:
If objects are not having explicit references or the Objects are having internal references are eligible
for GC.
class Test{
Test t;
public static void main(String[] args){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();

t1.t=t2;
t2.t=t3;
t3.t=t1;

t1=null;// No Object is eligible for GC.


t2=null;// No Object is eligible for GC.
t3=null;// All Objects are eligible GC , because, all Explicit references are nullified.
}
}

The methods for requesting JVM to run GC:


--> Once we made an object eligible for GC it may not be destroyed immediately by the GC.
Whenever jvm runs GC then only object will be destroyed by the GC. But when exactly JVM runs
GC we can't expect ,it is vendor dependent.
--> We can request jvm to run garbage collector programmatically, but whether jvm accept our
request or not there is no guaranty. But most of the times JVM will accept our request.

The following are various ways for requesting jvm to run GC:
1)By System class:
System class contains a static method GC for this purpose.

EX: System.gc();

2)By Runtime class:


A java application can communicate with jvm by using Runtime object.

Runtime class is a singleton class present in java.lang. Package.

We can create Runtime object by using factory method getRuntime().


504
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
Runtime r=Runtime.getRuntime();
Once we got Runtime object we can call the following methods on that object.
freeMemory(): returns the free memory present in the heap.
totalMemory(): returns total memory of the heap.
gc(): for requesting jvm to run gc.

EX: importjava.util.Date;
classRuntimeDemo
{
public static void main(String args[]){
Runtime r=Runtime.getRuntime();
System.out.println("total memory of the heap :"+r.totalMemory());
System.out.println("free memory of the heap :"+r.freeMemory());
for(int i=0;i<10000;i++)
{
Date d=new Date();
d=null;
}
System.out.println("free memory of the heap :"+r.freeMemory());
r.gc();
System.out.println("free memory of the heap :"+r.freeMemory());
}
}
OP:
Total memory of the heap: 5177344
Free memory of the heap: 4994920
Free memory of the heap: 4743408
Free memory of the heap: 5049776

NOTE: Runtime class is a singleton class so not create the object to use constructor.
Which of the following are valid ways for requesting jvm to run GC ?
System.gc(); (valid)
Runtime.gc(); (invalid)
(new Runtime).gc(); (invalid)
Runtime.getRuntime().gc(); (valid)

NOTE: gc() method present in System class is static, where as it is instance method in Runtime class.
NOTE: Over Runtime class gc() method , System class gc() method is recommended to use.
505

NOTE: In java it is not possible to find size of an object and address of an object.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Finalization:
-->Just before destroying any object gc always calls finalize() method to perform cleanup activities.
-->If the corresponding class contains finalize() method then it will be executed otherwise Object
class finalize() method will be executed.
which is declared as follows.
protected void finalize() throws Throwable

Case 1:
Just before destroying any object GC calls finalize() method on the object which is eligible for GC
then the corresponding class finalize() method will be executed.
For Example if String object is eligible for GC then String class finalize()method is executed but
not Test class finalize()method.

EX:
class Test
{
public static void main(String args[]){
String s=new String("Durga Software Solutions");
Test t=new Test();
s=null;
System.gc();
System.out.println("End of main.");
}
public void finalize(){
System.out.println("finalize() method is executed");
}
}

OP:
End of main.

In the above program String class finalize()method got executed. Which has empty
implementation.

If we replace String object with Test object then Test class finalize() method will be executed .

The following program is an Example of this.


506
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Test
{
public static void main(String args[]){
String s=new String("Durga Software Solutions");
Test t=new Test();
t=null;
System.gc();
System.out.println("End of main.");

}
public void finalize(){
System.out.println("finalize() method is executed");
}
}

OP:
finalize() method is executed
End of main

Case 2:
We can call finalize() method explicitly then it will be executed just like a normal method call
and object won't be destroyed. But before destroying any object GC always calls finalize()
method.

EX:
class Test
{
public static void main(String args[]){
Test t=new Test();
t.finalize();
t.finalize();
t=null;
System.gc();
System.out.println("End of main.");
}
public void finalize(){
System.out.println("finalize() method called");
507

}
}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


OP:
finalize() method called.
finalize() method called.
finalize() method called.
End of main.
In the above program finalize() method got executed 3 times in that 2 times explicitly by the
programmer and one time by the gc.

Case 3:
finalize() method can be call either by the programmer or by the GC .
If the programmer calls explicitly finalize() method and while executing the finalize() method if
an exception raised and uncaught then the program will be terminated abnormally.

If GC calls finalize() method and while executing the finalize()method if an exception raised and
uncaught then JVM simply ignores that exception and the program will be terminated normally.

EX:
class Test
{
public static void main(String args[]){
Test t=new Test();
//t.finalize();-------line(1)
t=null;
System.gc();
System.out.println("End of main.");
}
public void finalize(){
System.out.println("finalize() method called");
System.out.println(10/0);
}

If we are not comment line1 then programmer calling finalize() method explicitly and while
executing the finalize()method ArithmeticException raised which is uncaught hence the program
terminated abnormally.
If we are comment line1 then GC calls finalize() method and JVM ignores ArithmeticException and
program will be terminated normally.
Which of the following is true?
While executing finalize() method JVM ignores every exception(invalid).
While executing finalize() method JVM ignores only uncaught exception(valid).
508
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Case 4:
On any object GC calls finalize() method only once.

EX: classFinalizeDemo
{
staticFinalizeDemo s;
public static void main(String args[])throws Exception{
FinalizeDemo f=new FinalizeDemo();
System.out.println(f.hashCode());
f=null;
System.gc();
Thread.sleep(5000);
System.out.println(s.hashCode());
s=null;
System.gc();
Thread.sleep(5000);
System.out.println("end of main method");
}
public void finalize()
{
System.out.println("finalize method called");
s=this;
}
}
OP:
D:\Enum>java FinalizeDemo
4072869
finalize method called
4072869
End of main method

NOTE:
The behavior of the GC is vendor dependent and varied from JVM to JVM hence we can't expert exact
answer for the following.
1.What is the algorithm followed by GC.
2.Exactly at what time JVM runs GC.
3.In which order GC identifies the eligible objects.
4.In which order GC destroys the object etc.
5.Whether GC destroys all eligible objects or not.
509

When ever the program runs with low memory then the JVM runs GC, but we can't except exactly at
Page

what time.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Memory Leaks:
In Java applications, if any object is not eligible for Garbage Collection and not utilized in java
applications then that Objects are called as "Memory Leaks".

Heap Memory Structer:


Heap Memory is mainly devided into the following two parts.
1.Young Generation
1.Eden Space
2.Survivor space
S0 Survivor space
S1 Survivor Space
2.Old Generation

When we create object newly, that object will come to Yound Generation, in Yound Generation , that
Object will come to Eden Space, at Eden space Minor Garbage Collection will be performed, if any
object is dereferenced object then Minor Garbage Collection will remove that object. In Eden Space ,
if any object is still live then Garbage Collector will move that live objects to Survivor space, in
Survivor space , initial objects will come to S0 survivor space, there also Minor Garbage Collection
will be performed, where if any object is dereferenced then Garbage Collector will remove that objects
and the remaining objects are moved to S1 Survivor space, there again Minor Garbage Collection is
going on, still any object is live then that object will be moved to Old Generation. In Old Generation,
Major Garbage Collection will be performed.

IN Old Generation, we will perform Garbage Collection by using either of the following Garbage
Collectors.
1.Serial Garbage Collector
2.Parallel Garbage Collector
3.Parallel Old Garbage Collector
4.Concurrent Mark andSweep [CMS] Garbage Collector
5.Garbage First [G1] Garbage Collector

1.Serial Garbage Collector:


This Garbage Collector will follow the following algorithm
1.Mark the Surviving objects in Old Generation.
2.Keep all marked objects at front end of the Heap and keep all the unmarked Objects at
another end[Sweep].
3.Free the memory for unmarked objects[Compact]
510
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


--> It will perform Garbage Collection by using Single Thread.
--> While performing garbage Collection, it will pause all application threads which are
running in java applications.
--> It is suitable for Single Thread Model.
--> It is not suitable for Mulri threaded applications.
--> It is suitable for Standalone applications.
--> It is not suitable for Server side applications.
--> To run this Garbage Collector, it will take less memory.
--> To activate this Garbage Collector we have to use the following Command.

D:\java9>java -XX:+UseSerialGC Test

2.Parallel Garbage Collector / Throughput garbage Collector:


--> It will use the following algorithm to perform Garbage Collection
1.Mark the Surviving objects in Old Generation.
2.Keep all marked objects at front end of the Heap and keep all the unmarked Objects at
another end[Sweep].
3.Free the memory for unmarked objects[Compact]
--> It is default Garbage Collector in JVM.
--> It will use more than one thread to perform garbage Collection.
--> It will be used in Multi Threadded Environment.
--> It is suitable in Server side programming.
--> It will pause all the threads while performing Garbage Collection.
--> It require more memory to perform garbage Collection when compared with Serial Garbage
Collector.

To activate this Garbage Collector we will use the following command.

D:\java9>java -XX:+UseParallelGC Test

3.Parallel Old Garbage Collector:


--> It was introduced in JDK5.0 version.
--> It is same as Parallel Garbage Collector, but, it will use
"Mark-Summary-Compact" algorithm.
1.Mark Survivor objects in Old Generation.
2.Identifies all Survivor objects from the areas where Garbage Collection was performed
previously.
3.Delete Unmarked Objects , that is, Compact.
511

--> To acrtivate this Garbage Collector we have to use the following command.
Page

D:\java9>java -XX:+UseParallelOldGC Test

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4.Concurrent Mark And Sweep[CMS] Garbage Collector:
--> It allows multiple threads to perform garbage Collection.
--> It will not freeze all the application threads while performing Garbage Collection except in
the following two situations.
1.While performing marking the survivor objects.
2.Any changes in the heap memory while performing garbage Collection
-->It will provide very good performance when compared with Parallel Garbage Collector.
-->It is more complicated Garbage Collector and it needs more system Memory.
-->To activate this Garbage Collector we will use the following command.

D:\java9>java -XX:+UseConcMarkSeepGC Test

5.Garbage First [G1] Garbage Collector:


--> It was introduced in JAVA7 version.
--> In this mechanis, it will devide heap memory into no of regions, each region contains no of
Grids, where each grid contains Objects, Here Garbage Collection will be performed over all
the Grids that is Objects , if any useless object is identified then it will be removed.
-->This mechanism is very simple and fast.

-->To activate this mechanism we have to use the following command.

D:\java9>java -XX:+UseG1GC Test

Garbage Collection Optimization options:


-Xms -----> Initial Heap Size.
-Xmx -----> Max Heap Size
-Xmn ----> Size of Young generation
-XX:PermSize ---> Initial Permanent Generation Size
-XX:MaxPermSize ---> Maximum Permanent Generation Size

EX:
D:\java9>java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m
-XX:MaxPermSize=20m -XX:+UseSerialGC Test
512
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Virtual Machine: JVM
It is a Software Simulation of a Machine which can Perform Operations Like a Physical Machine.
EX:
1)JVM Acts as Runtime Engine to Run Java Applications
2)PVM (Parrot VM) Acts as Runtime Engine to Run Scripting Languages Like PEARL.
3)CLR (Common Language Runtime) Acts as Runtime Engine to Run .Net Based Application
4)KVM (Kernel Based Virtual Machine) for Linux Systems

JVM
--->JVM is the Part of JRE.
--->JVM is Responsible to Load and Run Java Applications.
--->JVM Runs Java Byte Code by creating 5 Identical Runtime Areas to execute Class Members.
1.Class Loader Sub System
2.Memory Management System
3.Execution Engine
4.PC-Registers
5.Native Methds Stack

ClassLoader Sub System:


ClassLoader Sub System is Responsible for the following 3 Activities.
1)Loading
2)Linking
3)Initialization

1)Loading:
Loading Means Reading Class Files and Store Corresponding Binary Data in Method Area.
For Each Class File JVM will Store the following Information in Method Area.
1)Fully Qualified Name of the Loaded Class OR Interface OR enum.
2)Fully Qualified Name of its Immediate Parent Class OR Interface OR enum.
3)Whether .class File is related to Class OR Interface OR enum.
4)The Modifiers Information
5)Variable OR Fields Information
6)Method Information
7)Constant Pool Information and so on.

After loading .class File Immediately JVM will Creates an Object of the Type class Class to Represent
Class Level Binary Information on the Heap Memory.
513

The Class Object used by Programmer to got Class Level Information Like Fully Qualified Name of
the Class, Parent Name, Method and Variable Information Etc.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


NOTE: For Every Loader Time Only One Class Object will be Created Even though we are using
Class Multiple Times in Our Application.

2)Linking:
Linking Consists of 3 Activities
1)Verification
2)Preparation
3)Resolution

Verification:
-->It is the Process of ensuring that Binary Representation of a Class is Structurally Correct OR
Not.
-->That is JVM will Check whether .class File generated by Valid Compiler OR Not and whether
.class File is Properly Formatted OR Not.
-->Internally Byte Code Verifier which is Part of ClassLoader Sub System is Responsible for this
Activity.
-->If Verification Fails then we will get Runtime Exception Saying java.lang.VerifyError.

Preparation:
In this Phase JVM will Allocate Memory for the Class Level Static Variables and Assign Default
Values (But Not Original Values Assign to the Variable).

NOTE: Original Values will be assigned in Initialization Phase.

Resolution:
-->It is the Process of Replaced Symbolic References used by the Loaded Type with Original
References.
-->Symbolic References are Resolved into Direct References by searching through Method Area to
Locate the Referenced Entity.

3)Initialization:
In this Phase All Static Variables Assignments with Original Values and Static Block Execution
will be performed from Parent Class to Child Class.

NOTE: While Loading, Linking and Initialization if any Error Occurs then we will get Runtime
Exception Saying LinkageError.
514
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Types of ClassLoaders:
Every ClassLoader Sub System contains the following 3 ClassLoaders.
1)Bootstrap ClassLoader OR Primordial ClassLoader
2)Extension ClassLoader
3)Application ClassLoader OR System ClassLoader

Bootstrap ClassLoader:
-->This ClassLoader is Responsible for loading 4 Java API Classes.
-->That is the Classes Present in rt.jar (runtime.jar).
Location: %JAVA_HOME%\jre\lib\rt.jar
-->This Location is Called Bootstrap Class Path.
-->That is Bootstrap ClassLoader is Responsible to Load Classes from Bootstrap Class Path.
-->Bootstrap ClassLoader is by Default Available with the JVM.
-->It is implemented in Native Languages Like C and C++.

Extension ClassLoader:
-->It is the Child of Bootstrap ClassLoader.
-->This ClassLoader is Responsible to Load Classes from Extension Class Path.
Location: %JAVA_HOME\jre\lib\ext
-->This ClassLoader is implemented in Java and the corresponding .class File Name is
sun.misc.Launcher$extClassLoader.class

Application ClassLoader OR System ClassLoader:


-->It is the Child of Extension ClassLoader.
-->This ClassLoader is Responsible to Load Classes from Application Class Path (Current
Working Directory).
-->It Internally Uses Environment Variable Class Path.
-->Application ClassLoader is implemented in Java and the corresponding .class File Name is
sun.misc.Launcher$appClassLoader.class

How ClassLoader will Work?


-->ClassLoader follows Delegation Hierarchy Principle.
-->Whenever JVM Come Across a Particular Class 1st it will Check whether the corresponding
Class is Already Loaded OR Not.
-->If it is Already Loaded in Method Area then JVM will Use that Loaded Class.
-->If it is Not Already Loaded then JVM Requests ClassLoader Sub System to Load that
Particular Class.
-->Then ClassLoader Sub System Handovers the Request to Application ClassLoader.
-->Application ClassLoader Delegates that Request to Extension ClassLoader and
515

-->ExtenstionClassLoader in-turn Delegates that Request to Bootstrap ClassLoader.


-->Bootstrap ClassLoader Searches in Bootstrap Class Path for the required .class File (jdk/jre/lib)
Page

-->If the required .class is Available, then it will be Loaded. Otherwise Bootstrap ClassLoader
Delegates that Request to Extension ClassLoader.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->Extension ClassLoader will Search in Extension Class Path (jdk/jre/lib/ext). If the required
.class File is Available then it will be Loaded, Otherwise it Delegates that Request to
Application ClassLoader.
-->Application ClassLoader will Search in Application Class Path (Current Working Directory).
If the specified .class is Already Available, then it will be Loaded Otherwise we will get
Runtime Exception Saying ClassNotFoundException OR NoClassDefFoundError.

Memory Management System:


-->While Loading and Running a Java Program JVM required Memory to Store Several Things
Like Byte Code, Objects, Variables, Etc.
-->Total JVM Memory organized in the following 5 Categories:
1)Method Area
2)Heap Area OR Heap Memory
3)Java Stacks Area
4)PC Registers Area
5)Native Method Stacks Area

1)Method Area:
-->Method Area will be Created at the Time of JVM Start - Up.
-->It will be Shared by All Threads (Global Memory).
-->This Memory Area Need Not be Continuous.
-->Method area shows runtime constant pool.
-->Total Class Level Binary Information including Static Variables Stored in Method Area.

2)Heap Area:
-->Programmer Point of View Heap Area is Consider as Important Memory Area.
-->Heap Area will be Created at the Time of JVM Start - Up.
-->Heap Area can be accessed by All Threads (Global OR Sharable Memory).
-->Heap Area Nee Not be Continuous.
-->All Objects and corresponding Instance Variables will be stored in the Heap Area.
-->Every Array in Java is an Object and Hence Arrays Also will be stored in Heap Memory Only.

-->We are able to get Heap memory calculations by using java.lang.Runtime class.
-->Runtime Class Present in java.lang Package and it is a Singleton Class.
-->We can Create Runtime Object by using
Runtime r = Runtime.getRuntime();
-->Once we got Runtime Object we can Call the following Methods on that Object.
1)maxMemory(): Returns Number of Bytes of Max Memory allocated to the Heap.
2)totalMemory(): Returns Number of Bytes of Total (Initial) Memory allocated to the Heap.
3)freeMemory(): Returns Number of Bytes of Free Memory Present in Heap.
516
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class A
{
}
class Test
{
public static void main(String[] args)throws Exception
{
A a1=new A();
A a2=new A();
A a3=new A();

Runtime rt=Runtime.getRuntime();
System.out.println(rt.maxMemory());
System.out.println(rt.totalMemory());
System.out.println(rt.freeMemory());
System.out.println(rt.totalMemory()-rt.freeMemory());
}
}

3)Stack Memory:
-->For Every Thread JVM will Create a Separate Runtime Stack.
-->Runtime Stack will be Created Automatically at the Time of Thread Creation.
-->All Method Calls and corresponding Local Variables, Intermediate Results will be stored in the
Stack.
-->For Every Method Call a Separate Entry will be Added to the Stack and that Entry is Called
Stack Frame OR Activation Record.
-->After completing that Method Call the corresponding Entry from the Stack will be Removed.
-->After completing All Method Calls, Just Before terminating the Thread, the Runtime Stack
will be destroyed by the JVM.
-->The Data stored in the Stack can be accessed by Only the corresponding Thread and it is Not
Available to Other Threads.

4)PC (Program Counter) Registers Area:


-->For Every Thread a Separate PC Register will be Created at the Time of Thread Creation.
-->PC Registers contains Address of Current executing Instruction.
-->Once Instruction Execution Completes Automatically PC Register will be incremented to Hold
Address of Next Instruction.
517
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5)Native Method Stacks:
-->For Every Thread JVM will Create a Separate Native Method Stack.
-->All Native Method Calls invoked by the Thread will be stored in the corresponding Native
Method Stack.

NOTE:
Method Area, Heap Area and Stack Area are considered as Major Memory Areas with Respect to
Programmers Point of View.

Method Area and Heap Area are for JVM. Whereas Stack Area, PC Registers Area and Native Method
Stack Area are for Thread. That is
-->One Separate Heap for Every JVM
-->One Separate Method Area for Every JVM
-->One Separate Stack for Every Thread
-->One Separate PC Register for Every Thread
-->One Separate Native Method Stack for Every Thread

Static Variables will be stored in Method Area whereas Instance Variables will be stored in Heap Area
and Local Variables will be stored in Stack Area.

Execution Engine:
-->This is the Central Component of JVM.
-->Execution Engine is Responsible to Execute Java Class Files.
-->Execution Engine contains 2 Components for executing Java Classes.
1)Interpreter
2)JIT Compiler

Interpreter:
-->It is Responsible to Read Byte Code and Interpret (Convert) into Machine Code (Native Code)
and Execute that Machine Code Line by Line.
-->The Problem with Interpreter is it Interpreters Every Time Even the Same Method Multiple
Times. Which Reduces Performance of the System.
-->To Overcome this Problem SUN People Introduced JIT Compilers in 1.1 Version.
518
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JIT Compiler:
-->The Main Purpose of JIT Compiler is to Improve Performance.
-->Internally JIT Compiler Maintains a Separate Count for Every Method whenever JVM Come
Across any Method Call.
-->First that Method will be interpreted normally by the Interpreter and JIT Compiler Increments
the corresponding Count Variable.
-->This Process will be continued for Every Method.
-->Once if any Method Count Reaches Threshold (The Starting Point for a New State) Value,
then JIT Compiler Identifies that Method Repeatedly used Method (HOT SPOT).
-->Immediately JIT Compiler Compiles that Method and Generates the corresponding Native
Code. Next Time JVM Come Across that Method Call then JVM Directly Use Native Code
and Executes it Instead of interpreting Once Again. So that Performance of the System will be
Improved.
-->The Threshold Count Value varied from JVM to JVM.
-->Profiler which is the Part of JIT Compiler is Responsible to IdentifY HOT SPOTS.

NOTE:
JVM Interprets Total Program Line by Line at least Once.
JIT Compilation is Applicable Only for Repeatedly invoked Methods. But Not for Every Method.

Java Native Interface (JNI):


JNI Acts as Bridge (Mediator) between Java Method Calls and corresponding Native Libraries.

Java Native Library:


Java Native Library is the collection of Native methods which are required in java.
Native method is a method declared in java , but, implemented in non java programming languages
like C , C++,...

519
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Generics
What is the requirement to use Generics in Java applications.
1.To represent one thing if we allow only one data type then it is type safe operation.

EX: Arrays are providing typesafe operation.


Student[] std=new Student[3];
std[0]=new Student();----> Valid
std[1]=new Student();----> Valid
std[2]=new Customer();---> Invalid

To repersent one thing if we allow more than one type then it is Type unsafe operation.

EX: Collection objects are providing type Unsafe operation, because, Collection objects are able to
allow heterogeneous elements.
ArrayList al=new ArrayList();
al.add("AAA");
al.add(new Employee());
al.add(new Integer(10));
al.add(new StringBuffer("CCC"));
In Collections to improve typedness or to provide typesafe operations then we have to use "Generics".

2.If we add elements to the Collection object and if we want to retrive elements from Collection
objects we must perform type casating, because, get(--) methods of Collections are able to retrive
elements in the form of java.lang.Object type.

EX:
ArrayList al=new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
System.out.println(al);
String str=al.get(2);---> Compilation Error, Incompatible types.
String str=(String)al.get(2);--> Valid
520
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we use Generics along with Collections then it is not required to type cast while iterating elements.
The main intention of Generics is,
1.To provide typesafe operations in Collections.
2.To avoid Type casting while retriving elements from Collections.
Generics is a Type parameter specified along with Collections inorder to fix a particular type of
elements to add.

Syntax:
Collection_Name<Generic_Type> ref=new Collection_Name<GenericType>([ Params]);

EX:
ArrayList<String> al=new ArrayList<String>();

The above ArrayList object is able to add only String type elements, if we are trying to add any other
elements then Compiler will rise an error.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
System.out.println(al);
al.add(new Integer(10));---> Error
System.out.println(al);
}
}

Before JDK5.0 version, ArrayList class is


public class ArrayList
{
public void add(Object obj)
{
521

}
public Object get(int index)
Page

{
}

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-----
-----
}

From JDK5.0 version ArrayList class is


public class ArrayList<T>
{
public void add(T t)
{
}
public T get(int index)
{
}
}
In the above ArrayList we can provide any user defained data type to T.

EX1: ArrayList<String> al = new ArrayList<String>();


Here ArrayList class is converted internally as
public class ArrayList<String>
{
public void add(String t)
{
}
public String get(int index)
{
}
}
Here add(-) method is able to take only String elements to add to the ArrayList and get() method will
return only String elements.

al.add("A");---> Valid
al.add("B");---> Valid
al.add("C");---> Valid
al.add(new Integer(10));---> Invalid.
String str=al.get(2); 522
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX2: ArrayList<Integer> al=new ArrayList<Integer>();
Here ArrayList class is converted internally like below.
public class ArrayList<Integer>
{
public void add(Integer t)
{
}
public Integer get(int index)
{
}
}

Here add(-) method is able to take only Integer elements to add to the ArrayList and get() method will
return only Integer elements.

al.add(new Integer(10));---> Valid


al.add(new Integer(20));---> Valid
al.add(30);---> Valid, Autoboxing
al.add("AAA");---> Invalid.
Integer in=al.get(1);--> valid
int i=al.get(2);---> Valid, Auto-Unboxing

If any java class is having Generic type parameter at its declaration then that class is called as "Generic
Class".

NOTE: "Generics" feature is provided by JAVA along with its JDK5.0 version.

EX:
class Account<T>
{
}

Account<Savings> acc=new Account<Savings>();


Account<Current> acc=new Account<Current>();

In the above Generic class declaration, we can use any valid java identifier as Type parameter.
523
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Account<X>
{
}

Status: Valid

EX:
class Account<Durga>
{
}

Status: Valid

In the above Generic class declaration, we can use any no of Type parameters by provide ','
seperator.

EX: class HashMap<K,V>


{
}

WHere 'K' is key.


Where 'V' is value.

EX:
class Account<T>
{
T obj;
public void set(T obj)
{
this.obj=obj;
}
public T get()
{
return obj;
}
public void display_Type()
{
System.out.println(obj.getClass().getName());
524

}
}
Page

class Test
{

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static void main(String[] args)
{
Account<String> acc=new Account<String>();
acc.set("Savings_Account");
System.out.println(acc.get());
acc.display_Type();
}
}

Bounded Types:
In Generic Classes, we can bound the type parameter for a particular range by using "extends"
keyword.

EX1:
class Test<T>
{
}

It is unbounded type, we can pass any type of parameter.


Test<String> t=new Test<String>();
Test<Integer> t=new Test<Integer>();

EX2:
class Test<T extends X>
{
}

If X is a class type then we can pass either X type elements or sub class elements of X type as
parameter types.

EX:
class Payment
{
}
class CashPayment extends Payment
{
}
class CardPayment extends Payment
{
}
525

class Bill<T extends Payment>


{
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Bill<Payment> bill=new Bill<Payment>(); ---> Valid
Bill<CashPayment> bill=new Bill<CashPayment>();--> Valid
Bill<CardPayment> bill=new Bill<CardPayment>();---> Valid

EX:
class Test<T extends Number>
{
}
Test<Number> t=new Test<Number>()---> Valid
Test<Integer> t=new Test<Integer>();----> Valid
Test<Float> t=new Test<Float>();----> Valid
Test<String> t=new Test<String>();---> Invalid

If 'X' is an interface then we are ABle to pass either X type elements of its implementation class
types as parameter.

EX:
interface Java
{
}
class CoreJava implements Java
{
}
class AdvJava implements Java
{
}
class Course<T extends Java>
{
}

Course<Java> crs1=new Course<Java>(); --->Valid


Course<CoreJava> crs2=new Course<CoreJava>();--> Valid
Course<AdvJava> crs3=new Course<AdvJava>();---> Valid

NOTE: Bouded parameters are not allowing "implements" keyword and "super" keyword.
class Test<T implements Runnable>
{
}
526

Status: Invalid
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Test<T super String>
{
}

Status: Invalid

In Generic classes , we can use more than one type as bounded parameter by using '&' symbol.

EX:
class Test<T extends Number & Serializable>
{
}

Here Test class is able to allow the elements which must be either same as NUmber or sub classes to
the number and which must be the implementations of Serializable interface.

Test<Integer> t=new Test<Integer>();--> Valid


Test<Float> t=new Test<Float>();--> Valid
Test<String> t=new Test<String>--> Invalid.

EX:
clas Test<T extends Number & Thread>
{
}

Status: Invalid

Reason: extends keyword will not allow two class types at a time.

EX:
class Test<T extends Runnbale & Serializable>
{
}

Statis: valid.

Reason: extends keyword is able to allow more than one interface type.
527
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
class Test<T extends Number & Runnable>
{
}

Status: Valid.

Reson: Extends is able to allow both class type and interface type , but, first we have to specify class
type then we ahve to specify Interface type.

EX:
class Test<T extends Runnable & Number>
{
}

Status: Invalid.

Reason: extends keyword allows first class_Name then interface_Name

EX:
import java.util.*;
class Account
{
String accNo;
String accName;
String accType;

Account(String accNo, String accName, String accType)


{
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}

}
class Bank
{
public ArrayList<Account> getAccountsList(ArrayList<Account> al)
{
528

al.add(new Account("a111", "AAA", "Savings"));


al.add(new Account("b111", "BBB", "Savings"));
Page

al.add(new Account("c111", "CCC", "Savings"));


al.add(new Account("d111", "DDD", "Savings"));

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


return al;
}
}
class Test
{
public static void main(String[] args)
{
ArrayList<Account> al=new ArrayList<Account>();
Bank bank=new Bank();
ArrayList<Account> acc_List=bank.getAccountsList(al);
System.out.println("ACCNO\tACCNAME\tACCTYPE");
System.out.println("------------------------------");
for(Account acc: acc_List)
{
System.out.println(acc.accNo+"\t"+acc.accName+"\t"+acc.accType);
}
}
}

529
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JDBC

Storage Areas:
As part of the Enterprise Application development it is essential to manage the organizations data
like Employee Details, Customer Details, Products Details..etc

-->To manage the above specified data in enterprise applications we have to use storage areas
(Memory elements). There are two types of Storage areas.

1) Temporary Storage Areas:


These are the memory elements, which will store the data temporarily
Eg: Buffers, Java Objects

2) Permanent Storage Objects:


These are the memory elements which will store data permanently.
Eg: FileSystems, DBMS, DataWareHouses.

File Systems:
It is a System, it will be provided by the local operating System.

--->Due to the above reason File Systems are not suitable for platform independent technologies
like JAVA.
--->File Systems are able to store less volume of the data.
--->File Systems are able to provide less security.
--->File Systems may increases data Redundancy.

--->In case of File Systems Query Language support is not available. So that all the database
operations are complex.

DBMS:
-->Database Management System is very good compare to file System but still it able to store less
data when compared to DataWareHouses.
-->DBMS is very good at the time of storing the data but which is not having Fast Retrieval
Mechanisms.
530
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


DataWareHouses:
When Compared to File Systems and DBMS it is able to store large and large volumes of data.

-->Data ware houses having fast retrieval mechanisms in the form of data mining techniques.

Q) What is the difference between database and database management system?


Ans:DataBase is a memory element to store the data.
Database Management System is a Software System,it can be used to manage the data by
storing it on database and retrieving it form Database.
Database is a collection of interrelated data as a single unit.
DBMS is a collection of interrelated data and a set of programs to access the data.

There are three types of DBMS:


1) RDMS (Relational Database Management Systems)
2) OODBMS (Object Oriented DataBase Management Systems)
3) ORDBMS (Object Relational DataBase Management Systems)

1) Relational Database Management Systems:


-->It is a DBMS,it can be used to represent the data in the form of tables.
-->This DBMS will use SQL3 as a Query Language to perform DataBase Operations.

2) Object Oriented Database Management System:


-->It is Database Management System, It will represents the data in the form of Objects.
-->This database management system will require OQL (Object Query Language)as Query language to
perform database operations.

3) Object Relational DataBase Management System:


-->It is a DataBaseManagement System,it will represents some part of data in the form of Tables
and some other part of the data in the form of objects
-->This DataBaseManagement System will require SQl3 as Query Language to perform database
operations.
Where SQL3 is the combination of SQL2 and OQL
SQL3=SQL2+OQL 531
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Query Processing System:
When we submit an SQL Query to the Database then Database Engine will perform the following
Steps.

Step1:
Query Tokenization:
This Phase will take SQL Query as an Input,divided into no.of tokens and Generate Stream of tokens
as an output.

Step2:
Query Processing:
This phase will take Stream of tokens as an Input,constructs Query Tree with the Tokens,if Query
Tree Success then no Syntax error is available in the provided SQL Query.If Query Tree is not Success
then there are some syntax errors in the provided SQL Query.

Step3:
Query Optimization:
The main purpose of Query Optimization phase is to perform optimization on Query Tree in order to
reduce execution time and to optimize memory utilization.

Step4:
Query Execution:
This phase will take optimized Query Tree as an input and execute the Query by using interpreters.

532
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JDBC (Java DataBase Connectivity):
-->The process of interacting with the database from Java Applications is called as JDBC.

-->JDBC is an API,which will provide very good predefined library to connect with database from
JAVA Applications in order to perform the basic database operations:

-->In case of JDBC Applications we will define the database logic and Java application and we will
send a Java represented database logic to Database Engine.But database engine is unable to
execute the Java represented database logic,it should required the database logic in Query
Language Representations.

-->In the above context, to execute JDBC applications we should require a conversion mechanism to
convert the database logic from Java representations to Query language representations and from
Query language representations to Java representations.

-->In the above situation the required conversion mechanisms are available in the form of a software
called as "Driver".

Driver:
-->Driver is an interface existed between Java application and database to map Java API calls to Query
language API calls and Query language API calls to Java API calls.

533
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->To provide driver as a product Sun MicroSystems has provided Driver as an interface and Sun
MicroSystems.lets the database vendors to provide implementation classes to the driver interface
as part of their database software's.

-->If we want to use Drivers in JDBC applications then we have to get Driver implementation from the
respective database software's.

->There are 180+ numbers of drivers but all these drivers could be classified into the following
Four types
1) Type 1
2) Type 2
3) Type 3
4) Type 4

Type 1 Driver:
-->Type 1 Driver is also called as JDBC-ODBC Driver and Bridge Driver.

-->JDBC-ODBC Driver is a driver provided by Sun Micro Systems as an Implementation to Driver


Interface.
534

-->Sun MicroSystems has provided JDBC-ODBC Driver with the inter dependent on the Microsoft’s
product ODBC Driver.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->ODBC Driver is a Open Specification,it will provide very good environment to interact with any type
of database from JDBC-ODBC Driver.

-->If we want to use JDBC-ODBC Driver in our JDBC Applications first we have to install the
MicroSoft Product ODBC Driver native library.

-->To interact with the database from Java Application if we use JDBC-ODBC Driver then we should
require two types conversions so that JDBC-ODBC Driver is Slower Driver.

-->JDBC-ODBC Driver is highly recommended for stand alone applications,it is not suitable for
web applications,distributed applications and so on.

-->JDBC-ODBC Driver is suggestable for Simple JDBC applications,not for complex JDBC applications.

-->The portability of the JDBC-ODBC Driver is very less.

535
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Type 2 Driver:
-->Type 2 Driver is also called part java,part native driver that is Type 2 Driver was implemented
by using Java implementations and the database vendor provided native library.

-->When compared to Type1 Driver Type2 Driver is faster Driver because it should not require two
times conversions to interact with the Database from Java Applications.

-->When compared to Type1 Driver Type2 driver portability is more.

-->Type2 Driver is still recommended for standalone application not suggestible for web applications
and Enterprise applications.

-->If we want to use Type2 Driver in our Jdbc applications then we have to install the database
vendor provided native library.

-->Type2 Driver is cast full Driver among all the drivers.

-->Type2 Driver's portability is not good when compared to Type3 Driver and Type4 Driver.

536
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3) Type 3 Driver:
-->Type 3 Driver is also called as MiddleWare DataBase Server Access Driver and NetWorkDriver.

-->Type 3 Driver is purely designed for Enterprise applications it is not suggestible for stand alone
applications.

-->Type 3 Driver portability is very good when compared to Type1 and Type2 Driver's.

-->Type 3 Driver will provide very good environment to interact with multiple no.of databases.

-->Type 3 Driver will provide very good environment to switch from one database to another
database without having modifications in client applications.

-->Type 3 Driver should not require any native library installations, it should require the
Compatibility with the application server.

-->Type 3 Driver is fastest Driver when compared to all the Drivers.

537
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4) Type 4 Driver:
-->Type 4 Driver is also called as pure Java Driver and Thin Driver because Type 4 Driver was
implemented completely by using java implementations.

-->Type 4 Driver is the frequent used Driver when compared to all the remaining Drivers.

-->Type 4 Driver is recommended for any type application includes standalone applications,
Network Applications....

-->Type 4 Driver portability is very good when compared to all the remaining Drivers.

-->Type 4 driver should not require any native library dependences and it should require
one time conversion to interact with database from Java Applications.

-->Type 4 is the cheapest Driver among all.

538
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Steps to design JDBC Application:
1) Load and register the Driver.

2) Establish the connection between Java Application.

3) Prepare either Statement or prepared Statement or CallableStatement Objects.

4) Write and execute SQL Queries.

5) Close the connection

Load and Register the Driver:


In general Driver is an interface provided by Sun Microsystems and whose implementation classes
are provided by the Database Vendors as part of their Database Softwares.

-->To load and Register the Driver first we have to make available Driver implementation to
JDBC application.For this we have to set classpath environment variable to the location Where we
have Driver implementation class.

-->If we want to use Type1 Driver provided by Sun MicroSystems in our JDBC applications then it is
not required to set classpath environment variable because Type1 Driver was provided by Sun
MicroSystems as part of Java Software in the form of sun.jdbc.odbc.JdbcOdbcdriver

-->If we want to use Type1 Driver in our JDBC applications then before loading we have to
Configure the Microsoft product odbc Driver.

-->To configure Microsoft product odbc Driver we have to use the following path.

539
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


To setting DSN:-
Start

Control Panel

System and Security

Administrative Tools

Data Sources (ODBC)

user DSN

Click on Add button

Select Microsoft ODBC for the Oracle

Click on Finish button

Provide DSN name (provide any name)

Click on OK

-->To load and register Driver in our Jdbc applications we have to use the following method from
class
‘Class’
Public static Class forName(String class_Name)

EX: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

-->When JVM encounter the above instruction JVM will pickup the parameter that is JDBCOdbcDriver
Class name and JVM will search for its .class file in the current location,if it is not available then
JVM will search for it in Java predefined library.

-->If JVM identify JDBCODBCDriver.class file in Java pre-defined library(rt.jar) then JVM will load
JdbcOdbcDriver class byte code to the memory.
540
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->At the time of loading JdbcOdbcDriver class byte code to the memory JVM will execute a static
block, As part of this JVM wiil execute a method call like DriverManager.registerDriver(--); by the
execution of registerDriver() method only JDBCOdbcDrvier will be available to our Jdbc
applications.

-->In case of Type1 Driver if we use either Jdbc 4.0 version or Jdk 6.0 version then it is optional
To perform loading and register the driver step because JVM will perform Drvier registration
automatically at the time of establishing the connection between Java application and Database.

NOTE:To prepare Jdbc applications Java API has provided the required pre-defined library in the form
of java.sql package so that we have to import this package in our Java file.

Import java.sql.*;

-->java.sql package includes the following pre-defined library to design Jdbc applications.

java.sql package includes the following predefined library:-


I-----interface C-------class

1. Driver (I)
2. DriverManager (C)
3. Connection (I)
4. Statement (I)
5. PreparedStatement (I)
6. ResultSet (I)
7. ResultSetMetaData (I)
8. DatabaseMetaData (I)
9. Savepoint(i)

541
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Establish the Connection between Java application and Database:

-->To establish the connection between Java application and Database we have to use the following
Method from DriverManager class.

Public static Connection getConnection(String url,String db_user_name,String db_password)

EX:Connection con=DriverManager.getConnection(“jdbc:odbc:dsnName”,”system”,”durga”);

-->When JVM encounter the above instruction JVM will access getConnection method,as part of the
getConnection method JVM will access connect() method to establish virtual socket connection

Between Java application and database as per the url which we provided.

-->wher getConnection() method will take three parameters


1.Driver URL
2.Database username
3.Database password
-->In general from Driver to Driver Driver class name and Driver url will varied.

-->If we use Type1 Driver then we have to use the following Driver class name and URL

d-class : sun.jdbc.odbc.JdbcOdbcDriver
url :jdbc:odbc:dsnName

-->In general all the Jdbc Drivers should have an url with the following format.

main-protocol: sub-protocol

-->where main-protocol name should be Jdbc for each and every Driver but the sub protocol name
should be varied from Driver to Driver.

Q) In Jdbc applications getConnecction() method will establish the connection between Java
application and Database and return connection object but connection is an interface how it is
possible to
542
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Create connection object?

Ans:In general in Java technology we are unable to create objects for the interfaces directly,if we
want to accommodate interface data in the form of objects then we have to take either an
implementation class or Anonymous Inner class.

-->If we take implementation class as an alternative then it may allow its own data a part from the
data Declared in interface and implementation class object should have its own identity instead of
interface identity.

-->If we want to create an object with only interface identity and to allow only interface data we have
to use Anonymous inner class as an alternative.

-->In jdbc applications getConnection() method will return connection object by returning
anonymous

Inner class object of connection interface.

NOTE: To create connection object taking an implementation class or anonymous inner class is
Completely depending on the Driver Implementation.

Create either Statement or PreparedStatment or CallableStatement objects as per the


requirement:
As part of the Jdbc applications after establish the connection between Java application and
Database.
We have to prepare SQL Queries,we have to transfer SQL Queries to the databseEngine and we have
to

make Database Engine to execute SQL Queries.

-->To write and execute SQL Queries we have to use same predefined library from Statement
prepared Statement and callableStatement.

-->To use the above required predefined library we have to prepare either Statement or
preparedStatement or CallableStatement objects.
543
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Q)What is the difference between Statement,PreparedStatement and Callable Statement Objects.
Ans:
-->In Jdbc applications when we have a requirement to execute all the SQL Queries independently
we have to use Statement.

-->In jdbc applications when we have a requirement to execute the same SQL Query in the next
Sequence where to improve the performance of JDBC application we will use prepared Statement.

-->In jdbc applications when we have a requirement to access stored procedures and functions
available At Database from Java application we will use Callable Statement object.

-->To prepare Statement object we have to use the following method from Connection.

Public Statement createStatement()

EX: Statement st=con.createStatement();

Where createStatement() method will return Statement object by creating Statement interfaces
Anonymous inner class object.

Write and execute SQL Queries:


1. ExecuteQuery()
2. ExecuteUpdate()
3. Execute()

Q) What are the differences between executeQuery(),executeUpdate() and execute() method?

Ans: Where executeQuery() method can be used to execute “selection group SQL Queries” in order
to fetch(retrieve) data from Database.

-->when JVM encounter executeQuery() method with selection group SQL query then JVM will pickup
Selection group SQL Query,send to JdbcOdbcDriver,it will send to connection.Now connection will
carry that SQL Query to the database engine through Odbc Driver.

-->At database database engine will execute the selection group SQL Query by performing Query
Tokenization,Query parsing,Query optimization and Query Execution.
544

-->By the execution of selection group SQL Query database engine will fetch the data from database
and return to Java Application.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


-->As Java technology is pure object oriented,Java application will store the fetched data in the form
of an object at heap memory called as “ResultSet”.

-->As per the predefined implementation of executeQuery method JVM will return the generated
ResultSet object reference as return value from executeQuery() method.

Public ResultSet executeQuery(String sql_Query) throws SQLException

EX: ResultSet rs=st.executeQuery(“select * from emp1”);

-->where executeUpdate() method can be used to execute updation group SQLQueries in order to
Perform the database operations like create,insert,update,delete,Drop….
-->when JVM encounter updation group SQL Query with execteUpdate() method the JVM will pickup
That Sql Query and send to Database through Database connection.At Database side Database
engine Will execute it,perform updation from Database,identify rowCount value (number of
records got updated) and return to Java application.

-->As per the predefined implementation of executeUpdate() method JVM will return row count
value From executeUpdate() method.

Public int executeUpdate(String sql_Query) throws Exception

EX: int rowCount=st.executeUpdate(“update emp1 set esal=esal+500 where esal<1000”);

-->In Jdbc applications execute() method can be used to execute both selection group and updation
Group SQL Queries.

-->when JVM encounter selection group SQL Query with execute() method then JVM will send
selection Group SQL Query to database engine,where database engine will execute it and send
back the fetched Data to Java Application.
-->In Java application ResultSet object will be created with the fetched data but as per the predefined
implementation of execute() method JVM will return “true” as a Boolean value.
-->when JVM encounter updation group SQL Query as parameter to execute() method then JVM
Will send it to the database engine,where database engine will perform updations on database
and return row Count value to Java application.But as per the predefined implementation of
545

execute() method JVM will return “false” as Boolean value from execute() method
public Boolean execute(String sql_Query) throws SQLException.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


EX:
boolean b1=st.execute (“select * from emp1”);

boolean b2=st.execcute(“update emp1 set esal=esal+500 where esal<10000”);

Close the connection:


In Jdbc applications after the database logic it is convention to close Database connection for this
we have to used the following method.

Public void close() throws SQLException

EX:con.close();

JdbcApp1: The following example demonstrate how to create a table on Database through a JDBC
application by taking table name as Dynamic input.

//import section
import java.sql.*;
import java.io.*;
class JdbcApp1{
public static void main(String args[]) throws Exception{

//load a register driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//establish connection between Java application and database


Connection con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");

//prepare Statement
Statement st=con.createStatement();

//create BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

//take table name as dynamic input


546

System.out.println("Enter table name");


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String tname=br.readLine();

//prepare SQLQuery

String sql="create table " + tname + "(eno number,ename varchar2(10),esal number)";

//execute SQL Query

st.executeUpdate(sql);

System.out.println("table created successfully");

//close the connection

con.close();

}}

547
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JdbcApp2: The following example demonstrates how to insert no.of records on database table by
taking records data as dynamic input.

import java.io.*;
import java.sql.*;
public class JdbcApp2 {
public static void main(String[] args)throws Exception {
Class.forName("oracle.jdbc.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga");
Statement st=con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.print("Employee Number :");
int eno=Integer.parseInt(br.readLine());
System.out.print("Employee Name :");
String ename=br.readLine();
System.out.print("Employee Salary :");
float esal=Float.parseFloat(br.readLine());
System.out.print("Employee Address :");
String eaddr=br.readLine();

st.executeUpdate("insert into emp1 values("+eno+",'"+ename+"',"+esal+",'"+eaddr+"')");


System.out.println("Employee Inserted Successfully");
System.out.print("Onemore Employee[Yes/No]? :");
String option=br.readLine();
if(option.equals("No"))
{
break;
}
}
con.close();
}}

In Jdbc applications if we want to used Type1 driver provided by sun micro systems then we have to
548

use the following Driver class and URL


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


driver.class:sun.jdbc.odbc.JdbcOdbcDriver
url:jdbc:odbc:dsnName
-->Similarly if we want to use Type4 Driver provided by oracle we have to use the following Driver
class and URL
driver_class:oracle.jdbc.driver.OracleDriver
url:jdbc:oracle:thin:@localhost:1521:xe

-->Oracle Driver is a class provided by oracle software in the form of Ojdbc14.jar file
-->Oracle Software has provided ojdbc14.jar file at the following location

C:\oracleexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc.jar

-->If we want to use Type4 Driver provided by oracle in our Jdbc applications we have to set
classpath environment variable to the location where we have ojdbc14.jar

D:\jdbc4>set
classpath=%classpath%;C:\oracleexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar

JdbcApp3: The following example Demonstrate how to perform updations on Database table
through Jdbc Application
import java.io.*;
import java.sql.*;
public class JdbcApp3 {
public static void main(String[] args)throws Exception {
//Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","durga");
Statement st=con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Bonus Amount :");
int bonus_Amt=Integer.parseInt(br.readLine());
System.out.print("Salary Range :");
float sal_Range=Float.parseFloat(br.readLine());
int rowCount=st.executeUpdate
("update emp1 set esal=esal+"+bonus_Amt+" where esal<"+sal_Range);
System.out.println("Employees Updated :"+rowCount);
549

con.close();
}}
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JdbcApp4: The following example demonstrates how to delete no.of records from database table
through a Jdbc application
import java.io.*;
import java.sql.*;
public class JdbcApp4 {
public static void main(String[] args)throws Exception {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","durga");
Statement st=con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Salary Range :");
float sal_Range=Float.parseFloat(br.readLine());
int rowCount=st.executeUpdate("delete from emp1 where esal<"+sal_Range);
System.out.println("Records Deleted :"+rowCount);
con.close();
}
}

-->In jdbc application we will use executeUpdate() method to execute the Updation group SQL
queries like create,insert,update,delete,drop,alter and so on.

-->If we execute the SQL Queries like insert,update and delete then really some no.of record will
be updated on database table then that number will be return as rowCount value from
executeUpdate().

-->If we execute the SQL Queries like create,alter,drop with executeUpdate() method then records
manipulation is not available on database,in this context the return value from executeUpdate()
method is completely depending on the type of Driver which we used in JDBC application.

-->In the above context if we use type1 Driver provided by SunMicroSystems the executeUpdate()
method will return "-1" as rowCount value.

-->For the above requirement if we use Type4 Driver provided by oracle then executeUpdate()
method will return "0" as rowCount value
550
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JdbcApp5:
import java.sql.*;
public class JdbcApp5 {
public static void main(String[] args)throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");
Statement st=con.createStatement();
int rowCount1=st.executeUpdate("create table emp1(eno number)");
System.out.println(rowCount1);
int rowCount2=st.executeUpdate("drop table emp1");
System.out.println(rowCount2);
con.close();
}
}

JdbcApp6:
import java.sql.*;
public class JdbcApp6 {
public static void main(String[] args)throws Exception {
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","durga");
Statement st=con.createStatement();
int rowCount1=st.executeUpdate("create table emp1(eno number)");
System.out.println(rowCount1);
int rowCount2=st.executeUpdate("drop table emp1");
System.out.println(rowCount2);
con.close();
}
} 551
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java 8 & Java 9
New Features
Study Material
552
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java 8 New Features
Java 7 – July 28th 2011
2 Years 7 Months 18 Days

Java 8 - March 18th 2014

Java 9 - September 22nd 2016

Java 10 - 2018

After Java 1.5version, Java 8 is the next major version.


Before Java 8, sun people gave importance only for objects but in 1.8version oracle people gave the importance
for functional aspects of programming to bring its benefits to Java.ie it doesn’t mean Java is functional oriented
programming language.

Java 8 New Features:


1) Lambda Expression
2) Functional Interfaces
3) Default methods
4) Predicates
5) Functions
6) Double colon operator (::)
7) Stream API
8) Date and Time API
Etc…..

553
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Lambda (λ) Expressions
☀ Lambda calculus is a big change in mathematical world which has been introduced in 1930. Because of
benefits of Lambda calculus slowly this concepts started using in programming world. “LISP” is the first
programming which uses Lambda Expression.

☀ The other languages which uses lambda expressions are:


 C#.Net
 C Objective
 C
 C++
 Python
 Ruby etc.
and finally in Java also.

☀ The Main Objective of Lambda Expression is to bring benefits of functional programming into Java.

What is Lambda Expression (λ):


 Lambda Expression is just an anonymous (nameless) function. That means the function which doesn’t have
the name, return type and access modifiers.
 Lambda Expression also known as anonymous functions or closures.

Ex: 1
()  {
public void m1() { sop(“hello”);
sop(“hello”); }
} ()  { sop(“hello”); }
()  sop(“hello”);

Ex:2

public void add(inta, int b) {


sop(a+b); (inta, int b)  sop(a+b);
}
554

 If the type of the parameter can be decided by compiler automatically based on the context then we can
Page

remove types also.


 The above Lambda expression we can rewrite as (a,b)  sop (a+b);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ex: 3

public String str(String str) { (String str)  return str;


return str;
}
(str)  str;

Conclusions:

1) A lambda expression can have zero or more number of parameters (arguments).

Ex:
()  sop(“hello”);
(int a )  sop(a);
(inta, int b)  return a+b;

2) Usually we can specify type of parameter. If the compiler expects the type based on the context then we can
remove type. i.e., programmer is not required.

Ex:
(inta, int b)  sop(a+b);

(a,b)  sop(a+b);

3) If multiple parameters present then these parameters should be separated with comma (,).

4) If zero number of parameters available then we have to use empty parameter [ like ()].

Ex: ()  sop(“hello”);

5) If only one parameter is available and if the compiler can expect the type then we can remove the type and
parenthesis also.

Ex:
555

(int a)  sop(a);

(a) sop(a);
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


A  sop(a);

6) Similar to method body lambda expression body also can contain multiple statements. If more than one
statements present then we have to enclose inside within curly braces. If one statement present then curly
braces are optional.

7) Once we write lambda expression we can call that expression just like a method, for this functional interfaces
are required.

Functional Interfaces
If an interface contain only one abstract method, such type of interfaces are called functional interfaces and the
method is called functional method or single abstract method (SAM).

Ex:
1) Runnable  It contains only run() method
2) Comparable  It contains only compareTo() method
3) ActionListener  It contains only actionPerformed()
4) Callable  It contains only call() method

Inside functional interface in addition to single Abstract method (SAM) we write any number of default and static
methods.

Ex:

1) interface Interf {
2) public abstract void m1();
3) default void m2() {
4) System.out.println (“hello”);
5) }
6) }

In Java 8, Sun Micro System introduced @Functional Interface annotation to specify that the interface is
Functional Interface.

Ex:

@Functional Interface
556

Interface Interf { This code compiles without any compilation errors.


public void m1();
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Inside Functional Interface we can take only one abstract method, if we take more than one abstract method then
compiler raise an error message that is called we will get compilation error.

Ex:

@Functional Interface {
public void m1(); This code gives compilation error.
public void m2();
}

Inside Functional Interface we have to take exactly only one abstract method.If we are not declaring that abstract
method then compiler gives an error message.

Ex:

@Functional Interface {
interface Interface { compilation error
}

Functional Interface with respect to Inheritance:


If an interface extends Functional Interface and child interface doesn’t contain any abstract method then child
interface is also Functional Interface

Ex:

1) @Functional Interface
2) interface A {
3) public void methodOne();
4) }
5) @Functional Interface
6) Interface B extends A {
7) }

In the child interface we can define exactly same parent interface abstract method.

Ex:

1) @Functional Interface
557

2) interface A {
3) public void methodOne();
4) }
Page

5) @Functional Interface
No Compile Time Error
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6) interface B extends A {
7) public void methodOne();
8) }

In the child interface we can’t define any new abstract methods otherwise child interface won’t be Functional
Interface and if we are trying to use @Functional Interface annotation then compiler gives an error message.

1) @Functional Interface {
2) interface A {
3) public void methodOne(); Compiletime Error
4) }
5) @Functional Interface
6) interface B extends A {
7) public void methodTwo();
8) }

Ex:

@Functional Interface
interface A {
No compile time error
public void methodOne();
}
interface B extends A {
public void methodTwo(); This’s Normal interface so that code compiles without error
}

In the above example in both parent & child interface we can write any number of default methods and there are
no restrictions. Restrictions are applicable only for abstract methods.

Functional Interface Vs Lambda Expressions:


Once we write Lambda expressions to invoke it’s functionality, then Functional Interface is required. We can use
Functional Interface reference to refer Lambda Expression.
558

Where ever Functional Interface concept is applicable there we can use Lambda Expressions

Ex:1 Without Lambda Expression


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) interface Interf {
2) public void methodOne() {}
3) public class Demo implements Interface {
4) public void methodOne() {
5) System.out.println(“method one execution”);
6) }
7) public class Test {
8) public static void main(String[] args) {
9) Interfi = new Demo();
10) i.methodOne();
11) }
12) }

Above code With Lambda expression

1) interface Interf {
2) public void methodOne() {}
3) class Test {
4) public static void main(String[] args) {
5) Interfi = ()  System.out.println(“MethodOne Execution”);
6) i.methodOne();
7) }
8) }

Without Lambda Expression

1) interface Interf {
2) public void sum(inta,int b);
3) }
4) class Demo implements Interf {
5) public void sum(inta,int b) {
6) System.out.println(“The sum:” +(a+b));
7) }
8) }
9) public class Test {
10) public static void main(String[] args) {
11) Interfi = new Demo();
559

12) i.sum(20,5);
13) }
Page

14) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Above code With Lambda Expression

1) interface Interf {
2) public void sum(inta, int b);
3) }
4) class Test {
5) public static void main(String[] args) {
6) Interfi = (a,b)  System.out.println(“The Sum:” +(a+b));
7) i.sum(5,10);
8) }
9) }

Without Lambda Expressions

1) interface Interf {
2) publicint square(int x);
3) }
4) class Demo implements Interf {
5) public int square(int x) {
6) return x*x; OR (int x)  x*x
7) }
8) }
9) class Test {
10) public static void main(String[] args) {
11) Interfi = new Demo();
12) System.out.println(“The Square of 7 is: “ +i.square(7));
13) }
14) }

Above code with Lambda Expression


560

1) interface Interf {
2) public int square(int x);
3) }
Page

4) class Test {
5) public static void main(String[] args) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6) Interfi = x  x*x;
7) System.out.println(“The Square of 5 is:”+i.square(5));
8) }
9) }

Without Lambda expression

1) class MyRunnable implements Runnable {


2) public void main() {
3) for(int i=0; i<10; i++) {
4) System.out.println(“Child Thread”);
5) }
6) }
7) }
8) class ThreadDemo {
9) public static void main(String[] args) {
10) Runnable r = new myRunnable();
11) Thread t = new Thread(r);
12) t.start();
13) for(int i=0; i<10; i++) {
14) System.out.println(“Main Thread”)
15) }
16) }
17) }

With Lambda expression

1) class ThreadDemo {
2) public static void main(String[] args) {
3) Runnable r = ()  {
4) for(int i=0; i<10; i++) {
5) System.out.println(“Child Thread”);
6) }
7) };
8) Thread t = new Thread(r);
9) t.start();
10) for(i=0; i<10; i++) {
11) System.out.println(“Main Thread”);
12) }
561

13) }
14) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Anonymous inner classes vs Lambda Expressions
Wherever we are using anonymous inner classes there may be a chance of using Lambda expression to reduce
length of the code and to resolve complexity.

Ex: With anonymous inner class

1) class Test {
2) public static void main(String[] args) {
3) Thread t = new Thread(new Runnable() {
4) public void run() {
5) for(int i=0; i<10; i++) {
6) System.out.println("Child Thread");
7) }
8) }
9) });
10) t.start();
11) for(int i=0; i<10; i++)
12) System.out.println("Main thread");
13) }
14) }

With Lambda expression

1) class Test {
2) public static void main(String[] args) {
3) Thread t = new Thread(()  {
4) for(int i=0; i<10; i++) {
5) System.out.println("Child Thread");
6) }
7) });
8) t.start();
9) for(int i=0; i<10; i++) {
10) System.out.println("Main Thread");
562

11) }
12) }
Page

13) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


What are the advantages of Lambda expression?

☀ We can reduce length of the code so that readability of the code will be improved.
☀ We can resolve complexity of anonymous inner classes.
☀ We can provide Lambda expression in the place of object.
☀ We can pass lambda expression as argument to methods.

Note:

☀ Anonymous inner class can extend concrete class, can extend abstract class, can implement interface with any
number of methods but
☀ Lambda expression can implement an interface with only single abstract method (Functional Interface).
☀ Hence if anonymous inner class implements Functional Interface in that particular case only we can replace
with lambda expressions. Hence wherever anonymous inner class concept is there, it may not possible to
replace with Lambda expressions.
☀ Anonymous inner class! = Lambda Expression

☀ Inside anonymous inner class we can declare instance variables.


☀ Inside anonymous inner class “this” always refers current inner class object(anonymous inner class) but not
related outer class object

Ex:

☀ Inside lambda expression we can’t declare instance variables.


☀ Whatever the variables declare inside lambda expression are simply acts as local variables
☀ Within lambda expression ‘this” keyword represents current outer class object reference (that is current
enclosing class reference in which we declare lambda expression)

Ex:

1) interface Interf {
2) public void m1();
3) }
4) class Test {
563

5) int x = 777;
6) public void m2() {
7) Interfi = () {
Page

8) int x = 888;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


9) System.out.println(x); 888
10) System.out.println(this.x); 777
11) };
12) i.m1();
13) }
14) public static void main(String[] args) {
15) Test t = new Test();
16) t.m2();
17) }
18) }

☀ From lambda expression we can access enclosing class variables and enclosing method variables directly.
☀ The local variables referenced from lambda expression are implicitly final and hence we can’t perform re-
assignment for those local variables otherwise we get compile time error.
Ex:

1) interface Interf {
2) public void m1();
3) }
4) class Test {
5) int x = 10;
6) public void m2() {
7) int y = 20;
8) Interfi = ()  {
9) System.out.println(x); 10
10) System.out.println(y); 20
11) x = 888;
12) y = 999; //CE
13) };
14) i.m1();
15) y = 777;
16) }
17) public static void main(String[] args) {
18) Test t = new Test();
19) t.m2();
20) }
21) }

Differences between anonymous inner classes and Lambda expression


564

Anonymous Inner class Lambda Expression


Page

It’s a class without name It’s a method without name (anonymous

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


function)
Anonymous inner class can extend lambda expression can’t extend
Abstract and concrete classes Abstract and concrete classes
Anonymous inner class can implement lambda expression can implement an
An interface that contains any number of Interface which contains single abstract method
Abstract methods (Functional Interface)
Inside anonymous inner class we can Inside lambda expression we can’t
Declare instance variables. Declare instance variables, whatever the
variables declared are simply acts as local
variables.
Anonymous inner classes can be lambda expressions can’t be instantiated
Instantiated
Inside anonymous inner class “this” Inside lambda expression “this”
Always refers current anonymous Always refers current outer class object. That is
Inner class object but not outer class enclosing class object.
Object.
Anonymous inner class is the best choice Lambda expression is the best Choice if we want
If we want to handle multiple methods. to handle interface
With single abstract method (Functional
Interface).
In the case of anonymous inner class At the time of compilation no dot Class file will be
At the time of compilation a separate generated for Lambda expression. It simply
Dot class file will be generated converts in to private method outer class.
(outerclass$1.class)
Memory allocated on demand Reside in permanent memory of JVM
Whenever we are creating an object (Method Area).

565

Default Methods
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


☀ Until 1.7 version onwards inside interface we can take only public abstract methods and public static final
variables (every method present inside interface is always public and abstract whether we are declaring or
not).
☀ Every variable declared inside interface is always public static final whether we are declaring or not.
☀ But from 1.8 version onwards in addition to these, we can declare default concrete methods also inside
interface, which are also known as defender methods.
☀ We can declare default method with the keyword “default” as follows

1) default void m1(){


2) System.out.println (“Default Method”);
3) }

☀ Interface default methods are by-default available to all implementation classes. Based on requirement
implementation class can use these default methods directly or can override.

Ex:

1) interface Interf {
2) default void m1() {
3) System.out.println("Default Method");
4) }
5) }
6) class Test implements Interf {
7) public static void main(String[] args) {
8) Test t = new Test();
9) t.m1();
10) }
11) }

☀ Default methods also known as defender methods or virtual extension methods.


☀ The main advantage of default methods is without effecting implementation classes we can add new
functionality to the interface (backward compatibility).

Note: We can’t override object class methods as default methods inside interface otherwise we get compile time
error.
566
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ex:

1) interface Interf {
2) default inthashCode() {
3) return 10;
4) }
5) }

CompileTimeError

Reason: Object class methods are by-default available to every Java class hence it’s not required to bring through
default methods.

Default method vs multiple inheritance


Two interfaces can contain default method with same signature then there may be a chance of ambiguity
problem (diamond problem) to the implementation class. To overcome this problem compulsory we should
override default method in the implementation class otherwise we get compile time error.

1) Eg 1:
2) interface Left {
3) default void m1() {
4) System.out.println("Left Default Method");
5) }
6) }
7)
8) Eg 2:
9) interface Right {
10) default void m1() {
11) System.out.println("Right Default Method");
12) }
13) }
14)
15) Eg 3:
16) class Test implements Left, Right {} 567
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


How to override default method in the implementation class?
In the implementation class we can provide complete new implementation or we can call any interface method as
follows.
interfacename.super.m1();

Ex:

1) class Test implements Left, Right {


2) public void m1() {
3) System.out.println("Test Class Method"); OR Left.super.m1();
4) }
5) public static void main(String[] args) {
6) Test t = new Test();
7) t.m1();
8) }
9) }

Differences between interface with default methods and abstract class


Even though we can add concrete methods in the form of default methods to the interface, it won’t be equal to
abstract class.

Interface with Default Methods Abstract Class


Inside interface every variable is Inside abstract class there may be a
Always public static final and there is Chance of instance variables which Are
No chance of instance variables required to the child class.
Interface never talks about state of Abstract class can talk about state of
Object. Object.

Inside interface we can’t declare Inside abstract class we can declare


Constructors. Constructors.
Inside interface we can’t declare Inside abstract class we can declare
Instance and static blocks. Instance and static blocks.
Functional interface with default Abstract class can’t refer lambda
Methods Can refer lambda expression. Expressions.
Inside interface we can’t override Inside abstract class we can override
568

Object class methods. Object class methods.


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Interface with default method != abstract class

Static methods inside interface:


☀ From 1.8 version onwards in addition to default methods we can write static methods also inside interface to
define utility functions.
☀ Interface static methods by-default not available to the implementation classes hence by using
implementation class reference we can’t call interface static
☀ methods. We should call interface static methods by using interface name.

Ex:

1) interface Interf {
2) public static void sum(int a, int b) {
3) System.out.println("The Sum:"+(a+b));
4) }
5) }
6) class Test implements Interf {
7) public static void main(String[] args) {
8) Test t = new Test();
9) t.sum(10, 20); //CE
10) Test.sum(10, 20); //CE
11) Interf.sum(10, 20);
12) }
13) }

☀ As interface static methods by default not available to the implementation class, overriding concept is not
applicable.
☀ Based on our requirement we can define exactly same method in the implementation class, it’s valid but not
overriding.

Ex:1
569

1) interface Interf {
2) public static void m1() {}
3) }
Page

4) class Test implements Interf {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5) public static void m1() {}
6) }

It’s valid but not overriding

Ex:2

1) interface Interf {
2) public static void m1() {}
3) }
4) class Test implements Interf {
5) public void m1() {}
6) }

This’s valid but not overriding

Ex3:

1) class P {
2) private void m1() {}
3) }
4) class C extends P {
5) public void m1() {}
6) }

This’s valid but not overriding

From 1.8 version onwards we can write main() method inside interface and hence we can run interface directly
from the command prompt.

Ex:

1) interface Interf {
570

2) public static void main(String[] args) {


3) System.out.println("Interface Main Method");
4) }
Page

5) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


At the command prompt:
Javac Interf.Java
JavaInterf

Predicates
 A predicate is a function with a single argument and returns boolean value.
 To implement predicate functions in Java, Oracle people introduced Predicate interface in 1.8 version
(i.e.,Predicate<T>).
 Predicate interface present in Java.util.function package.
 It’s a functional interface and it contains only one method i.e., test()

Ex:
interface Predicate<T> {
public boolean test(T t);
}

As predicate is a functional interface and hence it can refers lambda expression

Ex:1 Write a predicate to check whether the given integer is greater than 10 or not.

Ex:
571

public boolean test(Integer I) {


if (I >10) {
Page

return true;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
else {
return false;
}
}

(Integer I)  {
if(I > 10)
return true;
else
return false;
}

I  (I>10);

predicate<Integer> p = I (I >10);


System.out.println (p.test(100)); true
System.out.println (p.test(7)); false
Program:

1) import Java.util.function;
2) class Test {
3) public static void main(String[] args) {
4) predicate<Integer> p = I  (i>10);
5) System.out.println(p.test(100));
6) System.out.println(p.test(7));
7) System.out.println(p.test(true)); //CE
8) }
9) }

# 1 Write a predicate to check the length of given string is greater than 3 or not.
Predicate<String> p = s  (s.length() > 3);
System.out.println (p.test(“rvkb”)); true
System.out.println (p.test(“rk”)); false

#-2 write a predicate to check whether the given collection is empty or not.
Predicate<collection> p = c  c.isEmpty();

Predicate joining
572

It’s possible to join predicates into a single predicate by using the following methods.
Page

and()
or()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


negate()
these are exactly same as logical AND ,OR complement operators

Ex:

1) import Java.util.function.*;
2) class test {
3) public static void main(string[] args) {
4) int[] x = {0, 5, 10, 15, 20, 25, 30};
5) predicate<integer> p1 = i->i>10;
6) predicate<integer> p2=i -> i%2==0;
7) System.out.println("The Numbers Greater Than 10:");
8) m1(p1, x);
9) System.out.println("The Even Numbers Are:");
10) m1(p2, x);
11) System.out.println("The Numbers Not Greater Than 10:");
12) m1(p1.negate(), x);
13) System.out.println("The Numbers Greater Than 10 And Even Are:†);
14) m1(p1.and(p2), x);
15) System.out.println("The Numbers Greater Than 10 OR Even:†);
16) m1(p1.or(p2), x);
17) }
18) public static void m1(predicate<integer>p, int[] x) {
19) for(int x1:x) {
20) if(p.test(x1))
21) System.out.println(x1);
22) }
23) }
24) }

573
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Functions
 Functions are exactly same as predicates except that functions can return any type of result but function
should (can) return only one value and that value can be any type as per our requirement.
 To implement functions oracle people introduced Function interface in 1.8version.
 Function interface present in Java.util.function package.
 Functional interface contains only one method i.e., apply()

interface function(T,R) {
public R apply(T t);
}

Assignment: Write a function to find length of given input string.


Ex:

1) import Java.util.function.*;
2) class Test {
3) public static void main(String[] args) {
4) Function<String, Integer> f = s ->s.length();
5) System.out.println(f.apply("Durga"));
6) System.out.println(f.apply("Soft"));
7) }
8) }

Note: Function is a functional interface and hence it can refer lambda expression.
574
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Differences between predicate and function
Predicate Function
To implement conditional checks To perform certain operation And to
We should go for predicate return some result we Should go for
function.
Predicate can take one type Function can take 2 type Parameters.
Parameter which represents First one represent Input argument
Input argument type. type and Second one represent return
Predicate<T> Type.
Function<T,R>
Predicate interface defines Function interface defines only one
only one method called test() Method called apply().
public boolean test(T t) public R apply(T t)

Predicate can return only Function can return any type of value
boolean value.

Note: Predicate is a boolean valued function and(), or(), negate() are default methods present inside Predicate
interface.

575
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Method And Constructor References by
using :: (Double Colon) Operator
 Functional Interface method can be mapped to our specified method by using :: (double colon) operator. This
is called method reference.
 Our specified method can be either static method or instance method.
 Functional Interface method and our specified method should have same argument types, except this the
remaining things like return type, methodname, modifiers etc are not required to match.

Syntax
If our specified method is static method If the method is instance method
Classname::methodName Objref::methodName
 Functional Interface can refer lambda expression and Functional Interface can also refer method reference.
Hence lambda expression can be replaced with method reference. Hence method reference is alternative
syntax to lambda expression.

Ex: With Lambda Expression

1) class Test {
2) public static void main(String[] args) {
3) Runnable r = ()  {
4) for(int i=0; i<=10; i++) {
5)
System.out.println("Child Thread");
576

6) }
7) };
8) Thread t = new Thread(r);
Page

9) t.start();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10) for(int i=0; i<=10; i++) {
11) System.out.println("Main Thread");
12) }
13) }
14) }

With Method Reference

1) class Test {
2) public static void m1() {
3) for(int i=0; i<=10; i++) {
4) System.out.println("Child Thread");
5) }
6) }
7) public static void main(String[] args) {
8) Runnable r = Test:: m1;
9) Thread t = new Thread(r);
10) t.start();
11) for(int i=0; i<=10; i++) {
12) System.out.println("Main Thread");
13) }
14) }

In the above example Runnable interface run() method referring to Test class static method m1().
Method reference to Instance method:

Ex:

1) interface Interf {
2) public void m1(int i);
3) }
4) class Test {
5) public void m2(int i) {
6) System.out.println("From Method Reference:"+i);
7) }
8) public static void main(String[] args) {
9) Interf f = I ->sop("From Lambda Expression:"+i);
10) f.m1(10);
11) Test t = new Test();
12) Interf i1 = t::m2;
577

13) i1.m1(20);
14) }
Page

15) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above example functional interface method m1() referring to Test class instance method m2().
The main advantage of method reference is we can use already existing code to implement functional interfaces
(code reusability).

Constructor References
We can use :: ( double colon )operator to refer constructors also

Syntax: classname :: new

Ex:
Interf f = sample :: new;
functional interface f referring sample class constructor

Ex:

1) class Sample {
2) private String s;
3) Sample(String s) {
4) this.s = s;
5) System.out.println("Constructor Executed:"+s);
6) }
7) }
8) interface Interf {
9) public Sample get(String s);
10) }
11) class Test {
12) public static void main(String[] args) {
13) Interf f = s -> new Sample(s);
14) f.get("From Lambda Expression");
15) Interf f1 = Sample :: new;
16) f1.get("From Constructor Reference");
17) }
18) }

Note: In method and constructor references compulsory the argument types must be matched.
578
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Streams
To process objects of the collection, in 1.8 version Streams concept introduced.

What is the differences between Java.util.streams and Java.io streams?


java.util streams meant for processing objects from the collection. Ie, it represents a stream of objects from the
collection but Java.io streams meant for processing binary and character data with respect to file. i.e it represents
stream of binary data or character data from the file .hence Java.io streams and Java.util streams both are
different.

What is the difference between collection and stream?

 If we want to represent a group of individual objects as a single entity then We should go for collection.
 If we want to process a group of objects from the collection then we should go for streams.
 We can create a stream object to the collection by using stream() method of Collection interface. stream()
method is a default method added to the Collection in 1.8 version.

default Stream stream()


579

Ex: Stream s = c.stream();


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


 Stream is an interface present in java.util.stream. Once we got the stream, by using that we can process
objects of that collection.

 We can process the objects in the following 2 phases

1.Configuration
2.Processing

1) Configuration:
We can configure either by using filter mechanism or by using map mechanism.

Filtering:
We can configure a filter to filter elements from the collection based on some boolean condition by using
filter()method of Stream interface.

public Stream filter(Predicate<T> t)

here (Predicate<T > t ) can be a boolean valued function/lambda expression

Ex:
Stream s = c.stream();
Stream s1 = s.filter(i -> i%2==0);

Hence to filter elements of collection based on some Boolean condition we should go for filter() method.

Mapping:
If we want to create a separate new object, for every object present in the collection based on our requirement
then we should go for map() method of Stream interface.

public Stream map (Function f);

It can be lambda expression also


580

Ex:
Stream s = c.stream();
Page

Stream s1 = s.map(i-> i+10);


Once we performed configuration we can process objects by using several methods.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2) Processing
processing by collect() method
Processing by count()method
Processing by sorted()method
Processing by min() and max() methods
forEach() method
toArray() method
Stream.of()method

Processing by collect() method


This method collects the elements from the stream and adding to the specified to the collection indicated
(specified) by argument.

Ex 1: To collect only even numbers from the array list

Approach-1: Without Streams

1) import Java.util.*;
2) class Test {
3) public static void main(String[] args) {
4) ArrayList<Integer> l1 = new ArrayList<Integer>();
5) for(int i=0; i<=10; i++) {
6) l1.add(i);
7) }
8) System.out.println(l1);
9) ArrayList<Integer> l2 = new ArrayList<Integer>();
10) for(Integer i:l1) {
11) if(i%2 == 0)
12) l2.add(i);
13) }
14) System.out.println(l2);
15) }
581

16) }

Approach-2: With Streams


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) import Java.util.*;
2) import Java.util.stream.*;
3) class Test {
4) public static void main(String[] args) {
5) ArrayList<Integer> l1 = new ArrayList<Integer>();
6) for(inti=0; i<=10; i++) {
7) l1.add(i);
8) }
9) System.out.println(l1);
10) List<Integer> l2 = l1.stream().filter(i -> i%2==0).collect(Collectors.toList());
11) System.out.println(l2);
12) }
13) }

Ex: Program for map() and collect() Method

1) import Java.util.*;
2) import Java.util.stream.*;
3) class Test {
4) public static void main(String[] args) {
5) ArrayList<String> l = new ArrayList<String>();
6) l.add("rvk"); l.add("rk"); l.add("rkv"); l.add("rvki"); l.add("rvkir");
7) System.out.println(l);
8) List<String> l2 = l.Stream().map(s -
>s.toUpperCase()).collect(Collectors.toList());
9) System.out.println(l2);
10) }
11) }

II.Processing by count()method
This method returns number of elements present in the stream.

public long count()


582

Ex:
long count = l.stream().filter(s ->s.length()==5).count();
Page

sop(“The number of 5 length strings is:”+count);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


III.Processing by sorted()method
If we sort the elements present inside stream then we should go for sorted() method.
the sorting can either default natural sorting order or customized sorting order specified by comparator.
sorted()- default natural sorting order
sorted(Comparator c)-customized sorting order.

Ex:
List<String> l3=l.stream().sorted().collect(Collectors.toList());
sop(“according to default natural sorting order:”+l3);

List<String> l4=l.stream().sorted((s1,s2) -> -s1.compareTo(s2)).collect(Collectors.toList());


sop(“according to customized sorting order:”+l4);

IV.Processing by min() and max() methods


min(Comparator c)
returns minimum value according to specified comparator.

max(Comparator c)
returns maximum value according to specified comparator

Ex:
String min=l.stream().min((s1,s2) -> s1.compareTo(s2)).get();
sop(“minimum value is:”+min);

String max=l.stream().max((s1,s2) -> s1.compareTo(s2)).get();


sop(“maximum value is:”+max);

V.forEach() method
583

This method will not return anything.


This method will take lambda expression as argument and apply that lambda expression for each element present
in the stream.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Ex:
l.stream().forEach(s->sop(s));
l3.stream().forEach(System.out:: println);

Ex:

1) import Java.util.*;
2) import Java.util.stream.*;
3) class Test1 {
4) public static void main(String[] args) {
5) ArrayList<Integer> l1 = new ArrayaList<Integer>();
6) l1.add(0); l1.add(15); l1.add(10); l1.add(5); l1.add(30); l1.add(25); l1.add(20);
7) System.out.println(l1);
8) ArrayList<Integer> l2=l1.stream().map(i-> i+10).collect(Collectors.toList());
9) System.out.println(l2);
10) long count = l1.stream().filter(i->i%2==0).count();
11) System.out.println(count);
12) List<Integer> l3=l1.stream().sorted().collect(Collectors.toList());
13) System.out.println(l3);
14) Comparator<Integer> comp=(i1,i2)->i1.compareTo(i2);
15) List<Integer> l4=l1.stream().sorted(comp).collect(Collectors.toList());
16) System.out.println(l4);
17) Integer min=l1.stream().min(comp).get();
18) System.out.println(min);
19) Integer max=l1.stream().max(comp).get();
20) System.out.println(max);
21) l3.stream().forEach(i->sop(i));
22) l3.stream().forEach(System.out:: println);
23)
24) }
25) }

VI.toArray() method
We can use toArray() method to copy elements present in the stream into specified array

Integer[] ir = l1.stream().toArray(Integer[] :: new);


for(Integer i: ir) {
sop(i);
}
584

VII.Stream.of()method
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


We can also apply a stream for group of values and for arrays.

Ex:
Stream s=Stream.of(99,999,9999,99999);
s.forEach(System.out:: println);

Double[] d={10.0,10.1,10.2,10.3};
Stream s1=Stream.of(d);
s1.forEach(System.out :: println);

Date and Time API: (Joda-Time API)


Until Java 1.7version the classes present in Java.util package to handle Date and Time (like Date, Calendar,
TimeZoneetc) are not up to the mark with respect to convenience and performance.

To overcome this problem in the 1.8version oracle people introduced Joda-Time API. This API developed by
joda.org and available in Java in the form of Java.time package.

# program for to display System Date and time.


585

1) import Java.time.*;
Page

2) public class DateTime {


3) public static void main(String[] args) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4) LocalDate date = LocalDate.now();
5) System.out.println(date);
6) LocalTime time=LocalTime.now();
7) System.out.println(time);
8) }
9) }

O/p:
2015-11-23
12:39:26:587

Once we get LocalDate object we can call the following methods on that object to retrieve Day,month and year
values separately.

Ex:

1) import Java.time.*;
2) class Test {
3) public static void main(String[] args) {
4) LocalDate date = LocalDate.now();
5) System.out.println(date);
6) int dd = date.getDayOfMonth();
7) int mm = date.getMonthValue();
8) int yy = date.getYear();
9) System.out.println(dd+"..."+mm+"..."+yy);
10) System.out.printf("\n%d-%d-%d",dd,mm,yy);
11) }
12) }

Once we get LocalTime object we can call the following methods on that object.

Ex:

1) importJava.time.*;
2) class Test {
3) public static void main(String[] args) {
4) LocalTime time = LocalTime.now();
5) int h = time.getHour();
586

6) int m = time.getMinute();
7) int s = time.getSecond();
Page

8) int n = time.getNano();
9) System.out.printf("\n%d:%d:%d:%d",h,m,s,n);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10) }
11) }

If we want to represent both Date and Time then we should go for LocalDateTime object.

LocalDateTimedt = LocalDateTime.now();
System.out.println(dt);

O/p: 2015-11-23T12:57:24.531

We can represent a particular Date and Time by using LocalDateTime object as follows.

Ex:
LocalDateTime dt1 = LocalDateTime.of(1995,Month.APRIL,28,12,45);
sop(dt1);

Ex:
LocalDateTime dt1=LocalDateTime.of(1995,04,28,12,45);
Sop(dt1);
Sop(“After six months:”+dt.plusMonths(6));
Sop(“Before six months:”+dt.minusMonths(6));

To Represent Zone:
ZoneId object can be used to represent Zone.

Ex:

1) import Java.time.*;
2) class ProgramOne {
3) public static void main(String[] args) {
4) ZoneId zone = ZoneId.systemDefault();
5) System.out.println(zone);
6) }
7) }

We can create ZoneId for a particular zone as follows

Ex:
ZoneId la = ZoneId.of("America/Los_Angeles");
587

ZonedDateTimezt = ZonedDateTime.now(la);
System.out.println(zt);
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Period Object:
Period object can be used to represent quantity of time

Ex:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1989,06,15);
Period p = Period.between(birthday,today);
System.out.printf("age is %d year %d months %d days",p.getYears(),p.getMonths(),p.getDays());

# write a program to check the given year is leap year or not


1) import Java.time.*;
2) public class Leapyear {
3) int n = Integer.parseInt(args[0]);
4) Year y = Year.of(n);
5) if(y.isLeap())
6) System.out.printf("%d is Leap year",n);
7) else
8) System.out.printf("%d is not Leap year",n);
9) }

588
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java 9
New Features

589
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Table of Contents
1) Private Methods in Interfaces …………………………………………………………………………… 40

2) Try With Resources Enhancements ………………………………………………………………….… 47

3) Diamond Operator Enhancements ………………………………………………………………….… 53

4) SafeVarargs Annotation Enhancements …………………………………………………………..… 60

5) Factory Methods for Creating unmodifiable Collections ………………………………….… 64

6) Stream API Enhancements ………………………………………………………………………………… 71

7) The Java Shell (RPEL) ……………………………………………………………………………………….… 80

8) The Java Platform Module System (JPMS) ……………………………………………………..… 130

9) JLINK (JAVA LINKER) ………………………………………………………………………………………… 176

10) Process API Updates ……………………………………………………………………………………..… 180

11) HTTP/2 Client ………………………………………………………………………………………………..… 187


590
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Private Methods in Interfaces
Need Of Default Methods inside interfaces:
Prior to Java 8, Every method present inside interface is always public and abstract whether we are declaring or
not.

1) interface Prior2Java8Interf
2) {
3) public void m1();
4) public void m2();
5) }

Assume this interface is implemented by 1000s of classes and each class provided implementation for both
methods.

1) interface Prior2Java8Interf
2) {
3) public void m1();
4) public void m2();
5) }
6) class Test1 implements Prior2Java8Interf
7) {
8) public void m1(){}
9) public void m2(){}
10) }
11) class Test2 implements Prior2Java8Interf
12) {
13) public void m1(){}
14) public void m2(){}
15) }
16) class Test3 implements Prior2Java8Interf
17) {
18) public void m1(){}
591

19) public void m2(){}


20) }
21) class Test1000 implements Prior2Java8Interf
Page

22) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


23) public void m1(){}
24) public void m2(){}
25) }

It is valid because all implementation classes provided implementation for both m1() and m2().

Assume our programming requirement is we have to extend the functionality of this interface by adding a new
method m3().

1) interface Prior2Java8Interf
2) {
3) public void m1();
4) public void m2();
5) public void m3();
6) }

If we add new method m3() to the interface then all the implementation classes will be effected and won't be
compiled,because every implementation class should implement all methods of interface.

1) class Test1 implements Prior2Java8Interf


2) {
3) public void m1(){}
4) public void m2(){}
5) }

CE: Test1 is not abstract and does not override abstract method
m3() in PriorJava8Interf

Hence prior to java 8,it is impossible to extend the functionality of an existing interface without effecting
implementation classes. JDK 8 Engineers addresses this issue and provides solution in the form of Default
methods, which are also known as Defender methods or Virtual Extension Methods.

How to Declare Default Methods inside interfaces:


In Java 8, inside interface we can define default methods with implementation as follows.

1) interface Java8Interf
2) {
3) public void m1();
592

4) public void m2();


5) default void m3()
6) {
Page

7) //"Default Implementation

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


8) }
9) }

Interface default methods are by-default available to all implementation classes.Based on requirement
implementation class can ignore these methods or use these default methods directly or can override.
Hence the main advantage of Default Methods inside interfaces is, without effecting implementation classes we
can extend functionality of interface by adding new methods (Backward compatibility).

Need of private Methods inside interface:


If several default methods having same common functionality then there may be a chance of duplicate code
(Redundant Code).

Eg:

1) public interface Java8DBLogging


2) {
3) //Abstract Methods List
4) default void logInfo(String message)
5) {
6) Step1: Connect to DataBase
7) Setp2: Log Info Message
8) Setp3: Close the DataBase connection
9) }
10) default void logWarn(String message)
11) {
12) Step1: Connect to DataBase
13) Setp2: Log Warn Message
14) Setp3: Close the DataBase connection
15) }
16) default void logError(String message)
17) {
18) Step1: Connect to DataBase
19) Setp2: Log Error Message
20) Setp3: Close the DataBase connection
21) }
22) default void logFatal(String message)
23) {
24) Step1: Connect to DataBase
593

25) Setp2: Log Fatal Message


26) Setp3: Close the DataBase connection
Page

27) }
28) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above code all log methods having some common code,which increases length of the code and reduces
readability.It creates maintenance problems also. In Java8 there is no solution for this.

How to declare private Methods inside interface:


JDK 9 Engineers addresses this issue and provided private methods inside interfaces. We can seperate that
common code into a private method and we can call that private method from every default method which
required that functionality.

1) public interface Java9DBLogging


2) {
3) //Abstract Methods List
4) default void logInfo(String message)
5) {
6) log(message,"INFO");
7) }
8) default void logWarn(String message)
9) {
10) log(message,"WARN");
11) }
12) default void logError(String message)
13) {
14) log(message,"ERROR");
15) }
16) default void logFatal(String message)
17) {
18) log(message,"FATAL");
19) }
20) private void log(String msg,String logLevel)
21) {
22) Step1: Connect to DataBase
23) Step2: Log Message with the Provided logLevel
24) Step3: Close the DataBase Connection
25) }
26) }
594

Demo Program for private instance methods inside interface:


private instance methods will provide code reusability for default methods.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) interface Java9Interf
2) {
3) default void m1()
4) {
5) m3();
6) }
7) default void m2()
8) {
9) m3();
10) }
11) private void m3()
12) {
13) System.out.println("common functionality of methods m1 & m2");
14) }
15) }
16) class Test implements Java9Interf
17) {
18) public static void main(String[] args)
19) {
20) Test t = new Test();
21) t.m1();
22) t.m2();
23) //t.m3(); ==>CE
24) }
25) }

Output:
D:\java9durga>java Test
common functionality of methods m1 & m2
common functionality of methods m1 & m2

Inside Java 8 interaces, we can take public static methods also.If several static methods having some common
functionality, we can seperate that common functionality into a private static method and we can call that private
static method from public static methods where ever it is required.

Demo Program for private static methods:


private static methods will provide code reusability for public static methods.
595

1) interface Java9Interf
2) {
3) public static void m1()
Page

4) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5) m3();
6) }
7) public static void m2()
8) {
9) m3();
10) }
11) private static void m3()
12) {
13) System.out.println("common functionality of methods m1 & m2");
14) }
15) }
16) class Test implements Java9Interf
17) {
18) public static void main(String[] args)
19) {
20) Java9Interf.m1();
21) Java9Interf.m2();
22) }
23) }

Output:
D:\durga_classes>java Test
common functionality of methods m1 & m2
common functionality of methods m1 & m2

Note: Interface static methods should be called by using interface name only even in implementation classes
also.

Advantages of private Methods inside interfaces:


The main advantages of private methods inside interfaces are:

1. Code Reusability
2. We can expose only intended methods to the API clients (Implementation classes), because interface private
methods are not visible to the implementation classses.

Note:

1. private methods cannot be abstract and hence compulsory private methods should have the body.
596

2. private method inside interface can be either static or non-static.


Page

JDK 7 vs JDK 8 vs JDK9:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1. Prior to java 8, we can declare only public-abstract methods and public-static-final variables inside interfaces.

1) interface Prior2Java8Interface
2) {
3) public-static-final variables
4) public-abstract methods
5) }

2. In Java 8 ,we can declare default and public-static methods also inside interface.

1) interface Java8Interface
2) {
3) public-static-final variables
4) public-abstract methods
5) default methods with implementation
6) public static methods with implementation
7) }

3. In Java 9, We can declare private instance and private static methods also inside interface.

1) interface Java9Interface
2) {
3) public-static-final variables
4) public-abstract methods
5) default methods with implementation
6) public static methods with implementation
7) private instance methods with implementation
8) private static methods with implementation
9) }

Note: The main advantage of private methods inside interface is Code Reusablility without effecting
implemenation classes.

597
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Try with Resources Enahancements
Need of Try with Resources:
Until 1.6 version it is highly recommended to write finally block to close all resources which are open as part of try
block.

1) BufferedReader br=null;
2) try
3) {
4) br=new BufferedReader(new FileReader("abc.txt"));
5) //use br based on our requirements
6) }
7) catch(IOException e)
8) {
9) // handling code
10) }
11) finally
12) {
598

13) if(br != null)


14) br.close();
15) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Problems in this Approach:
1. Compulsory programmer is required to close all opened resources which increases the complexity of the
programming
2. Compulsory we should write finally block explicitly which increases length of the code and reduces readability.

To overcome these problems Sun People introduced "try with resources" in 1.7 version.

Try with Resources:


The main advantage of "try with resources" is the resources which are opened as part of try block will be closed
automatically Once the control reaches end of the try block either normally or abnormally and hence we are not
required to close explicitly so that the complexity of programming will be reduced. It is not required to write
finally block explicitly and hence length of the code will be reduced and readability will be improved.

1) try(BufferedReader br=new BufferedReader(new FileReader("abc.txt")))


2) {
3) use be based on our requirement, br will be closed automatically , Onec control reaches
end of try either normally or abnormally and we are not required to close explicitly
4) }
5) catch(IOException e)
6) {
7) // handling code
8) }

Conclusions:
1. We can declare any number of resources but all these resources should be separated with ; (semicolon)

1) try(R1 ; R2 ; R3)
2) {
3) -------------
4) }

2. All resources should be AutoCloseable resources. A resource is said to be auto closable if and only if the
corresponding class implements the java.lang.AutoCloseable interface either directly or indirectly.

All database related, network related and file io related resources already implemented AutoCloseable interface.
599

Being a programmer we should aware this point and we are not required to do anything extra.

3. AutoCloseable interface introduced in Java 1.7 Version and it contains only one method: close()
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4. All resource reference variables should be final or effectively final and hence we can't perform reassignment
within the try block.

1) try(BufferedReader br=new BufferedReader(new FileReader("abc.txt")))


2) {
3) br=new BufferedReader(new FileReader("abc.txt"));
4) }

CE : Can't reassign a value to final variable br

5. Untill 1.6 version try should be followed by either catch or finally but in 1.7 version we can take only try with
resource without catch or finally

1) try(R)
2) {
3) //valid
4) }

6. The main advantage of "try with resources" is finally block will become dummy because we are not required to
close resources of explicitly.

Problems with JDK 7 Try with Resources:


1. The resource reference variables which are created outside of try block cannot be used directly in try with
resources.

1) BufferedReader br=new BufferedReader(new FileReader("abc.txt"))


2) try(br)
3) {
4) // Risky code
5) }

This syntax is invalid in until java 1.8V.

We should create the resource in try block primary list or we should declare with new reference variable in try
block. i.e. Resource reference variable should be local to try block.

Solution-1: Creation of Resource in try block primary list


600

1) try(BufferedReader br=new BufferedReader(new FileReader("abc.txt")))


2) {
Page

3) // It is valid syntax in java 1.8V

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4) }

Solution-2: Assign resource with new reference variable


1) BufferedReader br=new BufferedReader(new FileReader("abc.txt"))
2) try(BufferedReader br1=br)
3) {
4) // It is valid syntax in java 1.8V
5) }

But from JDK 9 onwards we can use the resource reference variables which are created outside of try block
directly in try block resources list. i.e. The resource reference variables need not be local to try block.

1) BufferedReader br=new BufferedReader(new FileReader("abc.txt"))


2) try(br)
3) {
4) // It is valid in JDK 9 but in valid until JDK 1.8V
5) }

But make sure resource(br) should be either final or effectively final. Effectively final means we should not
perform reassignment.

This enhancement reduces length of the code and increases readability.

1) MyResource r1 = new MyResource();


2) MyResource r2 = new MyResource();
3) MyResource r3 = new MyResource();
4) try(r1,r2,r3)
5) {
6) }

Demo Program:

1) class MyResource implements AutoCloseable


2) {
3) MyResource()
4) {
5) System.out.println("Resource Creation...");
601

6) }
7) public void doProcess()
Page

8) {
9) System.out.println("Resource Processing...");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10)
11) }
12) public void close()
13) {
14) System.out.println("Resource Closing...");
15) }
16) }
17) class Test
18) {
19) public static void preJDK7()
20) {
21) MyResource r=null;
22) try
23) {
24) r=new MyResource();
25) r.doProcess();
26) }
27) catch (Exception e)
28) {
29) System.out.println("Handling:"+e);
30) }
31) finally
32) {
33) try
34) {
35) if (r!=null)
36) {
37) r.close();
38) }
39) }
40) catch (Exception e)
41) {
42) System.out.println("Handling:"+e);
43) }
44) }
45) }
46) public static void JDK7()
47) {
48) try(MyResource r=new MyResource())
49) {
602

50) r.doProcess();
51) }
Page

52) catch(Exception e)
53) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


54) System.out.println("Handling:"+e);
55) }
56) }
57) public static void JDK9()
58) {
59) MyResource r= new MyResource();
60) try(r)
61) {
62) r.doProcess();
63) }
64) catch(Exception e)
65) {
66) System.out.println("Handling:"+e);
67) }
68) }
69) public static void multipleJDK9()
70) {
71) MyResource r1= new MyResource();
72) MyResource r2= new MyResource();
73) MyResource r3= new MyResource();
74) MyResource r4= new MyResource();
75) try(r1;r2;r3;r4)
76) {
77) r1.doProcess();
78) r2.doProcess();
79) r3.doProcess();
80) r4.doProcess();
81) }
82) catch(Exception e)
83) {
84) System.out.println("Handling:"+e);
85) }
86) }
87) public static void main(String[] args)
88) {
89) System.out.println("Program Execution With PreJDK7");
90) preJDK7();
91)
92) System.out.println("Program Execution With JDK7");
93) JDK7();
603

94)
95) System.out.println("Program Execution With JDK9");
Page

96) JDK9();
97) System.out.println("Program Execution Multiple Resources With JDK9");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


98) multipleJDK9();
99) }
100) }

Output:
Program Execution With PreJDK7
Resource Creation...
Resource Processing...
Resource Closing...
Program Execution With JDK7
Resource Creation...
Resource Processing...
Resource Closing...
Program Execution With JDK9
Resource Creation...
Resource Processing...
Resource Closing...
Program Execution Multiple Resources With JDK9
Resource Creation...
Resource Creation...
Resource Creation...
Resource Creation...
Resource Processing...
Resource Processing...
Resource Processing...
Resource Processing...
Resource Closing...
Resource Closing...
Resource Closing...
Resource Closing...

Diamond Operator Enhancements


604

This enhancement is as the part of Milling Project Coin (JEP 213).


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Before understanding this enhancement, we should aware Generics concept, which has been introduced in java
1.5 version.

The main objectives of Generics are:

1. To provide Type Safety


2. To resolve Type Casting Problems.

Case 1: Type-Safety
Arrays are always type safe. i.e we can give the guarantee for the type of elements present inside array. For
example if our programming requirement is to hold String type of objects, it is recommended to use String array.
For the string array we can add only string type of objects. By mistake if we are trying to add any other type we
will get compile time error.

Eg:

1) String[] s = new String[100];


2) s[0] = "Durga";
3) s[1] = "Pavan";
4) s[2] = new Integer(10);//error: incompatible types: Integer cannot be converted to String

String[] can contains only String type of elements. Hence, we can always give guarantee for the type of elements
present inside array. Due to this arrays are safe to use with respect to type. Hence arrays are type safe.

But collections are not type safe that is we can't give any guarantee for the type of elements present inside
collection. For example if our programming requirement is to hold only string type of objects, and if we choose
ArrayList, by mistake if we are trying to add any other type we won't get any compile time error but the program
may fail at runtime.

1) ArrayList l = new ArrayList();


2) l.add("Durga");
3) l.add("Pavan");
4) l.add(new Integer(10));
5) ....
6) String name1=(String)l.get(0);
7) String name2=(String)l.get(1);
8) String name3=(String)l.get(2);//RE: java.lang.ClassCastException

Hence we can't give any guarantee for the type of elements present inside collections. Due to this collections are
605

not safe to use with respect to type, i.e collections are not Type-Safe.
Case 2: Type-Casting
Page

In the case of array at the time of retrieval it is not required to perform any type casting.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) String[] s = new String[100];
2) s[0] = "Durga";
3) s[1] = "Pavan";
4) ...
5) String name1=s[0];//Type casting is not required.

But in the case of collection at the time of retrieval compulsory we should perform type casting otherwise we will
get compile time error.

Eg:

1) ArrayList l = new ArrayList();


2) l.add("Durga");
3) l.add("Pavan");
4) ....
5) String name1=l.get(0);//error: incompatible types: Object cannot be converted to String
6) String name1=(String)l.get(0);//valid

Hence in Collections Type Casting is bigger headache.

To overcome the above problems of collections(type-safety, type casting),Java people introduced Generics
concept in 1.5version.Hence the main objectives of Generics are:

1. To provide Type Safety to the collections.


2. To resolve Type casting problems.

Example for Generic Collection:


To hold only string type of objects, we can create a generic version of ArrayList as follows.

ArrayList<String> l = new ArrayList<String>();


Here String is called Parameter Type.

For this ArrayList we can add only string type of objects. By mistake if we are trying to add any other type then we
will get compile time error.

1) l.add("Durga");//valid
2) l.add("Ravi");//valid
3) l.add(new Integer(10));//error: no suitable method found for add(Integer)
606

Hence, through generics we are getting type safety.


Page

At the time of retrieval it is not required to perform any type casting we can assign elements directly to string
type variables.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


String name1 = l.get(0);//valid and Type Casting is not required.

Hence, through generic syntax we can resolve type casting problems.

Difference between Generic and Non-Generic Collections


ArrayList l = new ArrayList(); ArrayList<String> l = new ArrayList<String>();
It is Non Generic version of ArrayList It is Generic version of ArrayList
For this ArrayList we can add any type of object For this ArrayList we can add only String type of
and hence it is not Type-Safe. Objects. By mistake if we are trying to add any
other type,we will get compile time error.
At the time of retrieval compulsory we should At the time of retrieval, we are not required to
perform Type casting. perform Type casting.

Java 7 Diamond Operator (<>):


Diamond Operator '<>' was introduced in JDK 7 under project Coin.
The main objective of Diamond Operator is to instantiate generic classes very easily.

Prior to Java 7, Programmer compulsory should explicitly include the Type of generic class in the Type Parameter
of the constructor.

ArrayList<String> l = new ArrayList<String>();

Whenever we are using Diamond Operator, then the compiler will consider the type automatically based on
context, Which is also known as Type inference. We are not required to specify Type Parameter of the Constructor
explicitly.

ArrayList<String> l = new ArrayList<>();

Hence the main advantage of Diamond Operator is we are not required to speicfy the type parameter in the
constructor explicitly,length of the code will be reduced and readability will be improved.

Eg 2:
List<Map<String,Integer>> l = new ArrayList<Map<String,Integer>>();

can be writtern with Diamond operator as follows

List<Map<String,Integer>> l = new ArrayList<>();


607

But until Java 8 version we cannot apply diamond operator for Anonymous Generic classes. But in Java 9, we can
use.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Usage of Diamond Operator for Anonymous Classes:
In JDK 9, Usage of Diamond Operator extended to Anonymous classes also.

Anonymous class:
Sometimes we can declare classes without having the name, such type of nameless classes are called Anonymous
Classes.

Eg 1:

1) Thread t = new Thread()


2) {
3) };

We are creating a child class that extends Thread class without name(Anonymous class) and we are creating
object for that child class.

Eg 2:

1) Runnable r = new Runnable()


2) {
3) };

We are creating an implementation class for Runnable interface without name(Anonymous class) and we are
creating object for that implementation class.

Eg 3:

1) ArrayList<String> l = new ArrayList<String>()


2) {
3) };

We are creating a child class that extends ArrayList class without name(Anonymous class) and we are creating
object for that child class.

From JDK 9 onwards we can use Diamond Operator for Anonymous Classes also.
608

1) ArrayList<String> l = new ArrayList<>()


2) {
Page

3) };

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


It is valid in Java 9 but invalid in Java 8.

Demo Program - 1: To demonstrate usage of diamond operator for Anonymous Class

1) class MyGenClass<T>
2) {
3) T obj;
4) public MyGenClass(T obj)
5) {
6) this.obj = obj;
7) }
8)
9) public T getObj()
10) {
11) return obj;
12) }
13) public void process()
14) {
15) System.out.println("Processing obj...");
16) }
17) }
18) public class Test
19) {
20) public static void main(String[] args)
21) {
22) MyGenClass<String> c1 = new MyGenClass<String>("Durga")
23) {
24) public void process()
25) {
26) System.out.println("Processing... " + getObj());
27) }
28) };
29) c1.process();
30)
31) MyGenClass<String> c2 = new MyGenClass<>("Pavan")
32) {
33) public void process()
609

34) {
35) System.out.println("Processing... " + getObj());
Page

36) }
37) };

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


38) c2.process();
39) }
40) }

Output:

Processing... Durga
Processing... Pavan

If we compile the above program according to Java 1.8 version,then we will get compile time error
D:\durga_classes>javac -source 1.8 Test.java
error: cannot infer type arguments for MyGenClass<T>
MyGenClass<String> c2 = new MyGenClass<>("Pavan")
^
reason: cannot use '<>' with anonymous inner classes in -source 1.8
(use -source 9 or higher to enable '<>' with anonymous inner classes)

Demo Program - 2: To demonstrate usage of diamond operator for Anonymous Class

1) import java.util.Iterator;
2) import java.util.NoSuchElementException;
3) public class DiamondOperatorDemo
4) {
5) public static void main(String[] args)
6) {
7) String[] animals = { "Dog", "Cat", "Rat", "Tiger","Elephant" };
8) Iterator<String> iter = new Iterator<>()
9) {
10) int i = 0;
11) public boolean hasNext()
12) {
13) return i < animals.length;
14) }
15) public String next()
16) {
17) if (!hasNext())
18) throw new NoSuchElementException();
19) return animals[i++];
20) }
21) };
610

22) while (iter.hasNext())


23) {
Page

24) System.out.println(iter.next());
25) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


26) }
27) }

Output:

Dog
Cat
Rat
Tiger
Elephant

Note - 1:

1) ArrayList<String> preJava7 = new ArrayList<String>();


2) ArrayList<String> java7 = new ArrayList<>();
3) ArrayList<String> java9 = new ArrayList<>()
4) {
5) };

Note - 2:

Be Ready for Partial Diamond Operator in the next versions of Java, as the part of Project "Amber". Open JDK
people already working on this.

Eg: new Test<String,_>();

611
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


SafeVarargs Annotation Enhancements
This SafeVarargs Annotation was introduced in Java 7.
Prior to Java 9, we can use this annotation for final methods, static methods and constructors.
But from Java 9 onwards we can use for private methods also.

To understand the importance of this annotation, first we should aware var-arg methods and heap pollution
problem.

What is var-arg method?


Until 1.4 version, we can't declared a method with variable number of arguments. If there is a change in no of
arguments compulsory we have to define a new method. This approach increases length of the code and reduces
readability.

But from 1.5 version onwards, we can declare a method with variable number of arguments, such type of
methods are called var-arg methods.

1) public class Test


2) {
3) public static void m1(int... x)
4) {
612

5) System.out.println("var-arg method");
6) }
Page

7) public static void main(String[] args)


8) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


9) m1();
10) m1(10);
11) m1(10,20,30);
12) }
13) }

Output
var-arg method
var-arg method
var-arg method

Internally var-arg parameter will be converted into array.

1) public class Test


2) {
3) public static void sum(int... x)
4) {
5) int total=0;
6) for(int x1 : x)
7) {
8) total=total+x1;
9) }
10) System.out.println("The Sum:"+ total);
11) }
12) public static void main(String[] args)
13) {
14) sum();
15) sum(10);
16) sum(10,20,30);
17) }
18) }

Output
The Sum:0
The Sum:10
The Sum:60

Var-arg method with Generic Type:


613

If we use var-arg methods with Generic Type then there may be a chance of Heap Pollution.
At runtime if one type variable trying to point to another type value, then there may be a chance of
ClasssCastException. This problem is called Heap Pollution.
Page

In our code, if there is any chance of heap pollution then compiler will generate warnings.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) import java.util.*;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) List<String> l1= Arrays.asList("A","B");
7) List<String> l2= Arrays.asList("C","D");
8) m1(l1,l2);
9) }
10) public static void m1(List<String>... l)//argument will become List<String>[]
11) {
12) Object[] a = l;// we can assign List[] to Object[]
13) a[0]=Arrays.asList(10,20);
14) String name=(String)l[0].get(0);//String type pointing to Integer type
15) System.out.println(name);
16) }
17) }

Compilation:
javac Test.java

Note: Test.java uses unchecked or unsafe operations.


Note: Recompile with -Xlint:unchecked for details.
javac -Xlint:unchecked Test.java
warning: [unchecked] unchecked generic array creation for varargs parameter of type List<String>[]
m1(l1,l2);
^
warning: [unchecked] Possible heap pollution from parameterized vararg type List<String>
public static void m1(List<String>... l)
^
2 warnings

Execution:
java Test
RE: java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast to java.base/java.lang.String

In the above program at runtime, String type variable name is trying to point to Integer type,which causes Heap
Pollution and results ClassCastException.

String name = (String)l[0].get(0);


614

Need of @SafeVarargs Annotation:


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Very few Var-arg Methods cause Heap Pollution, not all the var-arg methods. If we know that our method won't
cause Heap Pollution, then we can suppress compiler warnings with @SafeVarargs annotation.

1) import java.util.*;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) List<String> l1= Arrays.asList("A","B");
7) List<String> l2= Arrays.asList("C","D");
8) m1(l1,l2);
9) }
10) @SafeVarargs
11) public static void m1(List<String>... l)
12) {
13) for(List<String> l1: l)
14) {
15) System.out.println(l1);
16) }
17) }
18) }

Output:
[A, B]
[C, D]

In the program, inside m1() method we are not performing any reassignments. Hence there is no chance of Heap
Pollution Problem. Hence we can suppress Compiler generated warnings with @SafeVarargs annotation.

Note: At compile time observe the difference with and without SafeVarargs Annotation.

Java 9 Enhancements to @SafeVarargs Annotation:


@SafeVarargs Annotation introduced in Java 7.
Unitl Java 8, this annotation is applicable only for static methods, final methods and constructors.
But from Java 9 onwards, we can also use for private instance methods also.
615

1) import java.util.*;
2) public class Test
3) {
Page

4) @SafeVarargs //valid

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5) public Test(List<String>... l)
6) {
7) }
8) @SafeVarargs //valid
9) public static void m1(List<String>... l)
10) {
11) }
12) @SafeVarargs //valid
13) public final void m2(List<String>... l)
14) {
15) }
16) @SafeVarargs //valid in Java 9 but not in Java 8
17) private void m3(List<String>... l) {
18) }
19) }

javac -source 1.8 Test.java


error: Invalid SafeVarargs annotation. Instance method m3(List<String>...) is not final.
private void m3(List<String>... l)
^
javac -source 1.9 Test.java
We won't get any compile time error.

FAQs:
Q1. For which purpose we can use @SafeVarargs annotation?
Q2. What is Heap Pollution?
Factory Methods for creating unmodifiable Collections
List: An indexed Collection of elements where duplicates are allowed and insertion order is preserved.

Set: An unordered Collection of elements where duplicates are not allowed and insertion order is not preserved.

Map: A Map is a collection of key-value pairs and each key-value pair is called Entry.Entry is an inner interface
present inside Map interface.Duplicate keys are not allowed,but values can be duplicated.

As the part of programming requirement, it is very common to use Immutable Collection objects to improve
Memory utilization and performance.
616

Prior to Java 9, we can create unmodifiable Collection objects as follows


Page

Eg 1: Creation of unmodifiable List object

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) List<String> beers=new ArrayList<String>();
2) beers.add("KF");
3) beers.add("FO");
4) beers.add("RC");
5) beers.add("FO");
6) beers =Collections.unmodifiableList(beers);

Eg 2: Creation of unmodifiable Set Object

1) Set<String> beers=new HashSet<String>();


2) beers.add("KF");
3) beers.add("KO");
4) beers.add("RC");
5) beers.add("FO");
6) beers =Collections.unmodifiableSet(beers);

Eg 3: Creation of unmodifiable Map object

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


2) map.put("A","Apple");
3) map.put("B","Banana");
4) map.put("C","Cat");
5) map.put("D","Dog");
6) map =Collections.unmodifiableMap(map);

This way of creating unmodifiable Collections is verbose and not convenient.It increases length of the code and
reduces readability.

JDK Engineers addresses this problem and introduced several factory methods for creating unmodifiable
collections.

Creation of unmodifiable List (Immutable List) with Java 9 Factory Methods:

Java 9 List interface defines several factory methods for this.

1. static <E> List<E> of()


2. static <E> List<E> of(E e1)
3. static <E> List<E> of(E e1, E e2)
4. static <E> List<E> of(E e1, E e2, E e3)
617

5. static <E> List<E> of(E e1, E e2, E e3, E e4)


6. static <E> List<E> of(E e1, E e2, E e3, E e4, E e5)
7. static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6)
Page

8. static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


9. static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
10.static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
11.static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
12. static <E> List<E> of(E... elements)

Upto 10 elements the matched method will be executed and for more than 10 elements internally var-arg method
will be called.JDK Enginerrs identified List of upto 10 elements is the common requirement and hence they
provided the corresponding methods. For remaining cases var-arg method will be executed, which is very costly.
These many methods just to improve performance.

Eg: To create unmodifiable List with Java 9 Factory Methods.

List<String> beers = List.of("KF","KO","RC","FO");


It is very simple and straight forward way.

Note:
1. While using these factory methods if any element is null then we will get NullPointerException.

List<String> fruits = List.of("Apple","Banana",null);  NullPointerException

2. After creating the List object,if we are trying to change the content(add|remove|replace elements)then we will
get UnsupportedOperationException because List is immutable(unmodifiable).

List<String> fruits=List.of("Apple","Banana","Mango");
fruits.add("Orange"); //UnsupportedOperationException
fruits.remove(1); //UnsupportedOperationException
fruits.set(1,"Orange"); //UnsupportedOperationException
Creation of unmodifiable Set(Immutable Set) with Java 9 Factory Methods:

Java 9 Set interface defines several factory methods for this.

1. static <E> Set<E> of()


2. static <E> Set<E> of(E e1)
3. static <E> Set<E> of(E e1, E e2)
4. static <E> Set<E> of(E e1, E e2, E e3)
5. static <E> Set<E> of(E e1, E e2, E e3, E e4)
6. static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5)
7. static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6)
8. static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)
618

9. static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
10.static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
11.static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
Page

12. static <E> Set<E> of(E... elements)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Eg: To create unmodifiable Set with Java 9 Factory Methods.

Set<String> beers = Set.of("KF","KO","RC","FO");

Note:

1. While using these Factory Methods if we are trying to add duplicate elements then we will get
IllegalArgumentException, because Set won't allow duplicate elements

Set<Integer> numbers=Set.of(10,20,30,10);
RE: IllegalArgumentException: duplicate element: 10

2. While using these factory methods if any element is null then we will get NullPointerException.

Set<String> fruits=Set.of("Apple","Banana",null); NullPointerException

3. After creating the Set object, if we are trying to change the content (add|remove elements)then we will get
UnsupportedOperationException because Set is immutable(unmodifiable).

Set<String> fruits=Set.of("Apple","Banana","Mango");
fruits.add("Orange"); //UnsupportedOperationException
fruits.remove("Apple"); //UnsupportedOperationException

Creation of unmodifiable Map (Immutable Map) with Java 9 Factory Methods:


Java 9 Map interface defines of() and ofEntries() Factory methods for this purpose.

1. static <K,V> Map<K,V> of()


2. static <K,V> Map<K,V> of(K k1,V v1)
3. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2)
4. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3)
5. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4)
619

6. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4,K k5,V v5)
7. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4,K k5,V v5,K k6,V v6)
Page

8. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4,K k5,V v5,K k6,V v6,K k7,V v7)
9. static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4,K k5,V v5,K k6,V v6,K k7,V v7,K k8,V v8)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10.static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4,K k5,V v5,K k6,V v6,K k7,V v7,K k8,V v8,K
k9,V v9)
11.static <K,V> Map<K,V> of(K k1,V v1,K k2,V v2,K k3,V v3,K k4,V v4,K k5,V v5,K k6,V v6,K k7,V v7,K k8,V v8,K
k9,V v9,K k10,V v10)
12.static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)

Note:
Up to 10 entries,it is recommended to use of() methods and for more than 10 items we should use ofEntries()
method.

Eg: Map<String,String> map=Map.of("A","Apple","B","Banana","C","Cat","D","Dog");

How to use Map.ofEntries() method:


Map interface contains static Method entry() to create immutable Entry objects.

Map.Entry<String,String> e=Map.entry("A","Apple");
This Entry object is immutable and we cannot modify its content. If we are trying to change we will get RE:
UnsupportedOperationException

e.setValue("Durga");  UnsupportedOperationException
By using these Entry objects we can create unmodifiable Map object with Map.ofEntries() method.

Eg:

1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) Map.Entry<String,String> e1=Map.entry("A","Apple");
7) Map.Entry<String,String> e2=Map.entry("B","Banana");
8) Map.Entry<String,String> e3=Map.entry("C","Cat");
9) Map<String,String> m=Map.ofEntries(e1,e2,e3);
10) System.out.println(m);
11) }
12) }
620

In Short way we can also create as follows.

1) import static java.util.Map.entry;


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2) Map<String,String> map=Map.ofEntries(entry("A","Apple"),entry("B","Banana"),entry("C
","Cat"),entry("D","Dog"));

Note:

1. While using these Factory Methods if we are trying to add duplicate keys then we will get
IllegalArgumentException: duplicate key.But values can be duplicated.

Map<String,String> map=Map.of("A","Apple","A","Banana","C","Cat","D","Dog");
RE: java.lang.IllegalArgumentException: duplicate key: A

2. While using these factory methods if any element is null (either key or value) then we will get
NullPointerException.

Map<String,String> map=Map.of("A",null,"B","Banana"); ==>NullPointerException


Map<String,String> map=Map.ofEntries(entry(null,"Apple"),entry("B","Banana"));
 NullPointerException

3. After creating the Map object, if we are trying to change the content(add|remove|replace elements)then we
will get UnsupportedOperationException because Map is immutable(unmodifiable).

Eg:

Map<String,String> map=Map.ofEntries(entry("A","Apple"),entry("B","Banana"));
map.put("C","Cat");  UnsupportedOperationException
map.remove("A");  UnsupportedOperationException

Serialization for unmodifiable Collections:


The immutable collection objects are serializable iff all elements are serializable.
In Brief form, the process of writing state of an object to a file is called Serialization and the process of reading
state of an object from the file is called Deserialization.
621

Serialization
Page

e1 e2 e3

CONTACT US: e1 e2 e3
l1
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
e1 21e2
+91- 7207 e3
24 27/28 WEBSITE: www.durgasoftonline.com

Deserialization emp.serAMEERPET, HYDERABAD.


FLAT NO: 202, HMDA MYTRIVANUM,
l2
1) import java.util.*;
2) import java.io.*;
3) class Employee implements Serializable
4) {
5) private int eno;
6) private String ename;
7) Employee(int eno,String ename)
8) {
9) this.eno=eno;
10) this.ename=ename;
11) }
12) public String toString()
13) {
14) return String.format("%d=%s",eno,ename);
15) }
16) }
17) class Test
18) {
19) public static void main(String[] args) throws Exception
20) {
21) Employee e1= new Employee(100,"Sunny");
22) Employee e2= new Employee(200,"Bunny");
23) Employee e3= new Employee(300,"Chinny");
24) List<Employee> l1=List.of(e1,e2,e3);
25) System.out.println(l1);
26)
27) System.out.println("Serialization of List Object...");
28) FileOutputStream fos=new FileOutputStream("emp.ser");
29) ObjectOutputStream oos=new ObjectOutputStream(fos);
30) oos.writeObject(l1);
622

31)
32) System.out.println("Deserialization of List Object...");
33) FileInputStream fis=new FileInputStream("emp.ser");
Page

34) ObjectInputStream ois=new ObjectInputStream(fis);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


35) List<Employee> l2=(List<Employee>)ois.readObject();
36) System.out.println(l2);
37) //l2.add(new Employee(400,"Vinnny"));//UnsupportedOperationException
38) }
39) }

Output:
D:\durga_classes>java Test
[100=Sunny, 200=Bunny, 300=Chinny]
Serialization of List Object...
Deserialization of List Object...
[100=Sunny, 200=Bunny, 300=Chinny]

After deserialization also we cannot modify the content, otherwise we will get UnsupportedOperationException.

Note: The Factroy Methods introduced in Java 9 are not to create general collections and these are meant for
creating immutable collections.

623

Stream API Enhancements


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Streams concept has been introduced in Java 1.8 version.

The main objective of Streams concept is to process elements of Collection with Functional Programming (Lambda
Expressions).

What is the difference between java.util streams and java.io streams?


java.util streams meant for processing objects from the collection. ie. it represents a stream of objects from the
collection but java.io streams meant for processing binary and character data with respect to file. i.e it represents
stream of binary data or character data from the file. Hence java.io streams and java.util streams are different
concepts.

What is the difference between Collections and Streams?


If we want to represent a group of individual objects as a single entity, then we should go for collection. If we
want to process a group of objects from the collection then we should go for Streams.

How to Create Stream Object?


We can create stream object to the collection by using stream() method of Collection interface. stream() method
is a default method added to the Collection in 1.8 version.

default Stream stream()

Ex: Stream s = c.stream(); // c is any Collection object

Note: Stream is an interface present in java.util.stream package.

How to process Objects of Collection By using Stream:


Once we got the stream, by using that we can process objects of that collection.
For this we can use either filter() method or map() method.

Processing Objects by using filter() method:


We can use filter() method to filter elements from the collection based on some boolean condition.

public Stream filter(Predicate<T> t)


624

Here (Predicate<T > t ) can be a boolean valued function/lambda expression


Demo Program:
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) import java.util.*;
2) import java.util.stream.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) ArrayList<Integer> l1 = new ArrayList<Integer>();
8) for(int i =0; i <=10; i++)
9) {
10) l1.add(i);
11) }
12) System.out.println("Before Filtering:"+l1);
13) List<Integer> l2=l1.stream().filter(i->i%2==0).collect(Collectors.toList());
14) System.out.println("After Filtering:"+l2);
15) }
16) }

Output:
Before Filtering:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After Filtering:[0, 2, 4, 6, 8, 10]

Processing Objects by using map() method:


If we want to create a separate new object, for every object present in the collection based on our requirement
then we should go for map() method of Stream interface.

public Stream map (Function f);


The argument can be lambda expression also

Demo Program:

1) import java.util.*;
2) import java.util.stream.*;
3) public class Test
4) {
5) public static void main(String[] args) {
6) ArrayList<Integer> l1 = new ArrayList<Integer>();
7) for(int i =0; i <=10; i++)
8) {
9) l1.add(i);
625

10) }
11) System.out.println("Before using map() method:"+l1);
12) List<Integer> l2=l1.stream().map(i->i*i).collect(Collectors.toList());
Page

13) System.out.println("After using map() method:"+l2);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


14) }
15) }

Output:
Before using map() method:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After using map() method:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Processing Objects by using flatMap() method:


Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. The difference is that
the map operation produces one output value for each input value, whereas the flatMap operation produces an
arbitrary number (zero or more) values for each input value.

Typical use is for the mapper function of flatMap to return Stream.empty() if it wants to send zero values, or
something like Stream.of(x, y, z) if it wants to return several values.

Demo Program:

1) import java.util.*;
2) import java.util.stream.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) ArrayList<Integer> l1 = new ArrayList<Integer>();
8) for(int i =0; i <=10; i++)
9) {
10) l1.add(i);
11) }
12) System.out.println("Before using map() method:"+l1);
13) List<Integer> l2=l1.stream().flatMap(
14) i->{ if (i%2 !=0) return Stream.empty();
15) else return Stream.of(i);
16) }).collect(Collectors.toList());
17) System.out.println("After using flatMap() method:"+l2);
18)
19) List<Integer> l3=l1.stream().flatMap(
20) i->{ if (i%2 !=0) return Stream.empty();
21) else return Stream.of(i,i*i);
22) }).collect(Collectors.toList());
626

23) System.out.println("After using flatMap() method:"+l3);


24) }
25) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Output:
D:\durga_classes>java Test
Before using map() method:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After using flatMap() method:[0, 2, 4, 6, 8, 10]
After using flatMap() method:[0, 0, 2, 4, 4, 16, 6, 36, 8, 64, 10, 100]

Q. What is the difference between map() and flatMap() methods?


Java 9 Enhancements for Stream API:
In Java 9 as the part of Stream API, the following new methods introduced.

1. takeWhile()
2. dropWhile()

3. Stream.iterate()
4. Stream.ofNullable()

Note: takeWhile() and dropWhile() methods are default methods and iterate() and ofNullable() are static
methods of Stream interface.

1. takeWhile():
It is the default method present in Stream interface.

default Stream takeWhile(Predicate p)

It returns the stream of elements that matches the given predicate.


It is similar to filter() method.

Difference between takeWhile() and filter():


filter() method will process every element present in the stream and consider the element if predicate is true.

But, in the case of takeWhile() method, there is no guarantee that it will process every element of the Stream. It
will take elements from the Stream as long as predicate returns true. If predicate returns false, at that point
onwards remaining elements won't be processed, i.e rest of the Stream is discarded.
627

Eg: Take elements until we will get even numbers. Once we got odd number then stop and ignore rest of the
stream.
Page

Demo Program:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) import java.util.*;
2) import java.util.stream.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) ArrayList<Integer> l1 = new ArrayList<Integer>();
8) l1.add(2);
9) l1.add(4);
10) l1.add(1);
11) l1.add(3);
12) l1.add(6);
13) l1.add(5);
14) l1.add(8);
15) System.out.println("Initial List:"+l1);
16) List<Integer> l2=l1.stream().filter(i->i%2==0).collect(Collectors.toList());
17) System.out.println("After Filtering:"+l2);
18) List<Integer> l3=l1.stream().takeWhile(i->i%2==0).collect(Collectors.toList());
19) System.out.println("After takeWhile:"+l3);
20) }
21) }

Output:
Initial List:[2, 4, 1, 3, 6, 5, 8]
After Filtering:[2, 4, 6, 8]
After takeWhile:[2, 4]

Eg 2:
Stream.of("A","AA","BBB","CCC","CC","C").takeWhile(s->s.length()<=2).forEach(System.out::println);

Output:
A
AA

2. dropWhile()
It is the default method present in Stream interface.

default Stream dropWhile(Predicate p)


628

It is the opposite of takeWhile() method.


Page

It drops elements instead of taking them as long as predicate returns true. Once predicate returns false then rest
of the Stream will be returned.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Demo Program:

1) import java.util.*;
2) import java.util.stream.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) ArrayList<Integer> l1 = new ArrayList<Integer>();
8) l1.add(2);
9) l1.add(4);
10) l1.add(1);
11) l1.add(3);
12) l1.add(6);
13) l1.add(5);
14) l1.add(8);
15) System.out.println("Initial List:"+l1);
16) List<Integer> l2=l1.stream().dropWhile(i->i%2==0).collect(Collectors.toList());
17) System.out.println("After dropWhile:"+l2);
18) }
19) }

Output:
Initial List:[2, 4, 1, 3, 6, 5, 8]
After dropWhile:[1, 3, 6, 5, 8]

Eg 2:
Stream.of("A","AA","BBB","CCC","CC","C").dropWhile(s->s.length()<=2).forEach(System.out::println);

Output:
BBB
CCC
CC
C

3. Stream.iterate():
It is the satic method present in Stream interface.
629

Form-1: iterate() method with 2 Arguments


Page

This method introduced in Java 8.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public static Stream iterate (T initial,UnaryOperator<T> f)

It takes an initial value and a function that provides next value.

Eg: Stream.iterate(1,x->x+1).forEach(System.out::println);

Output:
1
2
3
...infinite times
How to limit the number of iterations:
For this we can use limit() method.

Eg: Stream.iterate(1,x->x+1).limit(5).forEach(System.out::println);

Output:
1
2
3
4
5

Form-2: iterate() method with 3 arguments


The problem with 2 argument iterate() method is there may be a chance of infinite loop. To avoid, we should use
limit method.

To prevent infinite loops, in Java 9, another version of iterate() method introduced, which is nothing but 3-arg
iterate() method.

This method is something like for loop

for(int i =0;i<10;i++){}

public static Stream iterate(T initial,Predicate conditionCheck,UnaryOperator<T> f)


630

This method takes an initial value,


A terminate Predicate
Page

A function that provides next value.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Eg: Stream.iterate(1,x->x<5,x->x+1).forEach(System.out::println);

Output:
1
2
3
4

4. ofNullable():
public static Stream<T> ofNullable(T t)

This method will check whether the provided element is null or not. If it is not null, then this method returns the
Stream of that element. If it is null then this method returns empty stream.

This method is helpful to deal with null values in the stream


The main advantage of this method is to we can avoid NullPointerException and null checks everywhere.

Usually we can use this method in flatMap() to handle null values.

Eg 1:
List l=Stream.ofNullable(100).collect(Collectors.toList());
System.out.println(l);

Output:[100]

Eg 2:
List l=Stream.ofNullable(null).collect(Collectors.toList());
System.out.println(l);

Output: []

Demo Program:
631

1) import java.util.*;
2) import java.util.stream.*;
Page

3) import java.util.*;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4) import java.util.stream.*;
5) public class Test
6) {
7) public static void main(String[] args)
8) {
9) List<String> l=new ArrayList<String>();
10) l.add("A");
11) l.add("B");
12) l.add(null);
13) l.add("C");
14) l.add("D");
15) l.add(null);
16) System.out.println(l);
17)
18) List<String> l2= l.stream().filter(o->o!=null).collect(Collectors.toList());
19) System.out.println(l2);
20)
21) List<String> l3= l.stream()
22) .flatMap(o->Stream.ofNullable(o)).collect(Collectors.toList());
23) System.out.println(l3);
24) }
25) }

Output:
[A, B, null, C, D, null]
[A, B, C, D]
[A, B, C, D]

Demo Program:

1) import java.util.*;
2) import java.util.stream.*;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) Map<String,String> m=new HashMap<>();
8) m.put("A","Apple");
9) m.put("B","Banana");
632

10) m.put("C",null);
11) m.put("D","Dog");
12) m.put("E",null);
Page

13) List<String> l=m.entrySet().stream().map(e->e.getKey()).collect(Collectors.toList());


14) System.out.println(l);

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


15)
16) List<String> l2=m.entrySet().stream()
17) .flatMap(e->Stream.ofNullable(e.getValue())).collect(Collectors.toList());
18) System.out.println(l2);
19)
20) }
21) }

Output:
[A, B, C, D, E]
[Apple, Banana, Dog]

The Java Shell (RPEL)


JShell Agenda
1) Introduction to the JShell …………………………………………………………………………………….…. 81

2) Getting Started with JShell ……………………………………………………………………………………... 82

3) Getting Help from the JShell …………………………………………………………………………………... 86

4) Understanding JShell Snippets ………………………………………………………………………………… 95


633

5) Editing and Navigating Code Snippets …………………………………………………………………... 100

6) Working with JShell Variables …………………………………………………………………………….… 102


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


7) Working with JShell Methods …………………………………………………………….…………………. 107

8) Using An External Editor with JShell ………………………..…………………………………….……… 113

9) Using classes,interfaces and enum with JShell ………………………………………………….…… 115

10) Loading and Saving Snippets in JShell ……………………………………………..…………….……… 117

11) Using Jar Files in the JShell ………………………………………………………………………….………… 121

12) How to customize JShell Startup ………………………………………………………………..…………. 123

13) Shortcuts and Auto-Completion of Commands ……………………………………………………… 127

UNIT 1: Introduction to the JShell


Jshell is also known as interactive console.
JShell is Java's own REPL Tool.

REPL means Read, Evaluate, Print and Loop

By using this tool we can execute Java code snippets and we can get immediate results.
For beginners it is very good to start programming in fun way.

By using this Jshell we can test and execute Java expressions, statements, methods, classes etc. It is useful for
testing small code snippets very quickly, which can be plugged into our main coding based on our requirement.

Prior to Java 9 we cannot execute a single statement, expression, methods without full pledged classes. But in
Java 9 with JShell we can execute any small piece of code without having complete class structure.
634

It is not new thing in Java. It is already there in other languages like Python, Swift, Lisp, Scala, Ruby etc..

Python IDLE
Page

Apple's Swift Programming Language  PlayGround

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Limitations of JShell:
1. JShell is not meant for Main Coding. We can use just to test small coding snippets, which can be used in our
Main Coding.

2. JShell is not replacement of Regular Java IDEs like Eclpise, NetBeans etc

3. It is not that much impressed feature. All other languages like Python, LISP, Scala, Ruby, Swift etc are already
having this REPL tools

UNIT-2: Getting Started with JShell


Starting and Stopping JShell:
Open the jshell from the command prompt in verbose mode
jshell -v

635
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


D:\durga_classes>jshell -v
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

How to exit jshell:


jshell> /exit
| Goodbye

Note: Observe the difference b/w with -v and without -v (verbose mode)

D:\durga_classes>jshell -v
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

Note: If any information displaying on the jshell starts with '|', it is the information to the programmer from the
jshell

jshell> 10+20
$1 ==> 30
| created scratch variable $1 : int

jshell> 20-30*6/2
$2 ==> -70
| created scratch variable $2 : int
jshell> System.out.println("DURGASOFT")
636

DURGASOFT

Here if we observe the output not starts with | because it is not information from the Jshell.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: Terminating semicolons are automatically added to the end of complete snippet by JShell if not entered. .

jshell> Math.sqrt(4)
$4 ==> 2.0
| created scratch variable $4 : double

jshell> Math.max(10,20)
$5 ==> 20
| created scratch variable $5 : int

jshell> Math.random()
$6 ==> 0.6956946870985563
| created scratch variable $6 : double

jshell> Math.random()
$7 ==> 0.3657412865477785
| created scratch variable $7 : double

jshell> Math.random()
$8 ==> 0.8828801968574324
| created scratch variable $8 : double

Note: We are not required to import Java.lang package, because by default available.

Can you check whether the following will work or not?


jshell> ArrayList<String> l = new ArrayList<String>();
l ==> []
| created variable l : ArrayList<String>

Note: The following packages are bydefault available to the Jshell and we are not required to import. We can
check with /imports command

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.*
637

| import Java.util.prefs.*
| import Java.util.regex.*
| import Java.util.stream.*
Page

jshell> ArrayList<String> l=new ArrayList<String>();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


l ==> []

jshell> l.add("Sunny");l.add("Bunny");l.add("Chinny");
$2 ==> true
$3 ==> true
$4 ==> true

jshell> l
l ==> [Sunny, Bunny, Chinny]

jshell> l.isEmpty()
$6 ==> false

jshell> l.get(2)
$7 ==> "Chinny"

jshell> l.get(10)
| Java.lang.IndexOutOfBoundsException thrown: Index 10 out-of-bounds for length 3

jshell> l.size()
$9 ==> 3

jshell> if(l.isEmpty()) System.out.println("Empty");else System.out.println("Not Empty");


Not Empty

jshell> for(int i =0;i<10;i=i+2)System.out.println(i)


0
2
4
6
8

Note: Interlly jshell having Java compiler which is responsible to check syntax.If any violation we will get Compile
time error which is exactly same as normal compile time errors.

jshell> System.out.println(x+y)
| Error:
| cannot find symbol
| symbol: variable x
| System.out.println(x+y)
| ^
638

| Error:
| cannot find symbol
Page

| symbol: variable y
| System.out.println(x+y)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> Sytsem.out.println("Durga")
| Error:
| package Sytsem does not exist
| Sytsem.out.println("Durga")
| ^--------^

Note: In our program if there is any chance of getting checked exceptions compulsory we required to handle
either by try-catch or by throws keyword. Otherwise we will get Compile time error.

Eg:

1) import Java.io.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) PrintWriter pw=new PrintWriter("abc.txt");
7) pw.println("Hello");
8) }
9) }

D:\durga_classes>Javac Test.Java
Test.Java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
PrintWriter pw=new PrintWriter("abc.txt");
But in the case of Jshell, jshell itself will takes care of these and we are not required to use try-catch or throws.
Thanks to Jshell.

jshell> PrintWriter pw=new PrintWriter("abc.txt");pw.println("Hello");pw.flush();


pw ==> Java.io.PrintWriter@e25b2fe

Conclusions:
1. From the jshell we can execute any expression, any Java statement.
2. Most of the packages are not required to import to the Jshell because by default already available to the jshell.
3. Internally jshell use Java compiler to check syntaxes
4. If we are not handling any checked exceptions we won’t get any compile time errors, because jshell will takes
care.
639
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


UNIT - 3: Getting Help from the JShell
If You Cry For Help....JShell will provide everything.

JShell can provide complete information about available commands with full documentation, and how to use
each command and what are various options are available etc..

Agenda:
1) To know list of options allowed with jshell:

Type jshell --help from normal command prompt

2) To know the version of jshell:

Type jshell --version from normal command prompt

3) To know introduction of jshell:

jshell> /help intro

4) For List of commands:

type /help from jshell

5) To get information about a particular command:

jshell>/help commandname

6) To get just names of all commands without any description:

just type / followed by tab

7) To know the list of options available for a command

jshell>/command - tab
640

jshell> /list -
-all -history -start
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) To know list of options allowed with jshell
Type jshell --help from normal command prompt

D:\durga_classes>jshell --help
Usage: jshell <options> <load files>
where possible options include:
--class-path <path> Specify where to find user class files
--module-path <path> Specify where to find application modules
--add-modules <module>(,<module>)*
Specify modules to resolve, or all modules on the
module path if <module> is ALL-MODULE-PATHs
--startup <file> One run replacement for the start-up definitions
--no-startup Do not run the start-up definitions
--feedback <mode> Specify the initial feedback mode. The mode may be
predefined (silent, concise, normal, or verbose) or
previously user-defined
-q Quiet feedback. Same as: --feedback concise
-s Really quiet feedback. Same as: --feedback silent
-v Verbose feedback. Same as: --feedback verbose
-J<flag> Pass <flag> directly to the runtime system.
Use one -J for each runtime flag or flag argument
-R<flag> Pass <flag> to the remote runtime system.
Use one -R for each remote flag or flag argument
-C<flag> Pass <flag> to the compiler.
Use one -C for each compiler flag or flag argument
--version Print version information and exit
--show-version Print version information and continue
--help Print this synopsis of standard options and exit
--help-extra, -X Print help on non-standard options and exit

2) To know the version of jshell


Type jshell --version from normal command prompt
641

D:\durga_classes>jshell --version
jshell 9
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


3) To know introduction of jshell
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 jshell commands that allow you to understand and
| control what you are doing, like: /list
|
| For a list of commands: /help

4) For List of commands


type /help from jshell

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
642

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


| Save snippet source to a file.
| /open <file>
Page

| open a file as source input

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| /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
| /exit
| exit jshell
| /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 jshell
| /reload [-restore] [-quiet] [-class-path <path>] [-module-path <path>]...
| reset and replay relevant history -- current or previous (-restore)
| /history
| history of what you have typed
| /help [<command>|<subject>]
| get information about jshell
| /set editor|start|feedback|mode|prompt|truncation|format ...
| set jshell configuration information
| /? [<command>|<subject>]
| get information about jshell
| /!
| re-run last snippet
| /<id>
| re-run snippet by id
| /-<n>
| re-run n-th previous snippet
|
| 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
| shortcuts
| a description of keystrokes for snippet and command completion,
643

| information access, and automatic code generation


| context
| the evaluation context options for /env /reload and /reset
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5) To get information about a particular command
jshell>/help commandname

jshell> /help list


|
| /list
|
| Show the source of snippets, prefaced with the snippet id.
|
| /list
| List the currently active snippets of code that you typed or read with /open
|
| /list -start
| List the automatically evaluated start-up snippets
|
| /list -all
| List all snippets including failed, overwritten, dropped, and start-up
|
| /list <name>
| List snippets with the specified name (preference for active snippets)
|
| /list <id>
| List the snippet with the specified snippet id

To get Information about methods command


jshell> /help methods
|
| /methods
|
| List the name, parameter types, and return type of jshell methods.
|
| /methods
| List the name, parameter types, and return type of the current active jshell methods
|
| /methods <name>
| List jshell methods with the specified name (preference for active methods)
|
| /methods <id>
644

| List the jshell method with the specified snippet id


|
Page

| /methods -start
| List the automatically added start-up jshell methods

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


|
| /methods -all
| List all snippets including failed, overwritten, dropped, and start-up

6) To get just names of all commands without any description


just type / followed by tab

jshell> /
/! /? /drop /edit /env /exit /help
/history /imports /list /methods /open /reload /reset
/save /set /types /vars

<press tab again to see synopsis>

If we press tab again then we will get one line synopsis for every command:
jshell> /
/!
re-run last snippet

/-<n>
re-run n-th previous snippet

/<id>
re-run snippet by id

/?
get information about jshell

/drop
delete a source entry referenced by name or id

/edit
edit a source entry referenced by name or id

/env
view or change the evaluation context

/exit
645

exit jshell

/help
Page

get information about jshell

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


/history
history of what you have typed

/imports
list the imported items

/list
list the source you have typed

/methods
list the declared methods and their signatures

/open
open a file as source input

/reload
reset and replay relevant history -- current or previous (-restore)

/reset
reset jshell

/save
Save snippet source to a file.

/set
set jshell configuration information

/types
list the declared types

/vars
list the declared variables and their values

<press tab again to see full documentation>

If we press tab again then we can see full documentation of command one by one:

jshell> /
/!
646

Reevaluate the most recently entered snippet.

<press tab to see next command>


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> /
/-<n>
Reevaluate the n-th most recently entered snippet.

<press tab to see next command>

jshell> /
/<id>
Reevaluate the snippet specified by the id.

<press tab to see next command>

7) To know the list of options available for a command


jshell>/command - tab

jshell> /list -
-all -history -start

<press tab again to see synopsis>

jshell> /list -
If we press tab again then we will get synopsis:
jshell> /list -
list the source you have typed

<press tab again to see full documentation>


jshell> /list -

If we press tab again then we will get documentation:


jshell> /list -
Show the source of snippets, prefaced with the snippet id.

/list
List the currently active snippets of code that you typed or read with /open

/list -start
647

List the automatically evaluated start-up snippets

/list -all
Page

List all snippets including failed, overwritten, dropped, and start-up

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


/list <name>
List snippets with the specified name (preference for active snippets)

/list <id>
List the snippet with the specified snippet id

Conclusions:
1) To know list of options allowed with jshell
Type jshell --help from normal command prompt

2) To know the version of jshell


Type jshell --version from normal command prompt

3) To know introduction of jshell


648

jshell> /help intro


Page

4) For List of commands

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


type /help from jshell

5) To get information about a particular command


jshell>/help commandname

6) To get just names of all commands without any description

just type / followed by tab

7) To know the list of options available for a command

jshell>/command - tab

jshell> /list -
-all -history -start

UNIT - 4: Understanding JShell Snippets


What are Coding Snippets?
Everything what allowed in Java is a snippet. It can be
Expression,Declaration,Statement,classe,interface,method,variable,import,...
We can use all these as snippets from jshell.

***But package declarations are not allowed from the jshell.


649

jshell> System.out.println("Hello")
Page

Hello

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> int x=10
x ==> 10
| created variable x : int

jshell> 10+20
$3 ==> 30
| created scratch variable $3 : int

jshell> $3>x
$4 ==> true
| created scratch variable $4 : boolean

jshell> String s =10


| Error:
| incompatible types: int cannot be converted to Java.lang.String
| String s =10;
| ^^

jshell> String s= "Durga"


s ==> "Durga"
| created variable s : String

jshell> public void m1()


...> {
...> System.out.println("hello");
...> }
| created method m1()

jshell> m1()
hello

Note: We can use /list command to list out all snippets stored in the jshell memory with snippet id.

jshell> /list

1 : System.out.println("Hello")
2 : int x=10;
3 : 10+20
4 : $3>x
650

5 : String s= "Durga";
6 : public void m1()
Page

{
System.out.println("hello");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


}
7 : m1()

The numbers 1,2,3 are snippet id. In the future we can access the snippet with id directly.

Note: There are some snippets which will be executed automatically at the time jshell star-tup,and these are
called start-up snippets. We can also add our own snippets as start-up snippets.

We can list out all start-up snippets with command: /list -start

jshell> /list -start

s1 : import Java.io.*;
s2 : import Java.math.*;
s3 : import Java.net.*;
s4 : import Java.nio.file.*;
s5 : import Java.util.*;
s6 : import Java.util.concurrent.*;
s7 : import Java.util.function.*;
s8 : import Java.util.prefs.*;
s9 : import Java.util.regex.*;
s10 : import Java.util.stream.*;

All these are default imports to the jshell.

We can list out all snippets by the command: /list -all

jshell> /list -all

s1 : import Java.io.*;
s2 : import Java.math.*;
s3 : import Java.net.*;
s4 : import Java.nio.file.*;
s5 : import Java.util.*;
s6 : import Java.util.concurrent.*;
s7 : import Java.util.function.*;
s8 : import Java.util.prefs.*;
s9 : import Java.util.regex.*;
s10 : import Java.util.stream.*;
1 : System.out.println("Hello")
2 : int x=10;
651

3 : 10+20
4 : $3>x
Page

e1 : String s =10;
5 : String s= "Durga";

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6 : public void m1()
{
System.out.println("hello");
}
7 : m1()

We can access snippets by using id directly.

jshell> /list 1

1 : System.out.println("Hello")

jshell> /list 1 2

1 : System.out.println("Hello")
2 : int x=10;

jshell> /list 1 5

1 : System.out.println("Hello")
5 : String s= "Durga";

We can also access snippets directly by using name.The name can be either variable name,class name ,method
name etc

jshell> /list m1

6 : public void m1()


{
System.out.println("hello");
}

jshell> /list x

2 : int x=10;

jshell> /list s

5 : String s= "Durga";

We can execute snippet directly by using id with the command: /id


652

jshell> /3
10+20
Page

$8 ==> 30

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| created scratch variable $8 : int

jshell> /7
m1()
hello

We can use drop command to drop a snippet(Making it inactive)


We can drop snippet by name or id.

jshell> /list

1 : System.out.println("Hello")
2 : int x=10;
3 : 10+20
4 : $3>x
5 : String s= "Durga";
6 : public void m1()
{
System.out.println("hello");
}
7 : m1()
8 : 10+20
9 : m1()

jshell> /drop $3
| dropped variable $3

jshell> /list

1 : System.out.println("Hello")
2 : int x=10;
4 : $3>x
5 : String s= "Durga";
6 : public void m1()
{
System.out.println("hello");
}
7 : m1()
8 : 10+20
9 : m1()
653

jshell> /4
$3>x
| Error:
Page

| cannot find symbol

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| symbol: variable $3
| $3>x
| ^^

Conclusions:
1. We can use /list command to list out all snippets stored in the jshell memory with snippet id.
jshell>/list

2. In the future we can access the snippet with id directly without retypinng whole snippet.
jshell>/list id

3. There are some snippets which will be executed automatically at the time jshell star-tup,and these are called
start-up snippets. We can list out all start-up snippets with command: /list -start

jshell> /list -start


We can also add our own snippets as start-up snippets.

4. The default start-up snippets are default imports to the jshell.

5. We can list out all snippets by the command: /list -all


jshell> /list -all

6. We can access snippets by using id directly.

jshell> /list 1

7. We can access snippets directly by using name.The name can be either variable name,class name ,method
name etc

jshell> /list m1

8. We can execute snippet directly by using id with the command: /id

jshell> /3

9. We can use drop command to drop a snippet(Making it inactive)


We can drop snippet by name or id.
jshell> /drop $3
654

Once we dropped a snippet,we cannot use otherwise we will get compile time error.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


UNIT – 5: Editing and Navigating Code Snippets
We can list all our active snippets with /list command and we can list total history of our jshell activities with
/history command.

jshell> /list

1 : int x=10;
2 : String s="Durga";
3 : System.out.println("Hello");
4 : class Test{}

jshell> /history

int x=10;
String s="Durga";
System.out.println("Hello");
class Test{}
/list
/history

1. By using down arrow and up arrow we can navigate through history.While navigating we can use left and right
arrows to move character by character with in the snippet.

2. We can Ctrl+A to move to the beginning of the line and Ctrl+E to move to the end of the line.

3. We can use Alt+B to move backward by one word and Alt+F to move forward by one word.

4. We can use Delete key to delete the character at the cursor. We can us Backspace to delete character before
the cursor.

5. We can use Ctrl+K to delete the text from the cursor to the end of line.

6. We can use Alt+D to delete the text from the cursor to the end of the word.

7. Ctrl+W to delete the text from cursor to the previous white space.

8. Ctrl+Y to paste most recently deleted text into the line.

9. Ctrl+R to Search backward through history


655

10. Ctrl+S to search forward through histroy


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


KEY ACTION
Up arrow Moves up one line, backward through history
Down arrow Moves down one line, forward through history
Left arrow Moves backward one character
Right arrow Moves forward one character
Ctrl+A Moves to the beginning of the line
Ctrl+E Moves to the end of the line
Alt+B Moves backward one word
Alt+F Moves forward one word
Delete Deletes the character at the cursor
Backspace Deletes the character before the cursor
Ctrl+K Deletes the text from the cursor to the end of the line
Alt+D Deletes the text from the cursor to the end of the word
Ctrl+W Deletes the text from the cursor to the previous white space.
Ctrl+Y Pastes the most recently deleted text into the line.
Ctrl+R Searches backward through history
Ctrl+S Searches forwards through history

656
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


UNIT – 6: Working with JShell Variables
After completing this JShell Variables session, we can answer the following:

1. What are various types of variables possible in jshell?


2. Is it possible to use scratch variable in our code?
3. Is it possible 2 variables with the same name in JShell?
4. If we are trying to declare a variable with the same name which is already available in JShell then what will
happen?
5. How to list out all active variables of jshell?
6. How to list out all active& in-active variables of jshell?
7. How to drop variables in the JShell?
8. What is the difference between print() and printf() methods?

In JShell,there are 2 types of variables

1. Explicit variables
2. Implicit variables or Scratch variables

Explicit variables:
These variables created by programmer explicitly based on our programming requirement.

Eg:

jshell> int x =10


x ==> 10
| created variable x : int

jshell> String s="Durga"


s ==> "Durga"
| created variable s : String
657

The variables x and s provided explicitly by the programmer and hence these are explicit variables.
Page

Implicit Variables:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Sometimes JShell itself creates variables implicitly to hold temporary values,such type of variables are called
Implicit variables.

Eg:

jshell> 10+20
$3 ==> 30
| created scratch variable $3 : int
jshell> 10<20
$4 ==> true
| created scratch variable $4 : boolean

The variables $3 and $4 are created by JShell and hence these are implicit variables.

Based on requirement we can use these scratch variables also.

jshell> $3+40
$5 ==> 70
| created scratch variable $5 : int

If we are trying to declare a variable with the same name which is already available then old variable will be
replaced with new variable.i.e in JShell, variable overriding is possible.
In JShell at a time only one variable is possible with the same name.i.e 2 variables with the same name is not
allowed.

jshell> String x="DURGASOFT"


x ==> "DURGASOFT"
| replaced variable x : String
| update overwrote variable x : int

In the above case,int variable x is replaced with String variable x.

While declaring variables compulsory the types must be matched,otherwise we will get compile time error.

jshell> String s1=true


| Error:
| incompatible types: boolean cannot be converted to Java.lang.String
| String s1=true;
| ^--^
658

jshell> String s1="Hello"


s1 ==> "Hello"
Page

| created variable s1 : String

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: By using /vars command we can list out type,name and value of all variables which are created in JShell.
Instead of /vars we can also use /var,/va,/v

jshell> /help vars


|
| /vars
|
| List the type, name, and value of jshell variables.
|
| /vars
| List the type, name, and value of the current active jshell variables
|
| /vars <name>
| List jshell variables with the specified name (preference for active var
iables)
|
| /vars <id>
| List the jshell variable with the specified snippet id
|
| /vars -start
| List the automatically added start-up jshell variables
|
| /vars -all
| List all jshell variables including failed, overwritten, dropped, and st
art-up

To List out All Active variables of JShell:


jshell> /vars
| String s = "Durga"
| int $3 = 30
| boolean $4 = true
| String x = "DURGASOFT"
| String s1 = "Hello"

To List out All Variables(both active and not-active):


jshell> /vars -all
| int x = (not-active)
| String s = "Durga"
659

| int $3 = 30
| boolean $4 = true
| String x = "DURGASOFT"
Page

| String s1 = (not-active)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| String s1 = "Hello"

We can drop a variable by using /drop command

jshell> /vars
| String s = "Durga"
| int $3 = 30
| boolean $4 = true
| String x = "DURGASOFT"
| String s1 = "Hello"

jshell> /drop $3
| dropped variable $3
jshell> /vars
| String s = "Durga"
| boolean $4 = true
| String x = "DURGASOFT"
| String s1 = "Hello"

We can create complex variables also

jshell>List<String> heroes=List.of("Ameer","Sharukh","Salman");
heroes ==> [Ameer, Sharukh, Salman]
| created variable heroes : List<String>

jshell>List<String> heroines=List.of("Katrina","Kareena","Deepika");
heroines ==> [Katrina, Kareena, Deepika]
| created variable heroines : List<String>

jshell> List<List<String>> l=List.of(heroes,heroines);


l ==> [[Ameer, Sharukh, Salman], [Katrina, Kareena, Deepika]]
| created variable l : List<List<String>>

jshell> /vars
| String s = "Durga"
| boolean $4 = true
| String x = "DURGASOFT"
| String s1 = "Hello"
| List<String> heroes = [Ameer, Sharukh, Salman]
| List<String> heroines = [Katrina, Kareena, Deepika]
| List<List<String>> l = [[Ameer, Sharukh, Salman], [Katrina,Kareena, Deepika]]
660

System.out.println() vs System.out.printf() methods:


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


public class PrintStream
{
public void print(boolean);
public void print(char);
public void println(boolean);
public void println(char);
public PrintStream printf(String,Object...);
....
}
System.out.println() method return type is void.
But System.out.printf() method return type is PrintStread object.On that PrintStream object we can call printf()
method again.

jshell> System.out.println("Hello");
Hello

jshell> System.out.printf("Hello:%s\n","Durga")
Hello:Durga
$11 ==> Java.io.PrintStream@10bdf5e5
| created scratch variable $11 : PrintStream

jshell> $11.printf("Hello")
Hello$12 ==> Java.io.PrintStream@10bdf5e5
| created scratch variable $12 : PrintStream

jshell> /vars
| String s = "Durga"
| boolean $4 = true
| String x = "DURGASOFT"
| String s1 = "Hello"
| List<String> heroes = [Ameer, Sharukh, Salman]
| List<String> heroines = [Katrina, Kareena, Deepika]
| List<List<String>> l = [[Ameer, Sharukh, Salman],
[Katrina, Kareena, Deepika]]
| PrintStream $11 = Java.io.PrintStream@10bdf5e5
| PrintStream $12 = Java.io.PrintStream@10bdf5e5

FAQs:
661

1. What are various types of variables possible in jshell?


2. Is it possible to use scratch variable in our code?
Page

3. Is it possible 2 variables with the same name in JShell?

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4. If we are trying to declare a variable with the same name which is already available in JShell then what will
happen?
5. How to list out all active variables of jshell?
6. How to list out all active& in-active variables of jshell?
7. How to drop variables in the JShell?
8. What is the difference between print() and printf() methods?

UNIT – 7: Working with JShell Methods


In the JShell we can create our own methods and we can invoke these methods multiple times based on our
requirement.

Eg:

jshell> public void m1()


...> {
...> System.out.println("Hello");
...> }
| created method m1()

jshell> m1()
Hello

jshell> public void m2()


...> {
662

...> System.out.println("New Method");


...> }
| created method m2()
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> m2()
New Method

In the JShell there may be a chance of multiple methods with the same name but different argument types, and
such type of methods are called overloaded methods.Hence we can declare oveloaded methods in the JShell.

jshell> public void m1(){}


| created method m1()

jshell> public void m1(int i){}


| created method m1(int)

jshell> /methods
| void m1()
| void m1(int)

We can list out all methods information by using /methods command.

jshell> /help methods


|
| /methods
|
| List the name, parameter types, and return type of jshell methods.
|
| /methods
| List the name, parameter types, and return type of the current active jshell methods
|
| /methods <name>
| List jshell methods with the specified name (preference for active methods)
|
| /methods <id>
| List the jshell method with the specified snippet id
|
| /methods -start
| List the automatically added start-up jshell methods
|
| /methods -all
| List all snippets including failed, overwritten, dropped, and start-up

jshell> /methods
663

| void m1()
| void m2()
| void m1(int)
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If we are trying to declare a method with same signature of already existing method in JShell,then old method will
be overridden with new method(eventhough return types are different).
i.e in JShell at a time only one method with same signature is possible.

jshell> public void m1(int i){}


| created method m1(int)

jshell> public int m1(int i){return 10;}


| replaced method m1(int)
| update overwrote method m1(int)

jshell> /methods
| int m1(int)

jshell> /methods -all


| void m1(int)
| int m1(int)

In the JShell we can create more complex methods also.

Eg1: To print the number of occurrences of specified character in the given String

1) 5 : public void charCount(String s,char ch)


2) {
3) int count=0;
4) for(int i =0; i <s.length(); i++)
5) {
6) if(s.charAt(i)==ch)
7) {
8) count++;
9) }
10) }
11) System.out.println("The number of occurrences:"+count);
12) }

jshell> charCount("Hello DurgaSoft",'o')


The number of occurrences:2

jshell> charCount("Jajaja",'j')
664

The number of occurrences:2

Eg 2: To print the sum of given integers


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) 8 : public void sum(int... x)
2) {
3) int total=0;
4) for(int x1: x)
5) {
6) total=total+x1;
7) }
8) System.out.println("The Sum:"+total);
9) }

jshell> sum(10,20)
The Sum:30

jshell> sum(10,20,30,40)
The Sum:100

In JShell,inside method body we can use undeclared variables and methods.But until declaring all dependent
variables and methods,we cannot invoke that method.

Eg1: Usage of undeclared variable inside method body


jshell> public void m1()
...> {
...> System.out.println(x);
...> }
| created method m1(), however, it cannot be invoked until variable x is declared

jshell> m1()
| attempted to call method m1() which cannot be invoked until variable x is declared

jshell> int x=10


x ==> 10
| created variable x : int
| update modified method m1()

jshell> m1()
10

Eg 2: Usage of undeclared method inside method body


665

jshell> public void m1()


...> {
Page

...> m2();
...> }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| created method m1(), however, it cannot be invoked until method m2() is declared

jshell> m1()
| attempted to call method m1() which cannot be invoked until method m2() is declared

jshell> public void m2()


...> {
...> System.out.println("Hello DURGASOFT");
...> }
| created method m2()
| update modified method m1()

jshell> m1()
Hello DURGASOFT

jshell> m2()
Hello DURGASOFT

We can drop methods by name with /drop command. If multiple methods with the same name then we should
drop by snippet id.

jshell> public void m1(){}


| created method m1()

jshell> public void m1(int i){}


| created method m1(int)

jshell> public void m2(){}


| created method m2()

jshell> public void m3(){}


| created method m3()

jshell> /methods
| void m1()
| void m1(int)
| void m2()
| void m3()

jshell> /drop m3
| dropped method m3()
666

jshell> /methods
| void m1()
Page

| void m1(int)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| void m2()

jshell> /drop m1
| The argument references more than one import, variable, method, or class.
| Use one of:
| /drop 1 : public void m1(){},
| /drop 2 : public void m1(int i){}

jshell> /methods
| void m1()
| void m1(int)
| void m2()

jshell> /list

1 : public void m1(){}


2 : public void m1(int i){}
3 : public void m2(){}

jshell> /drop 2
| dropped method m1(int)

jshell> /methods
| void m1()
| void m2()

FAQs:
1. Is it possible to declare methods in the JShell?
2. Is it possible to declare multiple methods with the same name in JShell?
667

3. Is it possible to declare multiple methods with the same signature in JShell?


4. If we are trying to declare a method with the same name which is already there in the JShell,but with different
argument types then what will happen?
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5.If we are trying to declare a method with the same signature which is already there in the JShell,then what will
happen?
6. Inside a method if we are trying to use a varaiable or method which is not yet declared then what will happen?
7. How to drop methods in JShell?
8. If multiple methods with the same name then how to drop these methods?

UNIT – 8: Using An External Editor with JShell


668

It is very difficult to type lengthy code from JShell. To overcome this problem,JShell provide in-built editor.
Page

We can open inbuilt editor with the command: /edit

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> /edit

diagram(image) of inbuilt-editor

If we are not satisfied with JShell in-built editor ,then we can set our own editor to the JShell.For this we have to
use /set editor command.

Eg:

jshell> /set editor "C:\\WINDOWS\\system32\\notepad.exe"


jshell> /set editor "C:\\Program Files\\EditPlus\\editplus.exe"

How to Set Notepad as editor to JShell:


jshell> /set editor "C:\\WINDOWS\\system32\\notepad.exe"
| Editor set to: C:\WINDOWS\system32\notepad.exe

If we type /edit automatically Notepad will be openend.

jshell> /edit

But this way of setting editor is temporary and it is applicable only for current session.

If we want to set current editor as permanent,then we have to use the command

jshell> /set editor -retain


| Editor setting retained: C:\WINDOWS\system32\notepad.exe

How to set EditPlus as editor to JShell:


jshell> /set editor "C:\\Program Files\\EditPlus\\editplus.exe"
| Editor set to: C:\Program Files\EditPlus\editplus.exe

If we type /edit automatically EditPlus editor will be opened.

How to set default editor once again:


669

We have to type the following command from the jshell


Page

jshell> /set editor -default

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| Editor set to: -default

To make default editor as permanent:


jshell> /set editor -retain
| Editor setting retained: -default

Note: It is not recommended to set IntelliJ,Eclipse,NetBeans as JShell editors,because it increases startup time
and shutdown time of jshell.

FAQs:
1. How to open default editor of JShell?
2. How to configure our own editor to the JShell?
3. How to configure Notepad as editor to the JShell?
4. How to make our customized editor as permanent editor in the JShell?

670

UNIT – 9: Using classes, interfaces and enum with JShell


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the JShell we can declare classes,interfaces,enums also.
We can use /types command to list out our created types like classes,interfaces and enums.

jshell> class Student{}


| created class Student

jshell> interface Interf{}


| created interface Interf

jshell> enum Colors{}


| created enum Colors

jshell> /types
| class Student
| interface Interf
| enum Colors

But recommened to use editor to type lengthy classes,interfaces and enums.

1) 1 : public class Student


2) {
3) private String name;
4) private int rollno;
5) Student(String name,int rollno)
6) {
7) this.name=name;
8) this.rollno=rollno;
9) }
10) public String getName()
11) {
12) return name;
13) }
14) public int getRollno()
15) {
16) return rollno;
17) }
18) }

jshell> /edit
| created class Student
671

jshell> /types
| class Student
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> Student s=new Student("Durga",101);
s ==> Student@754ba872
| created variable s : Student

jshell> s.getName()
$3 ==> "Durga"
| created scratch variable $3 : String

jshell> s.getRollno()
$4 ==> 101
| created scratch variable $4 : int

1) public interface Interf


2) {
3) public static void m1()
4) {
5) System.out.println("interface static method");
6) }
7) }
8) enum Beer
9) {
10) KF("Sour"),KO("Bitter"),RC("Salty");
11) String taste;
12) Beer(String taste)
13) {
14) this.taste=taste;
15) }
16) public String getTaste()
17) {
18) return taste;
19) }
20) }

jshell> /edit
| created interface Interf
| created enum Beer

jshell> Interf.m1()
672

interface static method

jshell> Beer.KF.getTaste()
Page

$8 ==> "Sour"

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| created scratch variable $8 : String

UNIT – 10: Loading and Saving Snippets in JShell


We can load and save snippets from the file.

Assume all our required snippets are available in mysnippets.jsh. This file can be with any extension like .txt,But
recommended to use .jsh.

mysnippets.jsh:
String s="Durga";
public void m1()
{
System.out.println("method defined in the file");
}
int x=10;

We can load all snippets of this file from the JShell with /open command as follows.

jshell> /list

jshell> /open mysnippets.jsh

jshell> /list

1 : String s="Durga";
2 : public void m1()
{
System.out.println("method defined in the file");
}
3 : int x=10;

Once we loaded snippets,we can use these loaded snippets based on our requirement.

jshell> m1()
673

method defined in the file


Page

jshell> s
s ==> "Durga"

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| value of s : String

jshell> x
x ==> 10
| value of x : int

Saving JShell snippets to the file:


We can save JShell snippets to the file with /save command.

jshell> /help save


|
| /save <file>
| Save the source of current active snippets to the file.
|
| /save -all <file>
| Save the source of all snippets to the file.
| Includes source including overwritten, failed, and start-up code.
|
| /save -history <file>
| Save the sequential history of all commands and snippets entered since jshell was launched.
|
| /save -start <file>
| Save the current start-up definitions to the file.

Note: If the specified file is not available then this save command itself will create that file.

jshell> /save active.jsh

jshell> /save -all all.jsh

jshell> /save -start start.jsh

jshell> /save -history history.jsh

jshell> /ex
674

| Goodbye

D:\>type active.jsh
Page

int x=10;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


x
System.out.println("Hello");
public void m1(){}

D:\>type start.jsh
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.*;

Note: Bydefault,all files will be created in current working directory. If we want in some other location then we
have to use absolute path(Full Path).

jshell> /save D:\\durga_classes\\active.jsh

How to Reload Previous state (session) of JShell:


We can reload previous session with /reload command so that all snippets of previous session will be available in
the current session.

jshell> /reload -restore

Eg:

jshell> int x=10


x ==> 10
| created variable x : int

jshell> 10+20
$2 ==> 30
| created scratch variable $2 : int

jshell> System.out.println("Hello");
Hello
675

jshell> /list
Page

1 : int x=10;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2 : 10+20
3 : System.out.println("Hello");

jshell> /exit
| Goodbye

D:\>jshell -v
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

jshell> /reload -restore


| Restarting and restoring from previous state.
-: int x=10;
-: 10+20
-: System.out.println("Hello");
Hello
jshell> /list
1 : int x=10;
2 : 10+20
3 : System.out.println("Hello");

How to reset JShell State:


We can reset JShell state by using /reset command.

jshell> /help reset


|
| /reset
|
| Reset the jshell tool code and execution state:
| * All entered code is lost.
| * Start-up code is re-executed.
| * The execution state is restarted.
| Tool settings are maintained, as set with: /set ...
| Save any work before using this command.

Eg:
jshell> /list

1 : int x=10;
676

2 : 10+20
3 : System.out.println("Hello");
Page

jshell> /reset

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


| Resetting state.

jshell> /list

UNIT – 11: Using Jar Files in the JShell


It is very easy to use external jar files in the jshell. We can add Jar files to the JShell in two ways.

1. From the Command Prompt


2. From the JShell Itself

1. Adding Jar File to the JShell from Command Prompt:


We have to open jshell with --class-path option.

D:\>jshell -v --class-path C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar

Demo Program to get all employees information from oracle database:

mysnippets.jsh:
1) import Java.sql.*;
2) public void getEmpInfo() throws Exception
3) {
677

4) Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","sc
ott","tiger");
Page

5) Statement st=con.createStatement();
6) ResultSet rs=st.executeQuery("select * from employees");

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


7) while(rs.next())
8) {
9) System.out.println(rs.getInt(1)+".."+rs.getString(2)+".."+rs.getDouble(3)+".."+rs.getStri
ng(4));
10) }
11) con.close();
12) }

DaTabase info:

1) create Table employees(eno number,ename varchar2(10),esal number(10,2),eaddr varchar2(10


));
2) insert into employees values(100,'Sunny',1000,'Mumbai');
3) insert into employees values(200,'Bunny',2000,'Hyd');
4) insert into employees values(300,'Chinny',3000,'Hyd');
5) insert into employees values(400,'Vinny',4000,'Delhi');

D:\>jshell -v --class-path C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar

jshell> /open mysnippets.jsh


jshell> getEmpInfo()
100..Sunny..1000.0..Mumbai
200..Bunny..2000.0..Hyd
300..Chinny..3000.0..Hyd
400..Vinny..4000.0..Delhi

2.Adding Jar File to the JShell from JShell itself:


We can add External Jars to the jshell from the Jshell itself with /env command.

jshell> /env --class-path C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar


| Setting new options and restoring state.

jshell> /open mysnippets.jsh

jshell> getEmpInfo()
100..Sunny..1000.0..Mumbai
200..Bunny..2000.0..Hyd
300..Chinny..3000.0..Hyd
678

400..Vinny..4000.0..Delhi

Note: Internally JShell will use environment variable CLASSPATH if we are not setting CLASSPATH explicitly.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


UNIT – 12: How to customize JShell Startup
By default the following snippets will be executed at the time of JShell Startup.

jshell> /list -start

s1 : import Java.io.*;
s2 : import Java.math.*;
s3 : import Java.net.*;
s4 : import Java.nio.file.*;
s5 : import Java.util.*;
s6 : import Java.util.concurrent.*;
s7 : import Java.util.function.*;
s8 : import Java.util.prefs.*;
s9 : import Java.util.regex.*;
s10 : import Java.util.stream.*;
679

We can customize these start-up snippets based on our requirement.


Page

Assume our required start-up snippets are available in myStartup.jsh.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


mystartup.jsh:

int x =10;
String s="DURGA";
System.out.println("Hello Durga Welcome to JShell");

To provide these snippets as startup snippets we have to open JShell as follows

D:\>jshell -v --startup mystartup.jsh


Hello Durga Welcome to JShell
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

jshell> /list -start

s1 : int x =10;
s2 : String s="DURGA";
s3 : System.out.println("Hello Durga Welcome to JShell");

Note: if we want DEFAULT import start-up snippets also then we have to open JShell as follows.

D:\>jshell -v --startup DEFAULT mystartup.jsh


Hello Durga Welcome to JShell
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

jshell> /list
1 : int x =10;
2 : String s="DURGA";
3 : System.out.println("Hello Durga Welcome to JShell");

jshell> /list -start

s1 : import Java.io.*;
s2 : import Java.math.*;
s3 : import Java.net.*;
s4 : import Java.nio.file.*;
s5 : import Java.util.*;
s6 : import Java.util.concurrent.*;
s7 : import Java.util.function.*;
s8 : import Java.util.prefs.*;
680

s9 : import Java.util.regex.*;
s10 : import Java.util.stream.*;
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note: To import all JAVASE packages (almost around 173 packages) at the time of startup we have to open JShell
as follows.

D:\>jshell -v --startup JAVASE

jshell> /list

jshell> /list -start

s1 : import Java.applet.*;
s2 : import Java.awt.*;
s3 : import Java.awt.color.*;
..
s172 : import org.xml.sax.ext.*;
s173 : import org.xml.sax.helpers.*;

Note: In addition to JAVASE, to provide our own snippets we have to open JShell as follows

D:\>jshell -v --startup JAVASE mystartup.jsh


Hello Durga Welcome to JShell
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

jshell> /list

1 : int x =10;
2 : String s="DURGA";
3 : System.out.println("Hello Durga Welcome to JShell");

jshell> /list -start

s1 : import Java.applet.*;
s2 : import Java.awt.*;
s3 : import Java.awt.color.*;
..
s172 : import org.xml.sax.ext.*;
s173 : import org.xml.sax.helpers.*;

Q. What is the difference between the following?


681

1. jshell -v
2. jshell -v --startup mystartup.jsh
3. jshell -v --startup DEFAULT mystartup.jsh
Page

4. jshell -v --startup JAVASE

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5. jshell -v --startup JAVASE mystartup.jsh

Need of PRINTING Option at the startup:


Usually we can use System.out.print() or System.out.println() methods to print some statements to the console. If
we use PRINTING Option then several overloaded print() and println() methods will be provided at the time of
startup and these internally call System.out.print() and System.out.println() methods methods.

Hence to print statements to the console just we can use print() or println() methods directly instead of using
System.out.print() or System.out.println() methods.

D:\>jshell -v --startup PRINTING

jshell> /list -start

s1 : void print(boolean b) { System.out.print(b); }


s2 : void print(char c) { System.out.print(c); }
s3 : void print(int i) { System.out.print(i); }
s4 : void print(long l) { System.out.print(l); }
s5 : void print(float f) { System.out.print(f); }
s6 : void print(double d) { System.out.print(d); }
s7 : void print(char s[]) { System.out.print(s); }
s8 : void print(String s) { System.out.print(s); }
s9 : void print(Object obj) { System.out.print(obj); }
s10 : void println() { System.out.println(); }
s11 : void println(boolean b) { System.out.println(b); }
s12 : void println(char c) { System.out.println(c); }
s13 : void println(int i) { System.out.println(i); }
s14 : void println(long l) { System.out.println(l); }
s15 : void println(float f) { System.out.println(f); }
s16 : void println(double d) { System.out.println(d); }
s17 : void println(char s[]) { System.out.println(s); }
s18 : void println(String s) { System.out.println(s); }
s19 : void println(Object obj) { System.out.println(obj); }
s20 : void printf(Java.util.Locale l, String format, Object... args) { System.out.printf(l, format, args); }
s21 : void printf(String format, Object... args) { System.out.printf(format, args); }

Now onwards,to print some statements to the console directly we can use print() and println() methodds.

jshell> print("Hello");
682

Hello
jshell> print(10.5)
10.5
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Note:

1. Total 21 overloaded print(),println() and printf() methods provided because of PRINTING shortcut.
2. Whenever we are using PRINTING shortcut,then DEFAULT imports won't come. Hence,to get DEFAULT imports
and PRINTING shortcut simultaneously,we have to open JShell as follows.

D:\>jshell -v --startup DEFAULT PRINTING

Note:

Various allowed options with --startup are :


1. DEFAULT
2. JAVASE
3. PRINTING

UNIT – 13: Shortcuts and Auto-Completion of Commands


Shortcut for Creating Variables:
Just type the value on the JShell and then "Shift+Tab followed by v" then complete variable declaration code will
be generated we have to provide only name of the variable.
683

jshell> "Durga" // just press "Shift+Tab followed by v"


Page

jshell> String s= "Durga"


We have to provide only name s

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


jshell> 10.5 // just press "Shift+Tab followed by v"
jshell> double d = 10.5

Shortcut for auto-import:


just type class or interface name on the JShell and press "Shift+Tab followed by i".
Then we will get options for import.

jshell> Connection // press "Shift+Tab followed by i"


0: Do nothing
1: import: com.sun.jdi.connect.spi.Connection
2: import: Java.sql.Connection
Choice: //enter 2
Imported: Java.sql.Connection

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.*
| import Java.sql.Connection

Auto Completion commands :


684

1. To get all static members of the class:


jshell>classsname.<Tab>
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Eg:

jshell> String.<Tab>
CASE_INSENSITIVE_ORDER class copyValueOf(
format( join( valueOf(

2. To get all instance members of class:


jshell>objectreference.<Tab>

jshell> String s="Durga";


jshell> s.<Tab>
charAt( chars() codePointAt( codePointBefore(
codePointCount( codePoints() compareTo( compareToIgnoreCase(
concat( contains( contentEquals( endsWith(
equals( equalsIgnoreCase( getBytes( getChars(
getClass() hashCode() indexOf( intern()
isEmpty() lastIndexOf( length() matches(
notify() notifyAll() offsetByCodePoints( regionMatches(
replace( replaceAll( replaceFirst( split(
startsWith( subSequence( substring( toCharArray()
toLowerCase( toString() toUpperCase( trim()

3. To get signature and documentation of a method:


jshell> classname.methodname(<Tab>
jshell> objectreference.methodname(<Tab>

jshell> s.sub<Tab>
subSequence( substring(

jshell> s.substring(
substring(

jshell> s.substring(<Tab>
Signatures:
String String.substring(int beginIndex)
String String.substring(int beginIndex, int endIndex)

<press Tab again to see documentation>


685

jshell> s.substring(<Tab>
String String.substring(int beginIndex)
Returns a string that is a substring of this string.The substring begins with the character at the specified index and
Page

extends to the end of this string.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)

Parameters:
beginIndex - the beginning index, inclusive.

Returns:
the specified substring.

Note: Even this <Tab> short cut applicable for our own classes and methods also.

jshell> public void m1(int...x){}


| created method m1(int...)

jshell> m1(<Tab>
m1(

jshell> m1(<Tab>
Signatures:
void m1(int... x)

686
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


The Java Platform Module System (JPMS)

JPMS Agenda
1) Introduction

2) What is the need of JPMS?

3) Jar Hell or Classpath Hell

4) What is a Module

5) Steps to Develop First Module Based Application

6) Various Possible Ways to Compile & run a Module

7) Inter Module Dependencies

8) requires and exports directive

9) JPMS vs NoClassDefFoundError

10) Transitive Dependencies (requires with transitive Keyword)

11) Optional Dependencies (Requires Directive with static keyword)

12) Cyclic Dependencies

13) Qualified Exports

14) Module Graph

15) Observable Modules

16) Aggregator Module


687

17) Package Naming Conflicts


Page

18) Module Resolution Process (MRP)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Java Platform Module System (JPMS)
Introduction:
Modularity concept introduced in Java 9 as the part of Jigsaw project. It is the main important concept in java 9.

The development of modularity concept started in 2005.


The First JEP(JDK Enhancement Proposal) for Modularity released in 2005. Java people tried to release Modularity
concept in Java 7(2011) & Java 8(2014). But they failed. Finally after several postponements this concept
introduced in Java 9.

Until Java 1.8 version we can develop applications by writing several classes, interfaces and enums. We can places
these components inside packages and we can convert these packages into jar files. By placing these jar files in
the classpath, we can run our applications. An enterprise application can contain 1000s of jar files also.

Hence jar file is nothing but a group of packages and each package contains several .class files.

But in Java 9, a new construct got introduced which is nothing but 'Module'. From java 9 version onwards we can
develop applications by using module concept.

Module is nothing but a group of packages similar to jar file. But the specialty of module when compared with jar
file is, module can contain configuration information also.

Hence module is more powerful than jar file. The configuration information of module should be specified in a
special file named with module-info.java

Every module should compulsory contains module-info.java, otherwise JVM won't consider that as a module of
Java 9 platform.

Package - 1 Package - 2 ------------ Package - n


688

module-info.java
Page

In Java 9, JDK itself modularized. All classes of Java 9 are grouped into several modules (around 98) like

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


java.base
java.logging
java.sql
java.desktop(AWT/Swing)
java.rmi etc
java.base module acts as base for all java 9 modules.
We can find module of a class by using getModule() method.

Eg: System.out.println(String.class.getModule());//module java.base

What is the need of JPMS?


Application development by using jar file concept has several serious problems.

Problem-1: Unexpected NoClassDefFoundError in middle of program execution


There is no way to specify jar file dependencies until java 1.8V.At runtime,if any dependent jar file is missing then
in the middle of execution of our program, we will get NoClassDefFoundError, which is not at all recommended.

Demo Program to demonistrate NoClassDefFoundError:

durgajava9
|-A1.java
|-A2.java
|-A3.java
|-Test.java

A1.java:

1) package pack1;
2) public class A1
3) {
4) public void m1()
5) {
6) System.out.println("pack1.A");
7) }
8) }

A2.java
689

1) package pack2;
2) import pack1.A1;
3) public class A2
Page

4) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5) public void m2()
6) {
7) System.out.println("pack2.A2 method");
8) A1 a = new A1();
9) a.m1();
10) }
11) }

A3.java:

1) import pack2.A2;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) System.out.println("Test class main");
7) A2 a= new A2();
8) a.m2();
9) }
10) }

D:\durgajava9>javac -d . A1.java
D:\durgajava9>javac -d . A2.java
D:\durgajava9>javac -d . A3.java
D:\durgajava9>javac Test.java

durgajava9
|-Test.class
|-pack1
|-A1.class
|-pack2
|-A2.class

At runtime, by mistake if pack1 is not available then after executing some part of the code in the middle, we will
get NoClassDefFoundError.

D:\durgajava9>java Test
Test class main
pack2.A2 method
Exception in thread "main" java.lang.NoClassDefFoundError: pack1/A1

But in Java9, there is a way to specify all dependent modules information in module-info.java. If any module is
missing then at the beginning only, JVM will identify and won't start its execution. Hence there is no chance of
690

raising NoClassDefFoundError in the middle of execution.


Page

Problem 2: Version Conflicts or Shadowing Problems

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


If JVM required any .class file, then it always searches in the classpath from left to right until required match
found.

classpath = jar1;jar2;jar3;jar4
If jar4 requires Test.class file of jar3.But Different versions of Test.class is available in jar1, jar2 and jar3. In this
case jar1 Test.class file will be considered, because JVM will always search from Left to Right in the classpath. It
will create version conflicts and causes abnormal behavior of program.

But in java9 module system, there is a way to specify dependent modules information for every module
seperately.JVM will always consider only required module and there is no order importance. Hence version
conflicts won't be raised in Java 9.

Problem 3: Security problem


There is no mechanism to hide packages of jar file.

Package Package
pack1 pack2

Jar File

Assume pack1 can be used by other jar files, but pack2 is just for internal purpose only. Until Java 8 there
is no way to specify this information. Everything in jar file is public and available to everyone. Hence there may be
a chance of Security problems.

public is too much public in jar files.

But in Java 9 Module system, we can export particular package of a module. Only this exported package can be
used by other modules. The remaining packages of that module are not visible to outside. Hence Strong
encapsulation is available in Java 9 and there is no chance of security problems.

Even though class is public, if module won't export the corresponding package, then it cannot be accessed by
other modules. Hence public is not really that much public in Java 9 Module System.

Module can offer Strong Encapsulation than Jar File.


691

Problem 4: JDK/JRE having Monolithic Structure and Very Large Size


Page

The number of classes in Java is increasing very rapidly from version to version.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JDK 1.0V having 250+ classes
JDK 1.1V having 500+ classes
...
JDK 1.8V having 4000+ classes

And all these classes are available in rt.jar.


Hence the size of rt.jar is increasing from version to version.
The size of rt.jar in Java 1.8Version is around 60 MB.

To run small program also, total rt.jar should be loaded, which makes our application heavy weight and not
suitable for IOT applications and micro services which are targeted for portable devices.
It will create memory and performance problems also.
(This is something like inviting a Big Elephant in our Small House: Installing a Heavy Weight Java application in a
small portable device).

But in java 9, rt.jar removed. Instead of rt.jar all classes are maintained in the form of modules. Hence from Java 9
onwards JDK itself modularized. Whenever we are executing a program only required modules will be loaded
instead of loading all modules, which makes our application light weighted.

Now we can use java applications for small devices also. From Java 9 version onwards, by using JLINK , we can
create our own very small custom JREs with only required modules.

Q. Explain differences between jar file and Java 9 module


Jar Module
1) Jar is a group of packages and each package 1) Module is also a group of packages and each
contains several classes package contains several classes. Module can
also contain one special file module-info.java to
hold module specific dependencies and
configuration information.
2) In jar file, there is no way to specify 2) For every module we have to maintain a
dependent jar files information special file module-info.java to specify module
dependencies
3) There is no way to check all jar file 3) JVM will check all module dependencies at
dependencies at the beginning only. Hence in the beginning only with the help of module-
the middle of the program execution there may info.java. If any dependent module is missing
be a chance of NoClassDefFoundError. then JVM won’t start its execution. Hence there
is no chance of NoClassDefFoundError in the
692

middle of execution.
4) In the classpath the order of jar files 4) In the module-path order is not important.
important and JVM will always considers from JVM will always check from the dependent
Page

left to right for the required .class files. If module only for the required .class files. Hence

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


multiple jars contain the same .class file then there is no chance of version conflicts and
there may be a chance of Version conflicts and abnormal behavior of the application.
results abnormal behavior of our application
5) In jar file there is no mechanism to control 5) In module there is a mechanism to control
access to the packages. Everything present in access to the packages.
the jar file is public to everyone. Any person is Only exported packages are visible to other
allowed to access any component from the jar modules. Hence there is no chance of security
file. Hence there may be a chance of security problems
problems
6) Jars follows monolithic structure and 6) Modules follow distributed structure and
applications will become heavy weight and not applications will become light weighted and
suitable for small devices. suitable for small devices.
7) Jar files approach cannot be used for IOT 7) Modules based approach can be used for IOT
devices and micro services. devices and micro services

Q. What is Jar Hell or Classpath Hell?


The problems with use of jar files are:

1. NoClassDefFoundError in the middle of program execution


2. Version Conflicts and Abnormal behavior of program
3. Lack of Security
4. Bigger Size

This set of Problems is called Jar Hell OR Classpath Hell. To overcome this, we should go for JPMS.

Q. What are various Goals/Benefits of JPMS?


1. Reliable Configuration
2. Strong Encapsulation & Security
3. Scalable Java Platform
4. Performance and Memory Improvements
etc

What is a Module:
Module is nothing but collection of packages. Each module should compulsory contains a special configuration
file: module-info.java.
693

Package - 1 Package - 2 ------------ Package - n


Page

module-info.java
CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


We can define module dependencies inside module-info.java file.

module moduleName
{
Here we have to define module dependencies which represents
1. What other modules required by this module?
2. What packages exported by this module for other modules?
etc
}

Steps to Develop First Module Based Application:

src

moduleA

pack1

Test.java

module-info.java

Step-1: Create a package with our required classes


694

1) package pack1;
2) public class Test
Page

3) {
4) public static void main(String[] args)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


5) {
6) System.out.println("First Module in JPMS");
7) }
8) }

Step-2: Writing module-info.java


For every module we should to write a special file named with module-info.java.
In this file we have to define dependencies of module.

module moduleA
{
}

Step-3: Arrange all files in the required package structure


Arrange all the files according to required folder structure

src

moduleA

pack1

Test.java

module-info.java
695

Step-4: Compile module with --module-source-path option


Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


javac --module-source-path src -d out -m moduleA

The generated class file structure is:

out

moduleA

pack1

Test.class

module-info.class

Step-5: Run the class with --module-path option


java --module-path out -m moduleA/pack1.Test

Output: First Module in JPMS

Case-1:

If module-info.java is not available then the code won't compile and we will get error. Hence module-info.java is
mandatory for every module.

javac --module-source-path src -d out -m moduleA


error: module moduleA not found in module source path

Case-2:
696

Every class inside module should be part of some package, otherwise we will get compile time error saying :
Page

unnamed package is not allowed in named modules


In the above application inside Test.java if we comment package statement

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


//package pack1;

1) public class Test


2) {
3) public static void main(String[] args)
4) {
5) System.out.println("First Module in JPMS");
6) }
7) }

error: unnamed package is not allowed in named modules

Case-3:
The module name should not ends with digit(like module1,module2 etc),otherwise we will get warning at compile
time.

javac --module-source-path src -d out -m module1


warning: [module] module name component module1 should avoid terminal digits

Various Possible Ways to Compile a Module:


javac --module-source-path src -d out -m moduleA
javac --module-source-path src -d out --module moduleA
javac --module-source-path src -d out
src/moduleA/module-info.java src/moduleA/pack1/Test.java
javac --module-source-path src -d out
C:/Users/Durga/Desktop/src/moduleA/module-info.java
C:/Users/Durga/Desktop/src/moduleA/pack1/Test.java

Various Possible Ways to Run a Module:


697

java --module-path out --add-modules moduleA pack1.Test


java --module-path out -m moduleA/pack1.Test
java --module-path out --module moduleA/pack1.Test
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Inter Module Dependencies:
Within the application we can create any number of modules and one module can use other modules.

We can define module dependencies inside module-info.java file.

module moduleName
{
Here we have to define module dependencies which represents
1. What other modules required by this module?
2. What packages exported by this module for other modules?
etc
}

Mainly we can use the following 2 types of directives

1. requires directive:

It can be used to specify the modules which are required by current module.

Eg:

1) module moduleA
2) {
3) requires moduleB;
4) }

It indicates that moduleA requires members of moduleB.

Note:

1. We cannot use same requires directive for multiple modules. For every module we have to use separate
requires directive.

requires moduleA,moduleB;  invalid

2. We can use requires directive only for modules but not for packages and classes.

2. exports directive:
698

It can be used to specify what packages exported by current module to the other modules.
Page

Eg:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) module moduleA
2) {
3) exports pack1;
4) }

It indicates that moduleA exporting pack1 package so that this package can be used by other modules.

Note: We cannot use same exports directive for exporting multiple packages. For every package a separate
exports directive must be required.

exports pack1,pack2;  invalid

Note: Be careful about syntax requires directive always expecting module name where as exports directive
expecting package name.

1) module modulename
2) {
3) requires modulename;
4) exports packagename;
5) }

Note:

By default all packages present in a module are private to that module. If module exports any package only that
particular package is accessible by other modules. Non exporting packages cannot be accessed by other modules.

Eg: Assume moduleA contains 2 packages pack1 and pack2. If moduleA exports only pack1 then other modules
can use only pack1. pack2 is just for its internal purpose and cannot be accessed by other modules.

1) module moduleA
2) {
3) exports pack1;
4) }

Demo program for inter module dependencies:


Rectangle diagram which represents total application
699

pack1 pack2
(A.java) (Test.java)
Page

module-info.java module-info.java

CONTACT US: moduleA moduleB


Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


moduleA components:
A.java:
1) package pack1;
2) public class A
3) {
4) public void m1()
5) {
6) System.out.println("Method of moduleA");
7) }
8) }

module-info.java:
1) module moduleA
2) {
3) exports pack1;
4) }

moduleB components:
Test.java:
1) package pack2;
2) import pack1.A;
3) public class Test
700

4) {
5) public static void main(String[] args)
6) {
Page

7) System.out.println("moduleB accessing members of moduleA");


8) A a = new A();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


9) a.m1();
10) }
11) }

module-info.java:
1) module moduleB
2) {
3) requires moduleA;
4) }

src

moduleA moduleB

pack1 pack2

A.java Test.java

module-info.java module-info.java

Compilation:
C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA,moduleB

Note: space is not allowed between the module names otherwise we will get error.

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB


error: Class names, 'moduleB', are only accepted if annotation processing is explicitly requested

out
701

moduleA moduleB
Page

pack1 pack2
CONTACT US:
Mobile: +91- 8885 25 26 27 A.class Mail ID: durgasoftonlinetraining@gmail.com
Test.class
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
module-info.class module-info.class
FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.
Execution:
C:\Users\Durga\Desktop>java --module-path out -m moduleB/pack2.Test

Output:
moduleB accessing members of moduleA
Method of moduleA

Case-1:
Even though class A is public, if moduleA won't export pack1, then moduleB cannot access A class.

Eg:

1) module moduleA
2) {
3) //exports pack1;
4) }

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA,moduleB


src\moduleB\pack2\Test.java:2: error: package pack1 is not visible
import pack1.A;
^
(package pack1 is declared in module moduleA, which does not export it)
1 error

Case-2:
We have to export only packages. If we are trying to export modules or classes then we will get compile time
error.
Eg-1: exporting module instead of package
702

1) module moduleA
2) {
Page

3) exports moduleA;
4) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB
src\moduleB\pack2\Test.java:2: error: package pack1 is not visible
import pack1.A;
^
(package pack1 is declared in module moduleA, which does not export it)
src\moduleA\module-info.java:3: error: package is empty or does not exist: moduleA
exports moduleA;

In this case compiler considers moduleA as package and it is trying to search for that package.

Eg-2: exporting class instead of package:

1) module moduleA
2) {
3) exports pack1.A;
4) }

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB


src\moduleB\pack2\Test.java:2: error: package pack1 is not visible
import pack1.A;
^
(package pack1 is declared in module moduleA, which does not export it)
src\moduleA\module-info.java:3: error: package is empty or does not exist: pack1.A
exports pack1.A;
^
2 errors

In this case compiler considers pack1.A as package and it is trying to search for that package.

Case-3:
If moduleB won't use "requires moduleA" directive then moduleB is not allowed to use members of moduleA,
even though moduleA exports.

1) module moduleB
2) {
3) //requires moduleA;
4) }

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB


src\moduleB\pack2\Test.java:2: error: package pack1 is not visible
703

import pack1.A;
^
(package pack1 is declared in module moduleA, but module moduleB does not read it)
Page

1 error

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Case-4:

If compiled codes are available in different packages then how to run?


We have to use special option: --upgrade-module-path

If compiled codes of moduleA is available in out and compiled codes of moduleB available in out2

out out 2

moduleA moduleB

pack1 pack2

A.class Test.class

module-info.class module-info.class

C:\Users\Durga\Desktop>java --upgrade-module-path out;out1 -m moduleB/pack2.Test


moduleB accessing members of moduleA
Method of moduleA

704
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Case-5:

If source codes of two modules are in different directories then how to compile?
Assume moduleA source code is available in src directory and moduleB source code is available in src2

src src 2

moduleA moduleB

pack1 pack2

A.java Test.java

module-info.java module-info.java

C:\Users\Durga\Desktop>javac --module-source-path src;src2 -d out -m moduleA, moduleB

Q. Which of the following are meaningful?


1) module moduleName
2) {
3) 1. requires modulename;
4) 2. requires modulename.packagename;
5) 3. requires modulename.packagename.classname;
6) 4. exports modulename;
7) 5. exports packagename;
8) 6. exports packagename.classname;
9) }

Answer: 1 & 5 are Valid

Note: We can use exports directive only for packages but not modules and classes, and we can use requires
705

directive only for modules but not for packages and classes.

Note: To access members of one module in other module, compulsory we have to take care the following 3
Page

things.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1. The module which is accessing must have requires dependency
2. The module which is providing functionality must have exports dependency
3. The member must be public.
JPMS vs NoClassDefFoundError:
In Java 9 Platform Modular System, JVM will check all dependencies at the beginning only. If any dependent
module is missing then JVM won't start its execution. Hence there is no chance of NoClassDefFoundError in the
middle of Program execution.

Demo Program:

pack1 pack2 pack3


(A.java) (B.java) (Test.java)

module-info.java module-info.java module-info.java

moduleA moduleB moduleC

Components of moduleA:
A.java:

1) package pack1;
2) public class A
3) {
4) public void m1()
5) {
6) System.out.println("Method of moduleA");
7) }
8) }

module-info.java:

1) module moduleA
2) {
3) exports pack1;
706

4) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Components of moduleB:
B.java:

1) package pack2;
2) import pack1.A;
3) public class B
4) {
5) public void m2()
6) {
7) System.out.println("Method of moduleB");
8) A a = new A();
9) a.m1();
10) }
11) }

module-info.java:

1) module moduleB
2) {
3) requires moduleA;
4) exports pack2;
5) }

Components of moduleC:
Test.java:

1) package pack3;
2) import pack2.B;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
707

7) System.out.println("Test class main method");


8) B b = new B();
9) b.m2();
Page

10) }
11) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


module-info.java:

1) module moduleC
2) {
3) requires moduleB;
4) }

Compilation and Execution:


C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB, moduleC

C:\Users\Durga\Desktop>java --module-path out -m moduleC/pack3.Test


Test class main method
Method of moduleB
Method of moduleA

If we delete compiled code of module (inside out folder), then JVM will raise error at the beginning only and JVM
won't start program execution.

C:\Users\Durga\Desktop>java --module-path out -m moduleC/pack3.Test


Error occurred during initialization of boot layer
java.lang.module. FindException: Module moduleA not found, required by moduleB

But in Non Modular programming, JVM will start execution and in the middle, it will raise NoClassDefFoundError.

Hence in Java Platform Module System, there is no chance of getting NoClassDefFoundError in the middle of
program execution.

Transitive Dependencies (requires with transitive Keyword):


AB, BC ==> AC
This property in mathematics is called Transitive Property.

Student1 requires Material, only for himself, if any other person asking he won't share.

1) module student1
2) {
3) requires material;
708

4) }

"Student1 requires material not only for himself, if any other person asking him, he will share it"
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) module Student1
2) {
3) requires transitive material;
4) }

Sometimes module requires the components of some other module not only for itself and for the modules that
requires that module also. For this requirement we can use transitive keyword.

The transitive keyword says that "Whatever I have will be given to a module that asks me."

Case-1:
1) module moduleA
2) {
3) exports pack1;
4) }
5) module moduleB
6) {
7) requires moduleA;
8) }
9) module moduleC
10) {
11) requires moduleB;
12) }

requires requires
moduleC moduleB moduleA

In this case only moduleB is available to moduleC and moduleA is not available. Hence moduleC cannot use the
members of moduleA directly.

Case-2:
1) module moduleA
2) {
3) exports pack1;
4) }
709

5) module moduleB
6) {
7) requires transitive moduleA;
Page

8) }
9) module moduleC

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10) {
11) requires moduleB;
12) }

requires requires
Module C Module B Module A

requires

In this both moduleB and moduleA are available to moduleC. Now moduleC can use members of both modules
directly.

Case Study:
Assume Modules C1, C2,....C10 requires Module B and Module B requires A.

C1

C2

A B
C3
:
:
:
C10

If we write "requires transitive A" inside module B

1) module B
710

2) {
3) requires transitive A;
4) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Then module A is by default available to C1, C2,.., C10 automatically. Inside every module of C, we are not
required to use "requires A" explicitly. Hence transitive keyword promotes code reusability.

Note: Transitive means implied readability i.e., Readability will be continues to the next level.

Demo Program for transitive keyword:

pack3 pack2 pack1


(Test.java) (B.java) (A.java)

module-info.java module-info.java module-info.java

moduleC moduleB moduleA

moduleA components:
A.java:

1) package pack1;
2) public class A
3) {
4) public void m1()
5) {
6) System.out.println("moduleA method");
7) }
8) }

module-info.java:

1) module moduleA
2) {
3) exports pack1;
4) }

moduleB components:
B.java:
711

1) package pack2;
2) import pack1.A;
3) public class B
Page

4) {
5) public A m2()

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


6) {
7) System.out.println("moduleB method");
8) A a = new A();
9) return a;
10) }
11) }

module-info.java:

1) module moduleB
2) {
3) requires transitive moduleA;
4) exports pack2;
5) }

moduleC components:
Test.java:

1) package pack3;
2) import pack2.B;
3) public class Test
4) {
5) public static void main(String[] args)
6) {
7) System.out.println("Test class main method");
8) B b = new B();
9) b.m2().m1();
10) }
11) }

module-info.java:

1) module moduleC
2) {
712

3) requires moduleB;
4) }
Page

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB, moduleC

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


C:\Users\Durga\Desktop>java --module-path out -m moduleC/pack3.Test
Test class main method
moduleB method
moduleA method

In the above program if we are not using transitive keyword then we will get compile time error because moduleA
is not available to moduleC.

javac --module-source-path src -d out -m moduleA,moduleB,moduleC


src\moduleC\pack3\Test.java:9: error: A.m1() in package pack1 is not accessible
b.m2().m1();
^
(package pack1 is declared in module moduleA, but module moduleC does not read it)

Optional Dependencies (Requires Directive with static keyword):


If Dependent Module should be available at compile time but optional at runtime, then such type of dependency
is called Otional Dependency. We can specify optional dependency by using static keyword.

Syntax: requires static <modulename>

The static keyword is used to say that, "This dependency check is mandatory at compile time and optional at
runtime."

Eg1:

1) module moduleB
2) {
3) requires moduleA;
4) }

moduleA should be available at the time of compilation and runtime. It is not optional dependency.

Eg2:

1) module moduleB
2) {
3) requires static moduleA;
4) }

At the time of compilation moduleA should be available, but at runtime it is optional. i.e., at runtime even
713

moduleA is not available JVM will execute code.

Demo Program for Optional Dependency:


Page

CONTACT US: pack1 pack2


Mobile: +91- 8885 25 26 27
(A.java) Mail ID: durgasoftonlinetraining@gmail.com
(B.java)
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com
module-info.java module-info.java
FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.

moduleA moduleB
moduleA components:
A.java:

1) package pack1;
2) public class A
3) {
4) public void m1()
5) {
6) System.out.println("moduleA method");
7) }
8) }

module-info.java:

1) module moduleA
2) {
3) exports pack1;
4) }

moduleB components:
Test.java:

1) package pack2;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) System.out.println("Optional Dependencies Demo!!!");
7)
714

8) }
9) }
Page

module-info.java:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) module moduleB
2) {
3) requires static moduleA;
4) }

At the time of compilation both modules should be available. But at runtime, we can run moduleB Test class, even
moduleA compiled classes are not available i.e., moduleB having optional dependency with moduleA.

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA,moduleB

C:\Users\Durga\Desktop>java --module-path out -m moduleB/pack2.Test


Optional Dependencies Demo!!!

If we remove static keyword and at runtime if we delete compiled classes of moduleA, then we will get error.

C:\Users\Durga\Desktop>java --module-path out -m moduleB/pack2.Test


Error occurred during initialization of boot layer
java.lang.module.FindException: Module moduleA not found, required by moduleB

Use cases of Optional Dependencies:


Usage of optional dependencies is very common in Programming world.

Sometimes we can develop library with optional dependencies.


Eg 1: If apache http Client is available use it, otherwise use HttpURLConnection.
Eg 2: If oracle module is available use it, otherwise use mysql module.

Why we should do this? For various reasons –

1. When distributing a library and we may not want to force a big dependency to the client.
2. On the other hand, a more advanced library may have performance benefits, so whatever module client needs,
he can use.
3. We may want to allow easily pluggable implementations of some functionality. We may provide
implementations using all of these, and pick the one whose dependency is found.
715

Q. What is the difference between the following?


Page

1) module moduleB

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2) {
3) 1. requires moduleA;
4) 2. requires transitive moduleA
5) 3. requires static moduleA
6) }

Cyclic Dependencies:
If moduleA depends on moduleB and moduleB depends on moduleA, such type of dependency is called cyclic
dependency.

Cyclic Dependencies between the modules are not allowed in java 9.

Demo Program:

moduleA moduleB

moduleA components:
module-info.java

1) module moduleA
2) {
3) requires moduleB;
4) }

moduleB components:
module-info.java

1) module moduleB
716

2) {
3) requires moduleA;
4) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


C:\Users\Durga\Desktop>javac --module-source-path src -d out -m moduleA, moduleB
src\moduleB\module-info.java:3: error: cyclic dependence involving moduleA
requires moduleA;

There may be a chance of cyclic dependency between more than 2 modules also.
moduleA requires moduleB
moduleB requires moduleC
moduleC requires moduleA

moduleA moduleB moduleC

Note: In all predefined modules also, there is no chance of cyclic dependency

717
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


718
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Qualified Exports:
Sometimes a module can export its package to specific module instead of every module. Then the specified
module only can access. Such type of exports are called Qualified Exports.

Syntax:
exports <pack1> to <module1>,<module2>,...

Eg:

1) module moduleA
2) {
3) exports pack1;//to export pack1 to all modules
4) exports pack1 to moduleA;// to export pack1 only for moduleA
5) exports pack1 to moduleA,moduleB;// to export pack1 for both moduleA,moduleB
6) }

Demo Program for Qualified Exports:

pack1 pack2 pack3 packA packB


(A.java) (B.java) (C.java) (Test.java) (Test.java)

module-info.java module-info.java module-info.java

exportermodule moduleA moduleB

Components of exportermodule:
A.java:

1) package pack1;
2) public class A
3) {
4) }

B.java:
719

1) package pack2;
2) public class B
3) {
Page

4) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


C.java:

1) package pack3;
2) public class C
3) {
4) }

module-info.java:

1) module exportermodule
2) {
3) exports pack1;
4) exports pack2 to moduleA;
5) exports pack3 to moduleA,moduleB;
6) }

moduleA moduleB
pack1 √ √
pack2 √ 
pack3 √ √

Components of moduleA:
Test.java:

1) package packA;
2) import pack1.A;
3) import pack2.B;
4) import pack3.C;
5) public class Test
6) {
7) public static void main(String[] args)
8) {
9) System.out.println("Qualified Exports Demo");
10) }
11) }

module-info.java:
720

1) module moduleA
2) {
3) requires exportermodule;
Page

4) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Explanation:
For moduleA, all 3 packages are available. Hence we can compile and run moduleA successfully.
C:\Users\Durga\Desktop>javac --module-source-path src -d out -m exportermodule, moduleA
C:\Users\Durga\Desktop>java --module-path out -m moduleA/packA.Test
Qualified Exports Demo
Components of moduleB:
Test.java:

1) package packB;
2) import pack1.A;
3) import pack2.B;
4) import pack3.C;
5) public class Test
6) {
7) public static void main(String[] args)
8) {
9) System.out.println("Qualified Exports Demo");
10) }
11) }

module-info.java:

1) module moduleB
2) {
3) requires exportermodule;
4) }

Explanation:
For moduleB, only pack1 and pack3 are available. pack2 is not available. But in moduleB we are trying to access
pack2 and hence we will get compile time error.

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m exportermodule, moduleB


src\moduleB\packB\Test.java:3: error: package pack2 is not visible
import pack2.B;
^
(package pack2 is declared in module exportermodule, which does not export it to module moduleB)
1 error
721

Q. Which of the following directives are valid inside module-info.java:


Page

1. requires moduleA;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2. requires moduleA,moduleB;
3. requires moduleA.pack1;
4. requires moduleA.pack1.A;
5. requires static moduleA;
6. requires transitive moduleA;
7. exports pack1;
8. exports pack1,pack2;
9. exports moduleA;
10. exports moduleA.pack1.A;
11. exports pack1 to moduleA;
12. exports pack1 to moduleA,moduleB;

Answers: 1,5,6,7,11,12

Module Graph:
The dependencies between the modules can be represented by using a special graph, which is nothing but
Module Graph.

Eg1: If moduleA requires moduleB then the corresponding module graph is :

1) module moduleA
2) {
3) requires moduleB;
4) }

moduleA

moduleB

Eg 2: If moduleA requires moduleB and moduleC then the corresponding module graph is:

1) module moduleA
2) {
3) requires moduleB;
4) requires moduleC;
5) }
722

moduleA
Page

CONTACT US: moduleB moduleC


Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Eg 3: If moduleA requires moduleB and moduleB requires moduleC then the corresponding module graph is:

1) module moduleA
2) {
3) requires moduleB;
4) }
5) module moduleB
6) {
7) requires moduleC;
8) }

moduleA

moduleB

moduleC

Eg 4: If moduleA requires moduleB and moduleB requires transitive moduleC then the corresponding module
graph is:

1) module moduleA
2) {
3) requires moduleB;
4) }
5) module moduleB
6) {
7) requires transitive moduleC;
8) }
moduleA

moduleB
723

moduleC
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Eg 5: If moduleA requires moduleB and moduleC, moduleC requires moduleD and transitive moduleE then the
corresponding Modular Graph is:

1) module moduleA
2) {
3) requires moduleB;
4) requires moduleC;
5) }
6) module moduleC
7) {
8) requires moduleD;
9) requires transitive moduleE;
10) }

moduleA

moduleB moduleC

moduleD moduleE

Java 9 JDK itself modularized. All classes of Java SE are divided into several modules.

Eg:
java.base
java.sql
java.xml
java.rmi
etc...
The module graph of JDK is
724
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


In the above diagram all modules requires java.base module either directly or indirectly. Hence this module acts
as BASE module for all java modules.
Observe modular graphs carefully:java.se and java.sql modules etc

Rules of Module Graph:


1. Two modules with the same name is not allowed.
2. Cyclic Dependency is not allowed between the modules and hence Module Graph should not contain cycles.

Observable Modules:
The modules which are observed by JVM at runtime are called Observable modules.

The modules we are specifying with --module-path option with java command are observed by JVM and hence
these are observable modules.

java --module-path out -m moduleA/pack1.Test

The modules present in module-path out are observable modules

JDK itself contains several modules (like java.base, java.sql, java.rmi etc). These modules can be observed
automatically by JVM at runtime and we are not required to use --module-path. Hence these are observable
modules.

Observable Modules = All Predefined JDK Modules + The modules specified with --module-path option

We can list out all Observable Modules by using --list-modules option with java command.
725

Eg1: To print all readymade compiled modules (pre defined modules) present in Java 9
Page

C:\Users\Durga\Desktop>java --list-modules

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


java.activation@9
java.base@9
java.compiler@9
....

Eg2: Assume our own created compiled modules are available in out folder. To list out these modules including
readymade java modules

C:\Users\Durga\Desktop>java --module-path out --list-modules


java.activation@9
java.base@9
...
exportermodule file:///C:/Users/Durga/Desktop/out/exportermodule/
moduleA file:///C:/Users/Durga/Desktop/out/moduleA/

Aggregator Module:
Sometimes a group of modules can be reused by multiple other modules. Then it is not recommended to read
each module individually. We can group those common modules into a single module, and we can read that
module directly. This module which aggregates functionality of several modules into a single module is called
Aggregator module. If any module reads aggregator module then automatically all its modules are by default
available to that module.

Aggregator module won't provide any functionality by its own, just it gathers and bundles together a bunch of
other modules.

aggregatorModule
726

moduleA moduleB moduleC


Page

1) module aggregatorModule

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2) {
3) requires transitive moduleA;
4) requires transitive moduleB;
5) requires transitive moduleC;
6) }

Aggregator Module not required to contain a single java class. Just it "requires transitive" of all common modules.

If any module reads aggregatorModule automatically all 3 modules are by default available to that module also.

1) module useModule
2) {
3) requires aggregatorModule;
4) }

Now useModule can use functionality of all 3 modules moduleA, moduleB and moduleC.

Demo Program for Aggregator Module:

pack1 pack2 pack3


(A.java) (B.java) (C.java)

module-info.java module-info.java module-info.java

moduleA moduleB moduleC

module-info.java
727

aggregatorModule
Page

CONTACT US: packA


Mobile: +91- 8885 25 26 27 (Test.java) Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 module-info.java WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


useModule
moduleA components:
A.java:

1) package pack1;
2) public class A
3) {
4) public void m1()
5) {
6) System.out.println("moduleA method");
7) }
8) }

module-info.java:

1) module moduleA
2) {
3) exports pack1;
4) }

moduleB components:
B.java:

1) package pack2;
2) public class B
3) {
4) public void m1()
5) {
6) System.out.println("moduleB method");
7) }
728

8) }

module-info.java:
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) module moduleB
2) {
3) exports pack2;
4) }

moduleC components:
C.java:

1) package pack3;
2) public class C
3) {
4) public void m1()
5) {
6) System.out.println("moduleC method");
7) }
8) }

module-info.java:

1) module moduleC
2) {
3) exports pack3;
4) }

aggregatorModule components:
module-info.java:

1) module aggregatorModule
2) {
3) requires transitive moduleA;
4) requires transitive moduleB;
729

5) requires transitive moduleC;


6) }
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


useModule components:
Test.java:

1) package packA;
2) import pack1.A;
3) import pack2.B;
4) import pack3.C;
5) public class Test
6) {
7) public static void main(String[] args)
8) {
9) System.out.println("Aggregator Module Demo");
10) A a = new A();
11) a.m1();
12)
13) B b = new B();
14) b.m1();
15)
16) C c = new C();
17) c.m1();
18) }
19) }

module-info.java:

Here we are not required to use requires directive for every module, just we have to use requires only for
aggregatorModule.

1) module useModule
2) {
3) //requires moduleA;
4) //requires moduleB;
5) //requires moduleC;
6) requires aggregatorModule;
7) }

C:\Users\Durga\Desktop>javac --module-source-path src -d out -m


moduleA,moduleB,moduleC,aggregatorModule,useModule
730

C:\Users\Durga\Desktop>java --module-path out -m useModule/packA.Test


Aggregator Module Demo
moduleA method
Page

moduleB method

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


moduleC method

Package Naming Conflicts:


Two jar files can contain a package with same name, which may creates version conflicts and abnormal behavior
of the program at runtime.

But in Java 9 module System, two modules cannot contain a package with same name; otherwise we will get
compile time error. Hence in module system, there is no chance of version conflicts and abnormal behavior of the
program.

Demo Program:

pack1 pack1 packA


(A.java) (B.java) (Test.java)

module-info.java module-info.java module-info.java

moduleA moduleB useModule

moduleA components:
A.java:

1) package pack1;
2) public class A
3) {
4) public void m1()
5) {
6) System.out.println("moduleA method");
7) }
8) }
731

module-info.java:
Page

1) module moduleA

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2) {
3) exports pack1;
4) }

moduleB components:
B.java:

1) package pack1;
2) public class B
3) {
4) public void m1()
5) {
6) System.out.println("moduleB method");
7) }
8) }

module-info.java:

1) module moduleB
2) {
3) exports pack1;
4) }

useModule components:
Test.java:

1) package packA;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) System.out.println("Package Naming Conflicts");
7) }
8) }

module-info.java:
732

1) module useModule {
Page

2) requires moduleA;
3) requires moduleB;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4) }

javac --module-source-path src -d out -m moduleA,moduleB,useModule


error: module useModule reads package pack1 from both moduleA and moduleB

Two modules cannot contain a package with same name.

Module Resolution Process (MRP):


In the case of traditional classpath, JVM won't check the required .class files at the beginning. While executing
program if JVM required any .class file, then only JVM will search in the classpath for the required .class file. If it is
available then it will be loaded and used and if it is not available then at runtime we will get
NoClassDefFoundError,which is not at all recommended.

But in module programming, JVM will search for the 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 its execution. Hence in
modular programming, there is no chance of getting NoClassDefFoundError in the middle of program execution.

Demo Program:

useModule

moduleA

moduleB

moduleC moduleD
733
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Components of useModule:
Test.java:

1) package packA;
2) public class Test
3) {
4) public static void main(String[] args)
5) {
6) System.out.println("Module Resolution Process(MRP) Demo");
7) }
8) }

module-info.java:

1) module useModule
2) {
3) requires moduleA;
4) }

Components of moduleA:
module-info.java:

1) module moduleA
2) {
3) requires moduleB;
4) }

Components of moduleB:
module-info.java:

1) module moduleB
2) {
3) requires moduleC;
4) requires moduleD;
734

5) }

Components of moduleC:
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


module-info.java:

1) module moduleC
2) {
3)
4) }

Components of moduleD:
module-info.java:

1. module moduleD
2. {
3.
4. }

javac --module-source-path src -d out -m moduleA,moduleB,moduleC,moduleD,useModule

java --module-path out --show-module-resolution -m useModule/packA.Test


The module what we are trying to execute will become root module.
Root module should contain the class with main method.

The main advantages of Module Resolution Process at beginning are:


1. We will get error if any dependent module is not available.
2. We will get error if multiple modules with the same name
3. We will get error if any cyclic dependency
4. We will get error if two modules contain packages with the same name.

Note:
The following are restricted keywords in java 9:
module, requires, transitive, exports
In normal Java program no restrictions and we can use for identifier purpose also.

735
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


JLINK (Java Linker)
Until 1.8 version to run a small Java program (like Hello World program) also, we should use a bigger JRE which
contains all java's inbuilt 4300+ classes. It increases the size of Java Runtime environment and Java applications.
Due to this Java is not suitable for IOT devices and Micro Services. (No one invite a bigger Elephant into their small
house).

To overcome this problem, Java people introduced Compact Profiles in Java 8. But they didn't succeed that much.
In Java 9, they introduced a permanent solution to reduce the size of Java Runtime Environment, which is nothing
but JLINK.

JLINK is Java's new command line tool (which is available in JDK_HOME\bin) which allows us to link sets of only
required modules (and their dependencies) to create a runtime image (our own JRE).

Now, our Custom JRE contains only required modules and classes instead of having all 4300+ classes.
It reduces the size of Java Runtime Environment, which makes java best suitable for IOT and micro services.

Hence, Jlink's main intention is to avoid shipping everything and, also, to run on very small devices with little
memory. By using Jlink, we can get our own very small JRE.
Jlink also has a list of plugins (like compress) that will help optimize our solutions.

How to use JLINK: Demo Program


src
|-demoModule
|-module-info.java
|-packA
|-Test.java

module-info.java:

1) module demoModule
2) {
3) }

Test.java:
736

1) package packA;
2) public class Test
Page

3) {

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


4) public static void main(String[] args)
5) {
6) System.out.println("JLINK Demo To create our own customized & small JRE");
7) }
8) }

Compilation:
C:\Users\Durga\Desktop>javac --module-source-path src -d out -m demoModule

Run with default JRE:


C:\Users\Durga\Desktop>java --module-path out -m demoModule/packA.Test

o/p: JLINK Demo To create our own customized & small JRE

Creation of our own JRE only with required modules:


demoModule requires java.base module. Hence add java.base module to out directory
(copy java.base.jmod from jdk-9\jmods to out folder)

out
|-java.base.jmod
|-demoModule
|-module-info.class
|-packA
|-Test.class

Now we can create our own JRE with JLINK command

C:\Users\Durga\Desktop>jlink --module-path out --add-modules demoModule,java.base --output durgajre

737

Now observe the size of durgajre is just 35.9MB which is very small when compared with default JRE size 203MB.
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


We can run our application with our own custom jre (durgajre) as follows

C:\Users\Durga\Desktop\durgajre\bin>java -m demoModule/packA.Test
o/p: JLINK Demo To create our own customized & small JRE

Compressing the size of JRE with compress plugin:


Still we can compress the size of JRE with compress plugin.

738
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


C:\Users\Durga\Desktop>jlink --module-path out --add-modules demoModule,java.base --compress 2 --output
durgajre2

C:\Users\Durga\Desktop\durgajre2\bin>java -m demoModule/packA.Test
o/p: JLINK Demo To create our own customized & small JRE

Providing our own name to the application with launcher plugin:


C:\Users\Durga\Desktop>jlink --module-path out --add-modules demoModule,java.base --launcher
demoapp=demoModule/packA.Test --compress 2 --output durgajre3

Now we can run our application only with the name demoapp
739

C:\Users\Durga\Desktop\durgajre3\bin>demoapp
JLINK Demo To create our own customized & small JRE
Page

If we set the path PATH = C:\Users\Durga\Desktop\durgajre3\bin

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Then we can run our application from anywhere.
D:\>demoapp
E:\>demoapp

Process API Updates (JEP-102)


Unitl java 8, communicating with processor/os/machine is very difficult. We required to write very complex
native code and we have to use 3rd party jar files.

The way of communication with processor is varied from system to system (i.e. os to os). For example, in
windows one way, but in Mac other way. Being a programmer we have to write code based on operating system,
which makes programming very complex.

To resolve this complexity, JDK 9 engineers introduced several enhancements to Process API. By using this
Updated API, we can write java code to communicate with any processor very easily. According to worldwide Java
Developers, Process API Updates is the number 1 feature in Java 9.

With this Enhanced API, we can perform the following activities very easily.

1. Get the Process ID (PID) of running process.


2. Create a new process
3. Destroy already running process
4. Get the process handles for processes
5. Get the parent and child processes of running process
6. Get the process information like owner, children,...
etc...

What's New in Java 9 Process API:


1. Added several new methods (like pid(),info() etc) to Process class.

2. Added several new methods (like startPipeline()) to ProcessBuilder class. We can use ProcessBuilder class to
create operating system processes.

3. Introduced a new powerful interface ProcessHandle. With this interface, we can access current running process,
we can access parent and child processes of a particular process etc

4. Introduced a new interface ProcessHandle.Info, by using this we can get complete information of a particular
740

process.
Page

Note: All these classes and interfaces are part of java.lang package and hence we are not required to use any
import statement.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


How to get ProcessHandle object:
It is the most powerful and useful interface introduced in java 9.
We can get ProcessHandle object as follows

1. ProcessHandle handle=ProcessHandle.current();
Returns the ProcessHandle of current running Process

2. ProcessHandle handle=p.toHandle();
Returns the ProcessHandle of specified Process object.

3. Optional<ProcessHandle> handle=ProcessHandle.of(PID);
Returns the ProcessHandle of proccess with the specified pid.
Here, the return type is Optional, because PID may exist or may not exist.

Use Case-1: To get the process ID (PID) of current process


1) public class Test
2) {
3) public static void main(String[] args) throws Exception
4) {
5) ProcessHandle p=ProcessHandle.current();
6) long pid=p.pid();
7) System.out.println("The PID of current running JVM instance :"+pid);
8) Thread.sleep(100000);
9) }
10) }

We can see this process id in Task Manager (alt+ctrl+delete in windows)

ProcessHandle.Info:
741

We can get complete information of a particular process by using ProcessHandle.Info object.


We can get this Info object as follows.
Page

ProcessHandle p = ProcessHandle.current();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


ProcessHandle.Info info = p.info();
Once we got Info object, we can call the following methods on that object.

1. user():
Return the user of the process.
public Optional<String> user()

2. command():
Returns the command,that can be used to start the process.
public Optional<String> command()
3. startInstant():
Returns the start time of the process.
public Optional<String> startInstant()

4. totalCpuDuration():
Returns the total cputime accumulated of the process.
public Optional<String> totalCpuDuration()

Use Case-2: To get snapshot of the current running process info


1) public class Test
2) {
3) public static void main(String[] args) throws Exception
4) {
5) ProcessHandle p=ProcessHandle.current();
6) ProcessHandle.Info info=p.info();
7) System.out.println("Complete Process Inforamtion:\n"+info);
8) System.out.println("User: "+info.user().get());
9) System.out.println("Command: "+info.command().get());
10) System.out.println("Start Time: "+info.startInstant().get());
11) System.out.println("Total CPU Time Acquired: "+info.totalCpuDuration().get());
12) }
13) }

Use Case-3: To get snapshot of the Particular Process Based on id


1) import java.util.*;
2) public class Test
3) {
742

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


5) {
6) Optional<ProcessHandle> opt=ProcessHandle.of(7532);
Page

7) ProcessHandle p=opt.get();

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


8) ProcessHandle.Info info=p.info();
9) System.out.println("Complete Process Inforamtion:\n"+info);
10) System.out.println("User: "+info.user().get());
11) System.out.println("Command: "+info.command().get());
12) System.out.println("Start Time: "+info.startInstant().get());
13) System.out.println("Total CPU Time Acquired: "+info.totalCpuDuration().get());
14) }
15) }

ProcessBuilder:
We can use ProcessBuilder to create processes.
We can create ProcessBuilder object by using the following constructor.

public ProcessBuilder(String... command)

The argument should be valid command to invoke the process.

Eg:
ProcessBuilder pb = new ProcessBuilder("javac","Test.java");
ProcessBuilder pb = new ProcessBuilder("java","Test");
ProcessBuilder pb = new ProcessBuilder("notepad.exe","D:\\names.txt");

Once we create a ProcessBuilder object,we can start the process by using start() method.

pb.start();

Use Case-4: To create and Start a process by using ProcessBuilder


FrameDemo.java:

1) import java.awt.*;
2) import java.awt.event.*;
3) public class FrameDemo
4) {
5) public static void main(String[] args)
6) {
743

7) Frame f = new Frame();


8) f.addWindowListener( new WindowAdapter()
9) {
Page

10) public void windowClosing(WindowEvent e)

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


11) {
12) System.exit(0);
13) }
14) });
15) f.add(new Label("This Process Started from Java by using ProcessBuilder !!!"));
16) f.setSize(500,500);
17) f.setVisible(true);
18) }
19) }

Test.java

1) public class Test


2) {
3) public static void main(String[] args) throws Exception
4) {
5) ProcessBuilder pb=new ProcessBuilder("java","FrameDemo");
6) pb.start();
7) }
8) }

Use Case-5: To open a file with notepad from java by using ProcessBuilder

1) public class Test


2) {
3) public static void main(String[] args) throws Exception
4) {
5) new ProcessBuilder("notepad.exe","FrameDemo.java").start();
6) }
7) }

Use Case-6: To start and destroy a process from java by using ProcessBuilder

1) class Test
2) {
3) public static void main(String[] args) throws Exception
4) {
5) ProcessBuilder pb=new ProcessBuilder("java","FrameDemo");
744

6) Process p=pb.start();
7) System.out.println("Process Started with id:"+p.pid());
8) Thread.sleep(10000);
Page

9) System.out.println("Destroying the process with id:"+p.pid());

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10) p.destroy();
11) }
12) }

Use Case-7: To destroy a process which is not created from Java


1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args) throws Exception {
5) Optional<ProcessHandle> optph=ProcessHandle.of(5232);
6) ProcessHandle ph=optph.get();
7) ph.destroy();
8) }
9) }

Use Case-8: To display all running process information


1) import java.util.*;
2) import java.util.stream.*;
3) import java.time.*;
4) class Test
5) {
6) public static void dumpProcessInfo(ProcessHandle p)
7) {
8) ProcessHandle.Info info=p.info();
9) System.out.println("Process Id:"+p.pid());
10) System.out.println("User: "+info.user().orElse(""));
11) System.out.println("Command: "+info.command().orElse(""));
12) System.out.println("Start Time: "+info.startInstant().orElse(Instant.now()).toString());
13) System.out.println("Total CPU Time Acquired: "+info.totalCpuDuration().
14) orElse(Duration.ofMillis(0)).toMillis());
15) System.out.println();
16) }
17) public static void main(String[] args) throws Exception
18) {
19) Stream<ProcessHandle> allp=ProcessHandle.allProcesses();
20) allp.limit(100).forEach(ph->dumpProcessInfo(ph));
21) }
745

22) }
Page

Use Case-9: To display all child process information

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


1) import java.util.stream.*;
2) import java.time.*;
3) class Test
4) {
5) public static void dumpProcessInfo(ProcessHandle p) {
6) ProcessHandle.Info info=p.info();
7) System.out.println("Process Id:"+p.pid());
8) System.out.println("User: "+info.user().orElse(""));
9) System.out.println("Command: "+info.command().orElse(""));
10) System.out.println("Start Time: "+info.startInstant().orElse(Instant.now()).toString());
11) System.out.println("Total CPU Time Acquired: "+info.totalCpuDuration()
12) .orElse(Duration.ofMillis(0)).toMillis());
13) System.out.println();
14) }
15) public static void main(String[] args) throws Exception {
16) ProcessHandle handle=ProcessHandle.current();
17) Stream<ProcessHandle> childp=handle.children();
18) childp.forEach(ph->dumpProcessInfo(ph));
19) }
20) }

Note: If Current Process not having any child processes then we won't get any output

Use Case-10: To perform a task at the time of Process Termination


1) import java.util.concurrent.*;
2) public class Test
3) {
4) public static void main(String[] args) throws Exception
5) {
6) ProcessBuilder pb=new ProcessBuilder("java","FrameDemo");
7) Process p=pb.start();
8) System.out.println("Process Started with id:"+p.pid());
9) CompletableFuture<Process> future=p.onExit();
10) future.thenAccept(p1->System.out.println("Process Terminated with Id:"+p1.pid()));
11) System.out.println(future.get());
12) }
13) }
746

Output [In Normal Termination]:

D:\durga_classes>java Test
Page

Process Started with id:4828

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Process[pid=4828, exitValue=0]
Process Terminated with Id:4828

Output [In Abnormal Termination alt+ctrl+delete]:

D:\durga_classes>java Test
Process Started with id:12512
Process[pid=12512, exitValue=1]
Process Terminated with Id:12512

Observe exit value: 0 for normal termination and non-zero for abnormal termination

HTTP/2 Client
What is the purpose of HTTP/2 Client:
HTTP/2 Client is one of the most exciting features, for which developers are waiting for long time.
By using this new HTTP/2 Client, from Java application, we can send HTTP Request and we can process HTTP
Response.

HTTP Request

Java Application
(HTTP/2 Client API)

HTTP Response Web Server

Prior to Java 9, we are using HttpURLConnection class to send HTTP Request and to Process HTTP Response. It is
the legacy class which was introduced as the part of JDK 1.1 (1997).There are several problems with this
HttpURLConnection class.

Problems with Traditional HttpURLConnection class:


747

1. It is very difficult to use.


2. It supports only HTTP/1.1 protocol but not HTTP/2(2015) where
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


A. We can send only one request at a time per TCP Connection, which creates network traffic problems and
performance problems.
B. It supports only Text data but not binary data

3. It works only in Blocking Mode (Synchronous Mode), which creates performance problems.

Because of these problems, slowly developers started using 3rd party Http Clients like Apache Http client and
Google Http client etc.

JDK 9 Engineers addresses these issues and introduced a brand new HTTP/2 Client in Java 9.

Advantages of Java 9 HTTP/2 Client:


1. It is Lightweight and very easy to use.
2. It supports both HTTP/1.1 and HTTP/2.
3. It supports both Text data and Binary Data (Streams)
4. It can work in both Blocking and Non-Blocking Modes (Synchronous Communication and Asynchronous
Communication)
5. It provides better performance and Scalability when compared with traditional HttpURLConnection.
etc...

Important Components of Java 9 HTTP/2 Client:

In Java 9, HTTP/2 Client provided as incubator module.

Module: jdk.incubator.httpclient
Package: jdk.incubator.http

Mainly 3 important classes are available:

1. HttpClient
2. HttpRequest
3. HttpResponse

Note:
748

Incubator module is by default not available to our java application. Hence compulsory we should read explicitly
by using requires directive.
Page

1) module demoModule

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


2) {
3) requires jdk.incubator.httpclient;
4) }

Steps to send Http Request and process Http Response from Java Application:
1. Create HttpClient Object
2. Create HttpRequest object
3. Send HttpRequest by using HttpClient and Get the HttpResponse
4. Process HttpResponse

1. Creation of HttpClient object:


We can use HttpClient object to send HttpRequest to the web server. We can create HttpClient object by using
factory method: newHttpClient()

HttpClient client = HttpClient.newHttpClient();


2. Creation of HttpRequest object:
We can create HttpRequest object as follows:

String url="http://www.durgasoft.com";
HttpRequest req=HttpRequest.newBuilder(new URI(url)).GET().build();

Note:
newBuilder() method returns Builder object.
GET() method sets the request method of this builder to GET.
build() method builds and returns a HttpRequest.
public static HttpRequest.Builder newBuilder(URI uri)
public static HttpRequest.Builder GET()
public abstract HttpRequest build()

3.Send HttpRequest by using HttpClient and Get the HttpResponse:


HttpClient contains the following methods:
1. send() to send synchronous request(blocking mode)
2. sendAsync() to send Asynchronous Request(Non Blocking Mode)

Eg:
HttpResponse resp=client.send(req,HttpResponse.BodyHandler.asString());
749

HttpResponse resp=client.send(req,HttpResponse.BodyHandler.asFile(Paths.get("abc.txt")));

Note:
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


BodyHandler is a functional interface present inside HttpResponse. It can be used to handle body of
HttpResponse.

4. Process HttpResponse:
HttpResponse contains the status code, response headers and body.

Status Line
Response Headers
Response Body
Structure of HTTP Response

HttpResponse class contains the following methods retrieve data from the response

1. statusCode()
Returns status code of the response
It may be (1XX,2XX,3XX,4XX,5XX)

2. body()
Returns body of the response
3. headers()
Returns header information of the response

Eg:
System.out.println("Status Code:"+resp.statusCode());
System.out.println("Body:"+resp.body());
System.out.println("Response Headers Info");
HttpHeaders header=resp.headers();
Map<String,List<String>> map=header.map();
map.forEach((k,v)->System.out.println("\t"+k+":"+v));

Demo Program to send GET Request in Blocking Mode:

demoModule

packA

Test.java
750

module-info.java
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


module-info.java:

1) module demoModule
2) {
3) requires jdk.incubator.httpclient;
4) }

Test.java:

1) package packA;
2) import jdk.incubator.http.HttpClient;
3) import jdk.incubator.http.HttpRequest;
4) import jdk.incubator.http.HttpResponse;
5) import jdk.incubator.http.HttpHeaders;
6) import java.net.URI;
7) import java.util.Map;
8) import java.util.List;
9) public class Test
10) {
11) public static void main(String[] args) throws Exception
12) {
13) String url="https://www.redbus.in/info/aboutus";
14) sendGetSyncRequest(url);
15) }
16) public static void sendGetSyncRequest(String url) throws Exception
17) {
18) HttpClient client=HttpClient.newHttpClient();
19) HttpRequest req=HttpRequest.newBuilder(new URI(url)).GET().build();
20) HttpResponse resp=client.send(req,HttpResponse.BodyHandler.asString());
21) processResponse(resp);
22) }
23) public static void processResponse(HttpResponse resp)
24) {
25) System.out.println("Status Code:"+resp.statusCode());
26) System.out.println("Response Body:"+resp.body());
27) HttpHeaders header=resp.headers();
28) Map<String,List<String>> map=header.map();
29) System.out.println("Response Headers");
30) map.forEach((k,v)->System.out.println("\t"+k+":"+v));
31) }
751

32) }
Page

Note:

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


Writing Http Response body to file abc.html:
HttpResponse resp = client.send(req,HttpResponse.BodyHandler.asFile(Paths.get("abc.html")));

Paths is a class present in java.nio.file package and hence we should write import as
import java.nio.file.Paths;

In this case, abc.html file will be created in the current working directory which contains total response body.

Demo Program:

demoModule

packA

Test.java

module-info.java

module-info.java:

1) module demoModule
2) {
3) requires jdk.incubator.httpclient;
4) }

Test.java:

1) package packA;
2) import jdk.incubator.http.HttpClient;
3) import jdk.incubator.http.HttpRequest;
4) import jdk.incubator.http.HttpResponse;
5) import jdk.incubator.http.HttpHeaders;
752

6) import java.net.URI;
7) import java.util.Map;
8) import java.util.List;
Page

9) import java.nio.file.Paths;

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


10) public class Test
11) {
12) public static void main(String[] args) throws Exception
13) {
14) String url="https://www.redbus.in/info/aboutus";
15) sendGetSyncRequest(url);
16) }
17) public static void sendGetSyncRequest(String url) throws Exception
18) {
19) HttpClient client=HttpClient.newHttpClient();
20) HttpRequest req=HttpRequest.newBuilder(new URI(url)).GET().build();
21) HttpResponse resp=client.send(req,HttpResponse.BodyHandler.asFile(Paths.get("abc.ht
ml")));
22) processResponse(resp);
23) }
24) public static void processResponse(HttpResponse resp)
25) {
26) System.out.println("Status Code:"+resp.statusCode());
27) //System.out.println("Response Body:"+resp.body());
28) HttpHeaders header=resp.headers();
29) Map<String,List<String>> map=header.map();
30) System.out.println("Response Headers");
31) map.forEach((k,v)->System.out.println("\t"+k+":"+v));
32) }
33) }

abc.html will be created in the current working directory. Open that file to see body of response.

Asynchronous Communication:
In Blocking Mode (Synchronous Mode), Once we send Http Request, we should wait until getting response. It
creates performance problems.

But in Non-Blocking Mode (Asynchronous Mode), we are not required to wait until getting the response. We can
continue our execution and later point of time we can use that HttpResponse once it is ready, so that
performance of the system will be improved.
753

HttpClient class contains sendAync() method to send asynchronous request.

CompletableFuture<HttpResponse<String>> cf = client.sendAsync(req,HttpResponse.BodyHandler.asString());
Page

CompletableFuture Object can be used to hold HttpResponse in aynchronous communication.

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


This class present in java.util.concurrent package.This class contains isDone() method to check whether processing
completed or not.

public boolean isDone()

Demo Program For Asynchronous Communication:

demoModule

packA

Test.java

module-info.java

module-info.java:

1) module demoModule
2) {
3) requires jdk.incubator.httpclient;
4) }

Test.java:

1) package packA;
2) import jdk.incubator.http.HttpClient;
3) import jdk.incubator.http.HttpRequest;
4) import jdk.incubator.http.HttpResponse;
5) import jdk.incubator.http.HttpHeaders;
6) import java.net.URI;
7) import java.util.Map;
8) import java.util.List;
9) import java.util.concurrent.CompletableFuture;
10) public class Test
11) {
12) public static void main(String[] args) throws Exception
754

13) {
14) String url="https://www.redbus.in/info/aboutus";
Page

15) sendGetAsyncRequest(url);
16) }

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.


17) public static void sendGetAsyncRequest(String url) throws Exception
18) {
19) HttpClient client=HttpClient.newHttpClient();
20) HttpRequest req=HttpRequest.newBuilder(new URI(url)).GET().build();
21) System.out.println("Sending Asynchronous Request...");
22) CompletableFuture<HttpResponse<String>> cf = client.sendAsync(req,HttpResponse.Bo
dyHandler.asString());
23) int count=0;
24) while(!cf.isDone())
25) {
26) System.out.println("Processing not done and doing other activity:"+ ++count);
27) }
28) processResponse(cf.get());
29) }
30) public static void processResponse(HttpResponse resp)
31) {
32) System.out.println("Status Code:"+resp.statusCode());
33) //System.out.println("Response Body:"+resp.body());
34) HttpHeaders header=resp.headers();
35) Map<String,List<String>> map=header.map();
36) System.out.println("Response Headers");
37) map.forEach((k,v)->System.out.println("\t"+k+":"+v));
38) }
39) }

755
Page

CONTACT US:
Mobile: +91- 8885 25 26 27 Mail ID: durgasoftonlinetraining@gmail.com
+91- 7207 21 24 27/28 WEBSITE: www.durgasoftonline.com

FLAT NO: 202, HMDA MYTRIVANUM, AMEERPET, HYDERABAD.

You might also like