0% found this document useful (0 votes)
27 views132 pages

Java Programming: Automobile Class Instructions

Uploaded by

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

Java Programming: Automobile Class Instructions

Uploaded by

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

PART 3

JAVA
PROGRAMMING

ALL RIGHTS RESERVED TO SVTI


Contents
INTRODUCTION TO JAVA ........................................................................................................................................... 5
Java..................................................................................................................................................................... 5
How to Get Java ................................................................................................................................................. 5
A First Java Program........................................................................................................................................... 5
Compilation Flow: .............................................................................................................................................. 7
JSDK Directory Structure .................................................................................................................................... 8
Eclipse ...................................................................................................................................................................... 10
Introduction to Eclipse ..................................................................................................................................... 10
Downloading Eclipse ........................................................................................................................................ 10
Installing Eclipse ............................................................................................................................................... 10
Running Eclipse for the First Time ................................................................................................................... 11
Editors, Views, and Perspectives ..................................................................................................................... 12
Setting , Creating , Running , Debugging and Import existing Java Project. .................................................... 12
Java Language Fundamentals .................................................................................................................................. 20
A JAVA PROGRAM ............................................................................................................................................ 20
IF-STATEMENT IN JAVA .................................................................................................................................... 20
Java Switch Statement ..................................................................................................................................... 21
Loops in Java .................................................................................................................................................... 23
Java Primitive Data Types ................................................................................................................................ 27
Java Variables ................................................................................................................................................... 27
Java Expressions ............................................................................................................................................... 29
Java String ........................................................................................................................................................ 29
Java Arrays ....................................................................................................................................................... 30
Enhanced for Loop(for-each loop) ................................................................................................................... 33
Objects and Classes in Java .............................................................................................................................. 33
Class in Java ...................................................................................................................................................... 34
Create an Object .............................................................................................................................................. 35
Instance Data and Class Data ........................................................................................................................... 35
Method in Java ................................................................................................................................................. 36
Constructors in Java ......................................................................................................................................... 38
Access Modifiers in Java................................................................................................................................... 40
Encapsulation in Java ....................................................................................................................................... 41
Java Objects ............................................................................................................................................................. 43
Printing consoles .............................................................................................................................................. 43
Difference between StringBuffer and StringBuilder ........................................................................................ 43
Methods and Messages ................................................................................................................................... 45
Java toString() method ..................................................................................................................................... 45

ALL RIGHTS RESERVED TO SVTI 1


Parameter Passing............................................................................................................................................ 46
Java Compare and Identity Objects ................................................................................................................. 47
Destroy Object ................................................................................................................................................. 48
Wrapper classes in Java ................................................................................................................................... 49
Java Enums ....................................................................................................................................................... 50
Inheritance in Java ................................................................................................................................................... 51
Inheritance ....................................................................................................................................................... 51
Inheritance in Java ........................................................................................................................................... 51
Java Type Casting ............................................................................................................................................. 53
Overriding and Overloading in Java ................................................................................................................. 54
Polymorphism in Java ...................................................................................................................................... 55
Super Keyword in Java ..................................................................................................................................... 56
Object class in Java........................................................................................................................................... 57
Advanced Inheritance and Generics ........................................................................................................................ 58
Abstract Classes ............................................................................................................................................... 58
Interfaces ......................................................................................................................................................... 59
Collections in Java ............................................................................................................................................ 60
Generics in Java ................................................................................................................................................ 61
Comparable in Java .......................................................................................................................................... 62
Packages ................................................................................................................................................................... 63
Introduction to Packages ................................................................................................................................. 63
Import a Class................................................................................................................................................... 63
Exception Handling .................................................................................................................................................. 65
Exceptions Overview ........................................................................................................................................ 65
Exception Hierarchy ......................................................................................................................................... 66
Exceptions Methods......................................................................................................................................... 66
Catching Exceptions ......................................................................................................................................... 67
The Finally Block............................................................................................................................................... 68
The Throws/Throw Keywords .......................................................................................................................... 69
Input/output Streams .............................................................................................................................................. 70
Overview of Streams ........................................................................................................................................ 70
Bytes vs. Characters ......................................................................................................................................... 70
When to use Character Stream over Byte Stream? ......................................................................................... 72
When to use Byte Stream over Character Stream? ........................................................................................ 72
Convert Byte stream into Character stream .................................................................................................... 72
File Object in Java............................................................................................................................................. 73
Binary Input/Output Streams .......................................................................................................................... 75
Java PrintWriter Class ...................................................................................................................................... 76

ALL RIGHTS RESERVED TO SVTI 2


Writing and Reading objects in Java ................................................................................................................ 78
Closing Streams ................................................................................................................................................ 80
Core Collections Framework .................................................................................................................................... 82
Set in Java......................................................................................................................................................... 82
Java List ............................................................................................................................................................ 85
Java Queue Interface ....................................................................................................................................... 86
Java Map Interface ........................................................................................................................................... 87
Sorting in Collection ......................................................................................................................................... 89
Difference between Comparable and Comparator ......................................................................................... 90
Java List sort() Method..................................................................................................................................... 93
Sort an Array in Java......................................................................................................................................... 94
Java Collections class/Methods ....................................................................................................................... 97
Java ArrayList ................................................................................................................................................... 98
Java HashMap .................................................................................................................................................. 99
Java HashSet .................................................................................................................................................. 100
JAVA EE OVERVIEW ................................................................................................................................................ 102
Introduction ................................................................................................................................................... 102
Setting up Java EE .......................................................................................................................................... 102
Java SE ............................................................................................................................................................ 102
Web Application and Services........................................................................................................................ 104
Enterprise JavaBeans ..................................................................................................................................... 105
Additional J2EE ............................................................................................................................................... 105
POJO ............................................................................................................................................................... 106
Dependency Injection .................................................................................................................................... 107
JAVA ANNOTATIONS ...................................................................................................................................... 108
Java EE ............................................................................................................................................................ 108
JDBC ....................................................................................................................................................................... 111
Introduction ................................................................................................................................................... 111
JDBC Architecture .......................................................................................................................................... 111
JDBC Driver..................................................................................................................................................... 111
Java Database Connectivity with MySQL ....................................................................................................... 114
JDBC Resources .............................................................................................................................................. 118
JDBC Exception handling ................................................................................................................................ 118
Performing Basic CRUD Operations Using JDBC .................................................................................................... 121
Executing Static SQL Statements ................................................................................................................... 121
Iterating Through Result Sets......................................................................................................................... 121
Understanding Scrollable Result Sets ............................................................................................................ 123
Prepared Statement ....................................................................................................................................... 128

ALL RIGHTS RESERVED TO SVTI 3


Retrieving Data Using Prepared Statement ................................................................................................... 128
JDBC Execute INSERT Statement Example ..................................................................................................... 129
JDBC Executing UPDATE Statement Example ................................................................................................ 130
JDBC Execute DELETE/Remove Statement Example ...................................................................................... 130

ALL RIGHTS RESERVED TO SVTI 4


CHAPTER 01

INTRODUCTION TO JAVA
Java
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle)
in the year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the Oak name to Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.

Java Example
Let's have a quick look at Java programming example. A detailed description of Hello Java example is
available in next page.

class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Output: Hello Java

How to Get Java


1. Open Internet Explorer icon and go to [Link].
2. Select the Free Java Download button, and then select Agree and Start Free Download. If you're
prompted for an administrator password or confirmation, type the password or provide confirmation.
3. On the notification bar, select Run. If you're prompted for an administrator password or confirmation,
type the password or provide confirmation.
4. Select Install > Close.
5. If you're having problems installing or using Java, look for answers in the Java Help Center.
6. Note: For PCs running Windows 8.1, Java will only work in Internet Explorer for the desktop.

A First Java Program


First Java Program | Hello World Example
In this page, we will learn how to write the simple program of java. We can write a simple hello java
program easily after installing the JDK and Set path must.

How to set path in Java


The path is required to be set for using tools such as javac, java, etc.
If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set because
all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK.
ALL RIGHTS RESERVED TO SVTI 5
There are two ways to set the path in Java:
1. Temporary
2. Permanent

1) How to set the Temporary Path of JDK in Windows


To set the temporary path of JDK, you need to follow the following steps:
Open the command prompt
Copy the path of the JDK/bin directory
Write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Let's see it in the figure given below:
HTML Tutorial

2) How to set Permanent Path of JDK in Windows


For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable ->
write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

For Example:
1) Go to MyComputer properties
2) Click on the advanced tab
3) Click on environment variables
4) Click on the new tab of user variables
5) Write the path in the variable name
6) Copy the path of bin folder
7) Paste path of bin folder in the variable value
8) Click on ok button
9) Click on ok button

ALL RIGHTS RESERVED TO SVTI 6


Now your permanent path is set. Now create a program.

Creating Hello World Example


Let's create the hello java program:
class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Test it Now
save this file as [Link]
To compile: javac [Link]
To execute: java Simple

Output:Hello Java

Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code into byte code.
SQL CREATE TABLE

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[], [Link]().

 class keyword is used to declare a class in java.

 public keyword is an access modifier which represents visibility. It means it is visible to all.

 static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.

 void is the return type of the method. It means it doesn't return any value.

 main represents the starting point of the program.

 String[] args is used for command line argument. We will learn it later.

ALL RIGHTS RESERVED TO SVTI 7


 [Link]() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal
working of [Link] statement later.

To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories
-> notepad and write a simple program as displayed below:

As displayed in the above diagram, write the simple program of java in notepad and saved it as
[Link]. To compile and run this program, you need to open the command prompt by start menu -
> All Programs -> Accessories -> command prompt.

To compile and run the above program, go to your current directory first; my current directory is c:\new.
Write here:
To compile: javac [Link]
To execute: java Simple

JSDK Directory Structure


The Basic Directory structure of Java Described below.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode. JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other. However, Java is
platform independent. There are three notions of the JVM: specification, implementation, and instance.

The JVM performs the following main tasks:


ALL RIGHTS RESERVED TO SVTI 8
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries
+ other files that JVM uses at runtime.
Prime Ministers of India | List of Prime Minister of India (1947-2020)
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
 Standard Edition Java Platform
 Enterprise Edition Java Platform
 Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc.
to complete the development of a Java Application.

ALL RIGHTS RESERVED TO SVTI 9


CHAPTER 02

ECLIPSE
Introduction to Eclipse
Eclipse is an integrated development environment (IDE) for Java and other programming languages like
C, C++, PHP, and Ruby etc. Development environment provided by Eclipse includes the Eclipse Java
development tools (JDT) for Java, Eclipse CDT for C/C++, and Eclipse PDT for PHP, among others. The
Eclipse platform which provides the foundation for the Eclipse IDE is composed of plug-ins and is
designed to be extensible using additional plug-ins. Developed using Java, the Eclipse platform can be
used to develop rich client applications, integrated development environments and other tools. Eclipse can
be used as an IDE for any programming language for which a plug-in is available.

Downloading Eclipse
You can download eclipse from [Link] The download page lists a number
of flavors of eclipse.

The capabilities of each packaging of eclipse are different. Java developers typically use Eclipse Classic
or Eclipse IDE for developing Java applications.
The drop down box in the right corner of the download page allows you to set the operating system on
which eclipse is to be installed. You can choose between Windows, Linux and Mac. Eclipse is packaged
as a zip file.
Installing Eclipse
To install on windows, you need a tool that can extract the contents of a zip file. For example you can use
7-zip
PeaZip
IZArc
Using any one of these tools, extract the contents of the eclipse zip file to any folder of your choice.

ALL RIGHTS RESERVED TO SVTI 10


Launching Eclipse
On the windows platform, if you extracted the contents of the zip file to c:\, then you can start eclipse by
using c:\eclipse\[Link]
When eclipse starts up for the first time it prompts you for the location of the workspace folder. All your
data will be stored in the workspace folder. You can accept the default or choose a new location.

If you select "Use this as the default and do not ask again", this dialog box will not come up again.

Running Eclipse for the First Time


Using the New Java Project wizard
The New Java Project Wizard has two pages. On the first page −
 Enter the Project Name.
 Select the Java Runtime Environment (JRE) or leave it at the default.
 Select the Project Layout which determines whether there would be a separate folder for the source
codes and class files. The recommended option is to create separate folders for sources and class files.

You can click on the Finish button to create the project or click on the Next button to change the java build
settings.

ALL RIGHTS RESERVED TO SVTI 11


On the second page you can change the Java Build Settings like setting the Project dependency (if there
are multiple projects) and adding additional jar files to the build path.
Editors, Views, and Perspectives
To use Eclipse, you need to know what view, editor, and perspective mean:
View
This is a window that gives you a graphical display of your data, whether that data is text, bulleted lists, a
GUI, images, and so on.

Editor
An editor is much like a view, except that the data in it is editable. When you’re working on your code,
you edit it in an editor, which is usually the central window displayed in the workbench.

Perspective
A perspective is a well-defined collection of views and editors. When you open a perspective, its views
and/or editors appear in the workbench.
Views display data but don’t let you edit it , editors both display data and make it editable. Because screen
space is always at a premium in GUIs, views are often stacked one on top of another. You select the one
you want to see using tabs that appear on the edge of the stacked views.

Setting , Creating , Running , Debugging and Import existing Java Project.


#1) Click on File -> New -> Java project.

ALL RIGHTS RESERVED TO SVTI 12


#2) The following window will open:

Give a name to your project in the highlighted text field. While creating a formal project the name should
have a logical sense, however as we are in the learning process, for now, you can name your project as
“MyFirstProject” and leave the rest of the fields as default and click next.

#3) The following screen opens up:

ALL RIGHTS RESERVED TO SVTI 13


Leave all the options as it is and click on finish.

You will see the following structure created in your project explorer.

Here you can see two sub-items under your project name. The JRE system library is the default Java
library that Eclipse adds to your project. This library provides Java support and without this, you cannot
proceed with creating a Java project. The other folder is the “src” folder or the source folder. Your project
structure will get created inside this.

#4) You now have your base project structure, let’s add more to this. In Java, we have packages and
classes. Packages provide logical separation for classes. Packages are just folders, whereas classes are
where you write your actual code.

To create a package right-click on your project name as shown below.

ALL RIGHTS RESERVED TO SVTI 14


Click on the package:

Java says package names should be in a small case, so give any name such as “myfirstpackage” and click
on finish.
Check your Project Structure.

#5) Next, you need to create a class, and this is where your actual code will go. Right-click on the package
name as shown below.

ALL RIGHTS RESERVED TO SVTI 15


Click on the class:

Give a name to your class and keep the modifier selected as public. While creating a simple Java project,
ensure to check the checkbox for creating the method “public static void main(String[] args)”.

Click on finish, and now your project will look as shown below.

You can see that the class is created and as we selected the main method to be added, the method signature
is added to the class. Similar to a class you can also create an interface by following the same steps and
by selecting “New Interface”.
#6) As we have successfully created a project and class, let’s put a simple print statement in it and run the
same to check the output.

ALL RIGHTS RESERVED TO SVTI 16


Write the below code and save:

Code:
Code generated:
package myfirstpackage;
public class MyFirstClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
[Link]("This is my first code");
}
}
Once you have saved the file there are multiple places from where you can run it as a Java application.
a) Keep your cursor on the class that you want to run and click on this icon:
b) Right-click on the class name in the project explorer and select Run as and click as shown below.

c) Select the class name in the project explorer and then select the Run option from the top menu ->

Select Run As and then click on Java application.

#7) As soon as you run your class from any of the above places, a console window opens up in the bottom
pane of your workbench and displays the output of your program.

ALL RIGHTS RESERVED TO SVTI 17


The cnsole in Eclipse displays the runtime logs while your application is running. In a simple application
like ours, it is simply the output of the print statement, however, in complex projects, there may be a lot
more information displayed. The console also displays error information if your program encounters any
exceptions while running. So in this section, we have created a simple project and seen how we can run it
and see the output generated by your code. Apart from classes, there are many other types of files that you
can create in Eclipse which can be used in a Java project such as XML files, interfaces, or even simple
files. You can explore the types of files or types of projects that you can create by clicking on File-> New-
> Others, and the following wizard will open up.

However, as a beginner, you may leave these for a while and work with the simple Java project by adding
more packages and classes as you need.

Build Your Java Project


A Java builder is the tool that will compile your code and create class files for your classes.
Usually, in Eclipse IDE, the default setting is to have your code build automatically.

ALL RIGHTS RESERVED TO SVTI 18


However, if you want to build manually, you can uncheck this option and then the Build Project option
will be enabled for you. You can also control the build configuration for your project and add or remove
builders by doing a right-click on the project name in the project explorer and open properties.

 You can add or remove builders from the above section.


 However, as a beginner, you may leave these for a while and work with the simple Java project by
adding more packages and classes as you need.
 Close and Reopen Your Java Project
 If you are done working on your project, then it is always a good option to close the project. A closed
project will still be available for you in the project explorer section. However, it will not be available
in the editor section.
 To close a project, simply click on the closed sign on all the open files of that project. To reopen any
file, simply navigate to that file from the project explorer and double click on the file name.

ALL RIGHTS RESERVED TO SVTI 19


CHAPTER 03

JAVA LANGUAGE FUNDAMENTALS


A JAVA PROGRAM
Creating Hello World Example
Let's create the hello java program:
class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Save the above file as [Link].
To compile: javac [Link]
To execute: java Simple

Output:
Hello Java

IF-STATEMENT IN JAVA
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}

Example:Exception Handling in Java - Javatpoint


//Java Program to demonstate the use of if statement.

ALL RIGHTS RESERVED TO SVTI 20


public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
[Link]("Age is greater than 18");
}
}
}

Output:
Age is greater than 18

Java Switch Statement


The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.

Points to Remember
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only. The case value must be literal or constant. It
doesn't allow variables.
The case values must be unique. In case of duplicate value, it renders compile-time error.
The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
Each case statement can have a break statement which is optional. When control reaches to the break
statement, it jumps the control after the switch expression. If a break statement is not found, it executes
the next case.
The case value can have a default label which is optional.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

ALL RIGHTS RESERVED TO SVTI 21


Example:
Difference between JDK, JRE, and JVM
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
//Default case statement
default:[Link]("Not in 10, 20 or 30");
}
}
}
Output: 20

ALL RIGHTS RESERVED TO SVTI 22


Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in Java.
1. for loop
2. while loop
3. do-while loop

For Loop
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
Hello Java Program for Beginners
 Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
 Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is
an optional condition.
 Statement: The statement of the loop is executed each time until the second condition is false.
 Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Flowchart:

ALL RIGHTS RESERVED TO SVTI 23


Example:
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
[Link](i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

ALL RIGHTS RESERVED TO SVTI 24


2. Java While Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}

Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}

Output:
SQL CREATE TABLE
1
2
3
4
5
6
7
8
9
10

ALL RIGHTS RESERVED TO SVTI 25


3. Java do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);

Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=10);
}
}
Output:
1
2
3
4
5
6
7
8
9
10

ALL RIGHTS RESERVED TO SVTI 26


Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before its use.
That is why we need to declare variable's type and name.

Data Type Default Value Default size

Boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Example:
int a = 100, int b = -200;
char c =’s’; char a=’z’;
float f=2.5;

Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is assigned
with a data type. Variable is a name of memory location. There are three types of variables in java: local,
instance and static. There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.

int data=50;//Here data is variable


ALL RIGHTS RESERVED TO SVTI 27
Types of Variables
There are three types of variables in Java:
1. Local variable
2. Instance variable
3. Static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
SQL CREATE TABLE
A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It
is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.

Example to understand the types of variables in java


public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
} }//end of class

Java Variable Example: Add Two Numbers


public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
} }
Output:
20

ALL RIGHTS RESERVED TO SVTI 28


Java Expressions
A Java expression consists of variables, operators, literals, and method calls. To know more about method
calls, visit Java methods. For example,
int score;
score = 90;
Here, score = 90 is an expression that returns an int. Consider another example,
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
Here, a + b - 3.4 is an expression.
if (number1 == number2)
[Link]("Number 1 is larger than number 2");
Here, number1 == number2 is an expression that returns a boolean value. Similarly, "Number 1 is larger
than number 2" is a string expression.

Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The [Link] class implements Serializable, Comparable and CharSequence interfaces.
Features of Java - Javatpoint

Java String Example

[Link]

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}}
Output:
java
strings.
example

ALL RIGHTS RESERVED TO SVTI 29


Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in
an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages
 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.
 Disadvantages
 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java


There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array

1. Single Dimensional Array in Java


Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
ALL RIGHTS RESERVED TO SVTI 30
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

Output:
10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Output:
33
3
4
5

2. Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

ALL RIGHTS RESERVED TO SVTI 31


Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}

Output:
123
245
445

ALL RIGHTS RESERVED TO SVTI 32


Enhanced for Loop(for-each loop)
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It
is also known as the enhanced for loop.

for-each Loop Sytnax


The syntax of the Java for-each loop is:
for(dataType item : array) {
...
}
Here,
array - an array or a collection
item - each item of array/collection is assigned to this variable
dataType - the data type of the array/collection\

Example 1: Print Array Elements


// print array elements

class Main {
public static void main(String[] args) {

// create an array
int[] numbers = {3, 9, 5, -5};

// for each loop


for (int number: numbers) {
[Link](number);
}
}
}
Output
3
9
5
-5
Here, we have used the for-each loop to print each element of the numbers array one by one.
In the first iteration, item will be 3.
In the second iteration, item will be 9.
In the third iteration, item will be 5.
In the fourth iteration, item will be -5.

Objects and Classes in Java


In this page, we will learn about Java objects and classes. In object-oriented programming technique, we
design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

ALL RIGHTS RESERVED TO SVTI 33


What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It
can be physical or logical (tangible and intangible). The example of an intangible object is the banking
system.
An object has three characteristics:
 State: represents the data (value) of an object.
 Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user. However, it is used internally by the JVM to identify each object uniquely.

Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so
writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are created. So,
an object is the instance(result) of a class.

Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.

Class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface

ALL RIGHTS RESERVED TO SVTI 34


Syntax to declare a class:
class <class_name>{
field;
method;
}

Create a Class
To create a class, use the keyword class:
[Link]
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}
Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and
that the name of the java file should match the class name.

Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now we can
use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:

Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
[Link](myObj.x);
}
}

Instance Data and Class Data


Class variables only have one copy that is shared by all the different objects of a class, whereas every
object has its own personal copy of an instance variable. So, instance variables across different objects
can have different values whereas class variables across different objects can have only one value.
Instance variable can't be marked as static

Example for instance variable

class A
{
int count;
}

ALL RIGHTS RESERVED TO SVTI 35


where as class variable as marked as Static

example for class variable

class A
{
static int count;
}

SO Class variables are simply static variables.

Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It provides the reusability of code. We can also easily modify
code using methods. In this section, we will learn what is a method in Java, types of methods, method
declaration, and how to call a method in Java.

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use it
many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.

The most important method in Java is the main() method. If you want to read more about the main()
method, go through the link [Link]
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type,
name, and arguments. It has six components that are known as method header, as we have shown in the
following figure.
C++ vs Java

ALL RIGHTS RESERVED TO SVTI 36


Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in which it
is defined.
Protected: When we use protected access specifier, the method is accessible within the same package or
subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.

Types of Method
There are two types of methods in Java:
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can
directly use these methods just by calling them in the program at any point. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background that is already
stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the [Link] class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Let's see an example of the predefined method.
[Link]
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
}
}

Output: The maximum number is: 9

ALL RIGHTS RESERVED TO SVTI 37


2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.

How to Create a User-defined Method


Let's create a user defined method that checks the number is even or odd. First, we will define the method.
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
We have defined the above method named findevenodd(). It has a parameter num of type int. The method
does not return any value that's why we have used void. The method body contains the steps to check the
number is even or odd. If the number is even, it prints the number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method


Once we have defined a method, it should be called. The calling of a method in a program is simple. When
we call or invoke a user-defined method, the program control transfer to the called method.
import [Link];
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num);
}
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer
to the method and gives the output accordingly.

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.

ALL RIGHTS RESERVED TO SVTI 38


It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if your
class doesn't have any.

Rules for creating Java constructor


There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In
other words, we can have private, protected, public or default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor

1. Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){[Link]("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:
Bike is created

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.
ALL RIGHTS RESERVED TO SVTI 39
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We can have
any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}

Output:
111 Karan
222 Aryan

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier
on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.

ALL RIGHTS RESERVED TO SVTI 40


3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the class private. Now
we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.


It provides you the control over the data. Suppose you want to set the value of id which should be greater
than 100 only, you can write the logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through
the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
Create an encapsulated class in Java.

Simple Example of Encapsulation in Java


Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
File: [Link]
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package [Link];

ALL RIGHTS RESERVED TO SVTI 41


public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
[Link]=name
}
}
File: [Link]
//A Java class to test the encapsulated class.
package [Link];
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
[Link]("vijay");
//getting value of the name member
[Link]([Link]());
}
}
Compile By: javac -d . [Link]
Run By: java [Link]

Output:
vijay

ALL RIGHTS RESERVED TO SVTI 42


CHAPTER 04

JAVA OBJECTS
Printing consoles

print(): print() method in Java is used to display a text on the console. This text is passed as the
parameter to this method in the form of String. This method prints the text on the console and the cursor
remains at the end of the text at the console.

println(): println() method in Java is also used to display a text on the console. This text is passed as
the parameter to this method in the form of String. This method prints the text on the console and the
cursor remains at the start of the next line at the console.

Example:
import [Link].*;

class GFG {
public static void main(String[] args)
{

//print example
[Link]("Here Text will Printed");

//println exaple
[Link]("This Text also printed ln used for new line ");
} }

Formatting output using [Link]().

This is the easiest of all methods as this is similar to printf in C. Note that [Link]() and
[Link]() take a single argument, but printf() may take multiple arguments.

Difference between StringBuffer and StringBuilder


Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder.
The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There
are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since
JDK 1.5.

A list of differences between StringBuffer and StringBuilder are given below:

ALL RIGHTS RESERVED TO SVTI 43


No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not


It means two threads can't call the methods of thread safe. It means two threads can call the
StringBuffer simultaneously. methods of StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

StringBuffer Example
//Java Program to demonstrate the use of StringBuffer class.

public class BufferTest{


public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
[Link]("java");
[Link](buffer);
}
}

hellojava
StringBuilder Example
//Java Program to demonstrate the use of StringBuilder class.

public class BuilderTest{


public static void main(String[] args){
ALL RIGHTS RESERVED TO SVTI 44
StringBuilder builder=new StringBuilder("hello");
[Link]("java");
[Link](builder);
}
}
hellojava

Methods and Messages


Method is just the fancy name given to a function that is bound (associated) to an object.
A message is what you send, asking for something to be done by the object you’ve sent the message to. A
method is the code that actually gets run by that receiving object, after the system has looked up the match
between the receiver and the message.
Sending a message to an object instance is just a fancy way of saying you are calling or invoking a method
(function).
The reason why it is sometimes called a message send, rather than a method call, is to highlight that there
is a mechanism provided by the language runtime that sits between the sender and the receiver object that
determines which actual method gets invoked. As it happens at runtime it is called dynamic or late binding.

Java toString() method


If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding
the toString() method, returns the desired output, it can be the state of an object etc. depends on your
implementation.

Advantage of Java toString() method


By overriding the toString() method of the Object class, we can return values of the object, so we don't
need to write much code.

Example of Java toString() method


Now let's see the real example of toString() method.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
[Link]=rollno;
[Link]=name;
[Link]=city;
}

public String toString(){//overriding the toString() method


return rollno+" "+name+" "+city;
}

ALL RIGHTS RESERVED TO SVTI 45


public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

[Link](s1);//compiler writes here [Link]()


[Link](s2);//compiler writes here [Link]()
} }

Output: 101 Raj lucknow


102 Vijay ghaziabad

Parameter Passing
There are different ways in which parameter data can be passed into and out of methods and functions.
Let us assume that a function B() is called from another function A(). In this case A is called the “caller
function” and B is called the “called function or callee function”. Also, the arguments which A sends
to B are called actual arguments and the parameters of B are called formal arguments.

Types of parameters:

Formal Parameter : A variable and its type as they appear in the prototype of the function or method.

Syntax:
function_name(datatype variable_name)

Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the
function or method call in the calling environment.
Syntax:
func_name(variable name(s));

Pass By Value: Changes made to formal parameter do not get transmitted back to the caller. Any
modifications to the formal parameter variable inside the called function or method affect only the
separate storage location and will not be reflected in the actual parameter in the calling environment.
This method is also called as call by value.

ALL RIGHTS RESERVED TO SVTI 46


Call by reference(aliasing): Changes made to formal parameter do get transmitted back to the caller
through parameter passing. Any changes to the formal parameter are reflected in the actual parameter
in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This
method is also called as <em>call by reference. This method is efficient in both time and space.

Java Compare and Identity Objects


Java Object class is the super class of all the Java classes. All Java classes implements the Object class
by default. The Java Object class provides the two important methods to compare two objects in Java,
i.e. equals() and hashCode() method. In this section, we will learn
how equals() and hashCode() method works. Along with this, we will also learn how to compare two
objects in Java with proper examples.
Java provides the two methods of the Object class to compare the objects are as follows:

Java equals() Method


For example, the expression obj1==obj2 tests the identity, not equality. While the
expression [Link](obj2) compares equality.

Java hashCode() Method


int a=[Link]();
int b=[Link]();
hashcode of emp1 = 2398801145
hashcode of emp2 = 1852349007
Comparing objects emp1 and emp2 = false

ALL RIGHTS RESERVED TO SVTI 47


Destroy Object
The destroy() method of thread class is used to destroy the thread group and all of its subgroups. The
thread group must be empty, indicating that all threads that had been in the thread group have since
stopped.

Syntax
public void destroy()
Example
public class JavaDestroyExp extends Thread
{
JavaDestroyExp(String threadname, ThreadGroup tg)
{
super(tg, threadname);
start();
}
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
[Link](10);
}
catch (InterruptedException ex) {
[Link]("Exception encounterted");}
}
[Link]([Link]().getName() +
" finished executing");
}
public static void main(String arg[]) throws InterruptedException, SecurityException
{
// creating a ThreadGroup
ThreadGroup g1 = new ThreadGroup("Parent thread");
// creating a child ThreadGroup for parent ThreadGroup
ThreadGroup g2 = new ThreadGroup(g1, "child thread");

// creating a thread
JavaDestroyExp t1 = new JavaDestroyExp("Thread-1", g1);
// creating another thread
JavaDestroyExp t2 = new JavaDestroyExp("Thread-2", g1);

// block until other thread is finished


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

ALL RIGHTS RESERVED TO SVTI 48


// destroying child thread
[Link]();
[Link]([Link]() + " destroyed");

// destroying parent thread


[Link]();
[Link]([Link]() + " destroyed");
} }
Output:
Thread-1 finished executing
Thread-2 finished executing
child thread destroyed
Parent thread destroyed
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as autoboxing
and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use
the wrapper classes.

Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will
not change the original value. But, if we convert the primitive value in an object, it will change the original
value.

Serialization: We need to convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.

Synchronization: Java synchronization works with objects in Multithreading.

[Link] package: The [Link] package provides the utility classes to deal with objects.

Collection Framework: Java collection framework works with objects only. All classes of the collection
framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue,
ArrayDeque, etc.) deal with objects only.
The eight classes of the [Link] package are known as wrapper classes in Java. The list of eight wrapper
classes are given below:

ALL RIGHTS RESERVED TO SVTI 49


Features of Java
Primitive Type Wrapper class
boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
double Double

Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST), season (SPRING,
SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and
BLACK) etc. According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
Enums are used to create our own data type like classes. The enum data type (also known as Enumerated
Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is more powerful. Here, we
can define an enum either inside the class or outside the class.

Points to remember for Java Enum


Enum improves type safety
Enum can be easily used in switch
Enum can be traversed
Enum can have fields, constructors and methods
Enum may implement many interfaces but cannot extend any class because it internally extends Enum
class

Simple Example of Java Enum


class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : [Link]())
[Link](s);
}}
Output:
WINTER
SPRING
SUMMER
FALL

ALL RIGHTS RESERVED TO SVTI 50


CHAPTER 05

INHERITANCE IN JAVA
Inheritance
The process by which one class acquires the properties(data members) and functionalities(methods) of
another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common properties and functionalities can be
extended from the another class.

Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent
class, super class or Base class.

Inheritance in Java
Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods. Inheritance allows us to reuse of code, it improves reusability in your java
application.

Note: The biggest advantage of Inheritance is that the code that is already present in base class need not
be rewritten in the child class.
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent class.
The class XYZ is inheriting the properties and methods of ABC class.
class XYZ extends ABC
{
}

Inheritance Example
In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since
class PhysicsTeacher extends the designation and college properties and work() method from base class,
we need not to declare these properties and method in sub class.
Here we have collegeName, designation and work() method which are common to all the teachers so we
have declared them in the base class, this way the child classes
like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be used
directly from base class.

class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
[Link]("Teaching"); } }

ALL RIGHTS RESERVED TO SVTI 51


public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
} }

Output:
Beginnersbook
Teacher
Physics
Teaching

Based on the above example we can say that PhysicsTeacher IS-A Teacher. This means that a child class
has IS-A relationship with the parent class. This is inheritance is known as IS-A relationship between
child and parent class

Types of inheritance
To learn types of inheritance in detail, refer: Types of Inheritance in Java.
1. Single Inheritance: refers to a child and parent class relationship where a class extends the another
class.

2. Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.

ALL RIGHTS RESERVED TO SVTI 52


3. Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.

4. Multiple Inheritance: refers to the concept of one class extending more than one classes, which means
a child class has two parent classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritance, read more about it here.

5. Hybrid inheritance: Combination of more than one types of inheritance in a single program. For
example class A & B extends class C and another class D extends class A then this is a hybrid
inheritance example because it is a combination of single and hierarchical inheritance.

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:


 Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:

ALL RIGHTS RESERVED TO SVTI 53


Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}
}

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:

Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

[Link](myDouble); // Outputs 9.78


[Link](myInt); // Outputs 9
}
}

Overriding and Overloading in Java


Overriding and Overloading are the core concepts in Java programming. They are the ways to implement
polymorphism in our java programs. Polymorphism is one of the OOPS Concepts.

Method Overloading:
Method Overloading is a Compile time polymorphism. In method overloading, more than one method
shares the same method name with different signature in the class. In method overloading, return type
can or can not be be same, but we must have to change the parameter because in java, we can not achieve
the method overloading by changing only the return type of the method.

Example of method overloading:


class MethodOverloadingEx{
static int add(int a, int b){return a+b;}
static int add(int a, int b, int c){return a+b+c;}

public static void main(String args[]) {


[Link](add(4, 6));
[Link](add(4, 6, 7));
}}

ALL RIGHTS RESERVED TO SVTI 54


Output:
//Here, add with two parameter method runs
10

// While here, add with three parameter method runs


17

Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, derived class provides the
specific implementation of the method that is already provided by the base class or parent class. In
method overriding, return type must be same or co-variant (return type may vary in same direction as
the derived class).

Example of method overriding:


class Animal{
void eat(){[Link]("eating.");}
}
class Dog extends Animal{
void eat(){[Link]("Dog is eating.");}
}
class MethodOverridingEx{
public static void main(String args[]) {
Dog d1=new Dog();
Animal a1=new Animal();
[Link]();
[Link]();
}
}

Output:
// Derived class method eat() runs
Dog is eating

// Base class method eat() runs


eating

Polymorphism in Java
It is the ability of an object to take many forms. To simply put, polymorphism in java allows us to
perform the same action in many different ways. Any Java object that can pass more than one IS-A
test is considered to be polymorphic and in java, all the java objects are polymorphic as it has passed
the IS-A test for their own type and for the class Object. There are two types of polymorphism in java:
compile-time polymorphism (Overloading ) and runtime polymorphism (Overriding).

ALL RIGHTS RESERVED TO SVTI 55


Polymorphism in Java Example
A superclass named “Shapes” has a method “area()”. Subclasses of “Shapes” can be “Triangle”,
“circle”, “Rectangle”, etc. Each subclass has its way of calculating area. Using Inheritance and
Polymorphism, the subclasses can use the “area()” method to find the area’s formula for that shape.
1 class Shapes {
2 public void area() {
3 [Link]("The formula for area of ");
4 }
5 }
6 class Triangle extends Shapes {
7 public void area() {
8 [Link]("Triangle is ½ * base * height ");
9 }
10 }
11 class Circle extends Shapes {
12 public void area() {
13 [Link]("Circle is 3.14 * radius * radius ");
14 }
15 }
16 class Main {
17 public static void main(String[] args) {
18 Shapes myShape = new Shapes(); // Create a Shapes object
19 Shapes myTriangle = new Triangle(); // Create a Triangle object
20 Shapes myCircle = new Circle(); // Create a Circle object
21 [Link]();
22 [Link]();
23 [Link]();
24 [Link]();
25 }
26 }

Output:
The formula for area of Triangle is ½ * base * height
The formula for area of Circle is 3.14 * radius * radius

Super Keyword in Java


The super keyword in java is a reference variable that is used to refer parent class objects. The keyword
“super” came into the picture with the concept of Inheritance.

Example
Using super to call the superclass of Dog (subclass):
class Animal { // Superclass (parent)
public void animalSound() {
[Link]("The animal makes a sound");

ALL RIGHTS RESERVED TO SVTI 56


}
}

class Dog extends Animal { // Subclass (child)


public void animalSound() {
[Link](); // Call the superclass method
[Link]("The dog says: bow wow");
}
}

public class Main {


public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
[Link](); // Call the method on the Dog object
}
}

Object class in Java


Object class is present in [Link] package. Every class in Java is directly or indirectly derived from
the Object class. If a Class does not extend any other class then it is direct child class of Object and if
extends other class then it is an indirectly derived. Therefore the Object class methods are available to
all Java classes. Hence Object class acts as a root of inheritance hierarchy in any Java Program.

Example:
The equals Method
Consider this code that tests two Integers, one and anotherOne, for equality:
Integer one = new Integer(1), anotherOne = new Integer(1);

if ([Link](anotherOne))
[Link]("objects are equal");
This code will display objects are equal even though one and anotherOne reference two different, distinct
objects. They are considered equal because they contain the same integer value.

ALL RIGHTS RESERVED TO SVTI 57


CHAPTER 06

ADVANCED INHERITANCE AND GENERICS

Abstract Classes
Data abstraction is the process of hiding certain details and showing only essential information to the
user. Abstraction can be achieved with either abstract classes or interfaces (which you will learn more
about in the next chapter).
The abstract keyword is a non-access modifier, used for classes and methods:

Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).

Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided
by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
[Link]("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we
used in the Polymorphism chapter to an abstract class:
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.

Example
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
[Link]("Zzz");
} }

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The pig says: wee wee");
}}

ALL RIGHTS RESERVED TO SVTI 58


class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();
[Link]();
}}

Interfaces
Another way to achieve abstraction in Java, is with interfaces. An interface is a completely "abstract
class" that is used to group related methods with empty bodies:

Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited) by another
class with the implements keyword (instead of extends). The body of the interface method is provided by
the "implement" class:

Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
[Link]("Zzz");
}}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();

ALL RIGHTS RESERVED TO SVTI 59


[Link](); } }
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible
to create an "Animal" object in the MyMainClass)
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)

Collections in Java
Any group of individual objects which are represented as a single unit is known as the collection of the
objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2
which holds all the collection classes and interface in it.
The Collection interface ([Link]) and Map interface ([Link]) are the two main
“root” interfaces of Java collection classes.

What is a Framework?
A framework is a set of classes and interfaces which provide a ready-made architecture. In order to
implement a new feature or a class, there is no need to define a framework. However, an optimal object-
oriented design always includes a framework with a collection of classes such that all the classes
perform the same kind of task.

Need for a Separate Collection Framework


Before Collection Framework(or before JDK 1.2) was introduced, the standard methods for grouping
Java objects (or collections) were Arrays or Vectors or Hashtables. All of these collections had no
common interface. Therefore, though the main aim of all the collections are same, the implementation
of all these collections were defined independently and had no correlation among them. And also, its
very difficult for the users to remember all the different methods, syntax and constructors present in
every collection class.
Let’s understand this with an example of adding an element in a hashtable and a vector.

// Java program to demonstrate


// why collection framework was needed
import [Link].*;
import [Link].*;

class CollectionDemo {

public static void main(String[] args)


{
// Creating instances of the array,
// vector and hashtable

ALL RIGHTS RESERVED TO SVTI 60


int arr[] = new int[] { 1, 2, 3, 4 };
Vector<Integer> v = new Vector();
Hashtable<Integer, String> h
= new Hashtable();

// Adding the elements into the


// vector
[Link](1);
[Link](2);

// Adding the element into the


// hashtable
[Link](1, "geeks");
[Link](2, "4geeks");

// Array instance creation requires [],


// while Vector and hastable require ()
// Vector element insertion requires addElement(),
// but hashtable element insertion requires put()

// Accessing the first element of the


// array, vector and hashtable
[Link](arr[0]);
[Link]([Link](0));
[Link]([Link](1));
// Array elements are accessed using [],
// vector elements using elementAt()
// and hashtable elements using get()
}}

Output:
1
1
geeks

Generics in Java
Generics mean parameterized types. The idea is to allow type (Integer, String, … etc, and user-defined
types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create
classes that work with different data types.
An entity such as class, interface, or method that operates on a parameterized type is called a generic
entity.

Why Generics?

ALL RIGHTS RESERVED TO SVTI 61


The Object is the superclass of all other classes and Object reference can refer to any type object. These
features lack type safety. Generics add that type safety feature.
Example:

// A Simple Java program to show working of user defined


// Generic classes

// We use < > to specify Parameter type


class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { [Link] = obj; } // constructor
public T getObject() { return [Link]; }
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
[Link]([Link]());

// instance of String type


Test <String> sObj =
new Test<String>("GeeksForGeeks");
[Link]([Link]()); }}

Output:
15
GeeksForGeeks
Comparable in Java
A comparable object is capable of comparing itself with another object. The class itself must implements
the [Link] interface to compare its instances. Consider a Movie class that has members
like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can
implement the Comparable interface with the Movie class, and we override the method compareTo() of
Comparable interface.

Example:
ALL RIGHTS RESERVED TO SVTI 62
CHAPTER 07

PACKAGES
Introduction to Packages
A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two
categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)

Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment. The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles website: [Link]
The library is divided into packages and classes. Meaning you can either import a single class (along with
its methods and attributes), or a whole package that contain all the classes that belong to the specified
package. To use a class or a package from the library, you need to use the import keyword:

Syntax
import [Link]; // Import a single class
import [Link].*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write
the following code:

Example
import [Link];
In the example above, [Link] is a package, while Scanner is a class of the [Link] package.
To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used to
read a complete line:

Example
Using the Scanner class to get user input:
import [Link];

class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner([Link]);
[Link]("Enter username");

String userName = [Link]();


[Link]("Username is: " + userName); } }

ALL RIGHTS RESERVED TO SVTI 63


Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class from
the [Link] package. This package also contains date and time facilities, random-number generator and
other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example will import
ALL the classes in the [Link] package:

Example
import [Link].*;

Static User-defined Packages


To create your own package, you need to understand that Java uses a file system directory to store them.
Just like folders on your computer:

Example
└── root
└── mypack
└── [Link]
To create a package, use the package keyword:

[Link]
package mypack;
class MyPackageClass {
public static void main(String[] args) {
[Link]("This is my package!");
}

ALL RIGHTS RESERVED TO SVTI 64


CHAPTER 08

EXCEPTION HANDLING
Exceptions Overview
An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.
 Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
 Based on these, we have three categories of Exceptions. You need to understand them to know how
exception handling works in Java.

Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be
ignored, the programmer should take care of (handle) these exceptions.

Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of
the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

Example

public class Unchecked_Demo {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
[Link](num[5]);
}
}
If you compile and execute the above program, you will get the following exception.

Output
Exception in thread "main" [Link]: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

ALL RIGHTS RESERVED TO SVTI 65


Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.

Exception Hierarchy
All exception classes are subtypes of the [Link] class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is derived
from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java
programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM
is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

Following is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods
Following is the list of important methods available in the Throwable class.
[Link]. Method & Description

1 public String getMessage()


Returns a detailed message about the exception that has occurred. This message is initialized
in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


Returns the name of the class concatenated with the result of getMessage().

4 public void printStackTrace()

ALL RIGHTS RESERVED TO SVTI 66


Prints the result of toString() along with the stack trace to [Link], the error output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at index 0 represents
the top of the call stack, and the last element in the array represents the method at the bottom
of the call stack.

6 public Throwable fillInStackTrace()


Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}

The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception
occurred is handled by catch block associated with it. Every try block should be immediately followed
either by a catch block or finally block. A catch statement involves declaring the type of exception you
are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the
try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to
the catch block much as an argument is passed into a method parameter.

Example
The following is an array declared with 2 elements. Then the code tries to access the 3 rd element of the
array which throws an exception.

// File Name : [Link]


import [Link].*;

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
[Link]("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}

ALL RIGHTS RESERVED TO SVTI 67


[Link]("Out of the block");
}
}
This will produce the following result −

Output
Exception thrown :[Link]: 3
Out of the block

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always executes, irrespective
of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax −

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
[Link]("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}finally {
a[0] = 6;
[Link]("First element value: " + a[0]);
[Link]("The finally statement is executed");
} } }

ALL RIGHTS RESERVED TO SVTI 68


This will produce the following result −
Output
Exception thrown :[Link]: 3
First element value: 6
The finally statement is executed
Note the following −
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.

The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
The following method declares that it throws a RemoteException −

Example
import [Link].*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared
in a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException −

Example
import [Link].*;
public class className {

public void withdraw(double amount) throws RemoteException,


InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

ALL RIGHTS RESERVED TO SVTI 69


CHAPTER 09

INPUT/OUTPUT STREAMS
Overview of Streams
A stream is a Java interface that takes a source, conducts a set of operations to extract specific data, then provides
that data to the application for use. Essentially, it allows you to extract specialized data from a collection of
generalized data.
A stream pipeline always begins with a source. The type of source is dependent on the type of data that you're
dealing with, but two of the more popular ones are arrays and collections.
To transform the collection into an initial stream, you'll need to add the stream() function to the source. This will
place the source into the stream pipeline where several different intermediate operations (such
as filter() and sort()) can operate on it.

Bytes vs. Characters


Character Stream
In Java, characters are stored using Unicode conventions (Refer this for details). Character stream
automatically allows us to read/write data character by character. For example FileReader and
FileWriter are character streams used to read from source and write to destination.

ALL RIGHTS RESERVED TO SVTI 70


// Java Program illustrating that we can read a file in
// a human readable format using FileReader
import [Link].*; // Accessing FileReader, FileWriter, IOException
public class GfG
{
public static void main(String[] args) throws IOException
{
FileReader sourceStream = null;
try
{
sourceStream = new FileReader("[Link]");

// Reading sourcefile and writing content to


// target file character by character.
int temp;
while ((temp = [Link]()) != -1)
[Link]((char)temp);
}
finally
{
// Closing stream as no longer in use
if (sourceStream != null)
[Link]();
}}}

Output :
Shows contents of file [Link]

Byte Stream
Byte streams process data byte by byte (8 bits). For example FileInputStream is used to read from source
and FileOutputStream to write to the destination.

// Java Program illustrating the Byte Stream to copy


// contents of one file to another file.
import [Link].*;
public class BStream
{
public static void main(String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
try
{
sourceStream = new FileInputStream("[Link]");

ALL RIGHTS RESERVED TO SVTI 71


targetStream = new FileOutputStream ("[Link]");

// Reading source file and writing content to target


// file byte by byte
int temp;
while ((temp = [Link]()) != -1)
[Link]((byte)temp);
}
finally
{
if (sourceStream != null)
[Link]();
if (targetStream != null)
[Link]();
}}}

When to use Character Stream over Byte Stream?


In Java, characters are stored using Unicode conventions. Character stream is useful when we want to
process text files. These text files can be processed character by character. A charact er size is typically
16 bits.

When to use Byte Stream over Character Stream?


Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files.

Convert Byte stream into Character stream


1. The byte stream is converted to a character stream:
public class Test {
public static void main(String[] args) throws IOException {
//1. Get the terminal object
File file = new File("C:"+ [Link]+"Users"+
[Link]+"Lenovo"+ [Link]+"Desktop"+ [Link]+"[Link]");
//2. Get the output stream
OutputStream outputStream = new FileOutputStream(file);
//3. Data input and output
OutputStreamWriter out = new OutputStreamWriter(outputStream);
[Link]("Hello");
//4. Close the stream
[Link]();
}
}

2. Copy of the file:Character stream


public class Test {
public static void main(String[] args) throws Exception {
String sourceFilePath = "C:\\Users\\Lenovo\\Desktop\\Portrait [Link]";
String destFilePath = "C:\\Users\\Lenovo\\Desktop\\[Link]";

ALL RIGHTS RESERVED TO SVTI 72


copyFile(sourceFilePath,destFilePath);
}
/**
* File copy
*/
public static boolean copyFile(String sourceFilePath,String destFilePath) throws Exception
{
//1. Get the File object
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
//2. Get the input and output stream
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
//3. Input and output of data
long start = [Link]();
int len = 0;
//____________________________________
Byte[] data = new byte[1024];// Open the buffer to read multiple contents at once
/ / Introduce the buffer
While((len = [Link](data))!=-1){// means reading data into a byte array and then returning the
number of reads
[Link](len); //Write part of the byte array to the target file
}
//______________________________________
long end = [Link]();
[Link]("End of file copy, total time: "+(end-start) + "milliseconds");
return true;
}}

File Object in Java


The File class is Java’s representation of a file or directory path name. Because file and directory names
have different formats on different platforms, a simple string is not adequate to name them. The File
class contains several methods for working with the path name, deleting and renaming files, creating
new directories, listing the contents of a directory, and determining several common attributes of files
and directories.
It is an abstract representation of file and directory pathnames.
A pathname, whether abstract or in string form can be either absolute or relative. The parent of an
abstract pathname may be obtained by invoking the getParent() method of this class.
First of all, we should create the File class object by passing the filename or directory name to it. A file
system may implement restrictions to certain operations on the actual file-system object, such as
reading, writing, and executing. These restrictions are collectively known as access permissions.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a
File object will never change.

How to create a File Object?


A File object is created by passing in a String that represents the name of a file, or a String or another
File object. For example,
File a = new File("/usr/local/bin/geeks");

ALL RIGHTS RESERVED TO SVTI 73


defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute abstract
file name.

Constructors

 File(File parent, String child) : Creates a new File instance from a parent abstract pathname and a
child pathname string.

 File(String pathname) : Creates a new File instance by converting the given pathname string into
an abstract pathname.

 File(String parent, String child) : Creates a new File instance from a parent pathname string and
a child pathname string.

 File(URI uri) : Creates a new File instance by converting the given file: URI into an abstract
pathname.

Methods

 boolean canExecute() : Tests whether the application can execute the file denoted by this abstract
pathname.

 boolean canRead() : Tests whether the application can read the file denoted by this abstract
pathname.

 boolean canWrite() : Tests whether the application can modify the file denoted by this abstract
pathname.

 int compareTo(File pathname) : Compares two abstract pathnames lexicographically.

 boolean createNewFile() : Atomically creates a new, empty file named by this abstract pathname .

Implementation
Program 1: Program to check if a file or directory physically exist or not.

// In this program, we accepts a file or directory name from


// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.
import [Link];
// Displaying file property
class fileProperty
{
public static void main(String[] args) {
//accept file name or directory name through command line args

ALL RIGHTS RESERVED TO SVTI 74


String fname =args[0];
//pass the filename or directory name to File object
File f = new File(fname);
//apply File class methods on File object
[Link]("File name :"+[Link]());
[Link]("Path: "+[Link]());
[Link]("Absolute path:" +[Link]());
[Link]("Parent:"+[Link]());
[Link]("Exists :"+[Link]());
if([Link]())
{
[Link]("Is writeable:"+[Link]());
[Link]("Is readable"+[Link]());
[Link]("Is a directory:"+[Link]());
[Link]("File Size in bytes "+[Link]());
}}}

Output:
File name :[Link]
Path: [Link]
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\[Link]
Parent:null
Exists :true
Is writeable:true
Is readabletrue
Is a directory:false
File Size in bytes 20

Binary Input/Output Streams.


A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very
basic functionality related to streams and I/O. We will see the most commonly used examples one by one.

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes
related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these two
classes to copy an input file into an output file −
ALL RIGHTS RESERVED TO SVTI 75
Example
import [Link].*;
public class CopyFile {

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


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();}}}}
Now let's have a file [Link] with the following content −
This is test for copy file.

Java PrintWriter Class


The PrintWriter class of the [Link] package can be used to write output data in a commonly readable
form (text).

It extends the abstract class Writer.

Working of PrintWriter
Unlike other writers, PrintWriter converts the primitive data (int, float, char, etc.) into the text format. It
then writes that formatted data to the writer.
Also, the PrintWriter class does not throw any input/output exception. Instead, we need to use
the checkError() method to find any error in it.

ALL RIGHTS RESERVED TO SVTI 76


Note: The PrintWriter class also has a feature of auto flushing. This means it forces the writer to write all
data to the destination if one of the println() or printf() methods is called.

Create a PrintWriter
In order to create a print writer, we must import the [Link] package first. Once we import the
package here is how we can create the print writer.

1. Using other writers


// Creates a FileWriter
FileWriter file = new FileWriter("[Link]");

// Creates a PrintWriter
PrintWriter output = new PrintWriter(file, autoFlush);

Here,
we have created a print writer that will write data to the file represented by the FileWriter
autoFlush is an optional parameter that specifies whether to perform auto flushing or not

2. Using other output streams


// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream("[Link]");

// Creates a PrintWriter
PrintWriter output = new PrintWriter(file, autoFlush);

Here,
we have created a print writer that will write data to the file represented by the FileOutputStream
the autoFlush is an optional parameter that specifies whether to perform auto flushing or not

3. Using filename
// Creates a PrintWriter
PrintWriter output = new PrintWriter(String file, boolean autoFlush);

Here,
we have created a print writer that will write data to the specified file
the autoFlush is an optional boolean parameter that specifies whether to perform auto flushing or nor

Note: In all the above cases, the PrintWriter writes data to the file using some default character encoding.
However, we can specify the character encoding (UTF8 or UTF16) as well.
// Creates a PrintWriter using some character encoding
PrintWriter output = new PrintWriter(String file, boolean autoFlush, Charset cs);

Here, we have used the Charset class to specify the character encoding.

Methods of PrintWriter
The PrintWriter class provides various methods that allow us to print data to the output.
ALL RIGHTS RESERVED TO SVTI 77
print() Method
print() - prints the specified data to the writer
println() - prints the data to the writer along with a new line character at the end
For example,
import [Link];

class Main {
public static void main(String[] args) {

String data = "This is a text inside the file.";

try {
PrintWriter output = new PrintWriter("[Link]");

[Link](data);
[Link]();
}
catch(Exception e) {
[Link]();
}}}
In the above example, we have created a print writer named output. This print writer is linked with the
file [Link].

PrintWriter output = new PrintWriter("[Link]");

To print data to the file, we have used the print() method.

Here when we run the program, the [Link] file is filled with the following content.

This is a text inside the file.

Writing and Reading objects in Java


The objects can be converted into byte-stream using [Link]. In order to enable
writing of objects into a file using ObjectOutputStream, it is mandatory that the concerned class
implements Serializable interface as shown in the class definition below.
Reading objects in Java are similar to writing object using ObjectOutputStreamObjectInputStream. Below
example shows the complete cycle of writing objects and reading objects in Java.
On reading objects, the ObjectInputStream directly tries to map all the attributes into the class into which
we try to cast the read object. If it is unable to map the respective object exactly then it throws
a ClassNotFound exception.
Let us now understand the writing and reading process using an example. We are using the Person class
shown above as an object.

[Link]

package packagename;
package packagename;
ALL RIGHTS RESERVED TO SVTI 78
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class WriterReader {

public static void main(String[] args) {

Person p1 = new Person("John", 30, "Male");


Person p2 = new Person("Rachel", 25, "Female");

try {
FileOutputStream f = new FileOutputStream(new File("[Link]"));
ObjectOutputStream o = new ObjectOutputStream(f);

// Write objects to file


[Link](p1);
[Link](p2);

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

FileInputStream fi = new FileInputStream(new File("[Link]"));


ObjectInputStream oi = new ObjectInputStream(fi);

// Read objects
Person pr1 = (Person) [Link]();
Person pr2 = (Person) [Link]();

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

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

} catch (FileNotFoundException e) {
[Link]("File not found");
} catch (IOException e) {
[Link]("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
}}}

On executing the above code, we get below output:

Name:John

ALL RIGHTS RESERVED TO SVTI 79


Age: 30
Gender: Male
Name:Rachel
Age: 25
Gender: Female

Closing Streams
The [Link]() method closes this stream and releases any system resources associated
with the stream.

Declaration
Following is the declaration for [Link]() method −
public void close()
Parameters
NA

Return Value
The method does not return any value

Exception
IOException − If an I/O error occurs.
Example
The following example shows the usage of [Link]() method.
package [Link];

import [Link];
import [Link];

public class InputStreamDemo {


public static void main(String[] args) throws Exception {
InputStream is = null;
int i = 0;

try {
// new input stream created
is = new FileInputStream("C://[Link]");

// invoke available
i = [Link]();

// number of bytes available is printed


[Link](i);

// releases any system resources associated with the stream


[Link]();

// throws io exception on available() invocation


i = [Link]();
[Link](i);
ALL RIGHTS RESERVED TO SVTI 80
} catch(Exception e) {
// if any I/O error occurs
[Link]("Sorry, the input stream is closed");
} finally {
// releases system resources associated with this stream
if(is!=null)
[Link]();
}
}
}
Assuming we have a text file c:/[Link], which has the following content. This file will be used as an input
for our example program −
ABCDEF
Let us compile and run the above program, this will produce the following result −
Sorry, the input stream is closed

ALL RIGHTS RESERVED TO SVTI 81


CHAPTER 10

CORE COLLECTIONS FRAMEWORK


The Collection Framework
The Collection framework represents a unified architecture for storing and manipulating a group of
objects. Let us see the hierarchy of Collection framework. The [Link] package contains all
the classes and interfaces for the Collection framework.

Set in Java
The set is an interface available in the [Link] package. The set interface extends the Collection
interface. An unordered collection or list in which duplicates are not allowed is referred to as a collection
interface. The set interface is used to create the mathematical set. The set interface use collection
interface's methods to avoid the insertion of the same elements. SortedSet and NavigableSet are two
interfaces that extend the set implementation.

ALL RIGHTS RESERVED TO SVTI 82


In the above diagram, the NavigableSet and SortedSet are both the interfaces. The NavigableSet extends
the SortedSet, so it will not retain the insertion order and store the data in a sorted way.

[Link]
import [Link].*;
public class setExample{
public static void main(String[] args)
{
// creating LinkedHashSet using the Set
Set<String> data = new LinkedHashSet<String>();
[Link]("JavaTpoint");
[Link]("Set");
[Link]("Example");
[Link]("Set");
[Link](data);
} }
Output:

ALL RIGHTS RESERVED TO SVTI 83


Note: Throughout the section, we have compiled the program with file name and run the program
with class name. Because the file name and the class name are different.
Operations on the Set Interface
On the Set, we can perform all the basic mathematical operations like intersection, union and difference.
Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and
set2 = [33, 2, 83, 45, 3, 12, 55]. We can perform the following operation on the Set:
Intersection: The intersection operation returns all those elements which are present in both the set. The
intersection of set1 and set2 will be [33, 45, 55].
Union: The union operation returns all the elements of set1 and set2 in a single set, and that set can either
be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83].
Difference: The difference operation deletes the values from the set which are present in another set. The
difference of the set1 and set2 will be [66, 34, 22, 77].
In set, addAll() method is used to perform the union, retainAll() method is used to perform the
intersection and removeAll() method is used to perform difference. Let's take an example to understand
how these methods are used to perform the intersection, union, and difference operations.
[Link]
import [Link].*;
public class SetOperations
{
public static void main(String args[])
{
Integer[] A = {22, 45,33, 66, 55, 34, 77};
Integer[] B = {33, 2, 83, 45, 3, 12, 55};
Set<Integer> set1 = new HashSet<Integer>();
[Link]([Link](A));
Set<Integer> set2 = new HashSet<Integer>();
[Link]([Link](B));
// Finding Union of set1 and set2
Set<Integer> union_data = new HashSet<Integer>(set1);
union_data.addAll(set2);
[Link]("Union of set1 and set2 is:");
[Link](union_data);
// Finding Intersection of set1 and set2
Set<Integer> intersection_data = new HashSet<Integer>(set1);
intersection_data.retainAll(set2);
[Link]("Intersection of set1 and set2 is:");
[Link](intersection_data);
// Finding Difference of set1 and set2
Set<Integer> difference_data = new HashSet<Integer>(set1);
difference_data.removeAll(set2);
[Link]("Difference of set1 and set2 is:");
[Link](difference_data);
}
}
Output:
ALL RIGHTS RESERVED TO SVTI 84
Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based methods
to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store
the null elements in the list.
The List interface is found in the [Link] package and inherits the Collection interface. It is a factory of
ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions.
The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList
and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.

List Interface declaration


public interface List<E> extends Collection<E>

Java List Example


Let's see a simple example of List where we are using the ArrayList class as the implementation.
import [Link].*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
[Link](fruit);

}}

Output:
Mango
Apple
Banana
Grapes
ALL RIGHTS RESERVED TO SVTI 85
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is
removed first and last element is removed at last.

Queue Interface declaration


public interface Queue<E> extends Collection<E>
PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner. It inherits AbstractQueue class.

PriorityQueue class declaration


Let's see the declaration for [Link] class.
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Java PriorityQueue Example
import [Link].*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Amit");
[Link]("Vijay");
[Link]("Karan");
[Link]("Jai");
[Link]("Rahul");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]("iterating the queue elements:");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
[Link]();
[Link]();
[Link]("after removing two elements:");
Iterator<String> itr2=[Link]();
while([Link]()){
[Link]([Link]());
} } }
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay

ALL RIGHTS RESERVED TO SVTI 86


Rahul
after removing two elements:
Karan
Rahul
Vijay

Java Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as
an entry. A Map contains unique keys. A Map is useful if you have to search, update or delete elements
on the basis of a key.

Java Map Hierarchy


There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap
allow null keys and values, but TreeMap doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class. It


maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains ascending


order.

ALL RIGHTS RESERVED TO SVTI 87


Java Map Example: Non-Generic (Old Style)
//Non-generic
import [Link].*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
[Link](1,"Amit");
[Link](5,"Rahul");
[Link](2,"Jai");
[Link](6,"Amit");
//Traversing Map
Set set=[Link]();//Converting to Set so that we can traverse
Iterator itr=[Link]();
while([Link]()){
//Converting to [Link] so that we can get key and value separately
[Link] entry=([Link])[Link]();
[Link]([Link]()+" "+[Link]());
} } }

Output:
1 Amit
2 Jai
5 Rahul
6 Amit

Java Map Example: Generic (New Style)


import [Link].*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
//Elements can traverse in any order
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
} } }

Output:
102 Rahul
100 Amit
101 Vijay

ALL RIGHTS RESERVED TO SVTI 88


Sorting in Collection
We can sort the elements of:
 String objects
 Wrapper class objects
 User-defined class objects

Collections class provides static methods for sorting the elements of a collection. If collection elements
are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class
provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements


public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable
type.
Note: String class and Wrapper classes implement the Comparable interface. So if you store the
objects of string or wrapper classes, it will be Comparable.

Example to sort string objects


import [Link].*;
class TestSort1{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();


[Link]("Viru");
[Link]("Saurav");
[Link]("Mukesh");
[Link]("Tahir");

[Link](al);
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
} } }

OUTPUT
Mukesh
Saurav
Tahir
Viru

Example to sort string objects in reverse order


import [Link].*;
class TestSort2{
public static void main(String args[]){

ALL RIGHTS RESERVED TO SVTI 89


ArrayList<String> al=new ArrayList<String>();
[Link]("Viru");
[Link]("Saurav");
[Link]("Mukesh");
[Link]("Tahir");

[Link](al,[Link]());
Iterator i=[Link]();
while([Link]())
{
[Link]([Link]());
} } }

OUTPUT
Viru
Tahir
Saurav
Mukesh

Difference between Comparable and Comparator


Comparable and Comparator both are interfaces and can be used to sort collection elements.
Java Comparable Example
Let's see the example of a Comparable interface that sorts the list elements on the basis of age.
File: [Link]
//Java Program to demonstrate the use of Java Comparable.
//Creating a class which implements Comparable Interface
import [Link].*;
import [Link].*;
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
[Link]=rollno;
[Link]=name;
[Link]=age;
}
public int compareTo(Student st){
if(age==[Link])
return 0;
else if(age>[Link])
return 1;
else
return -1; } }

ALL RIGHTS RESERVED TO SVTI 90


//Creating a test class to sort the elements
public class TestSort3{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
[Link](new Student(101,"Vijay",23));
[Link](new Student(106,"Ajay",27));
[Link](new Student(105,"Jai",21));

[Link](al);
for(Student st:al){
[Link]([Link]+" "+[Link]+" "+[Link]);
} } }

Output:
105 Jai 21
101 Vijay 23
106 Ajay 27

Java Comparator Example


Let's see an example of the Java Comparator interface where we are sorting the elements of a list using
different comparators.
[Link]
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
[Link]=rollno;
[Link]=name;
[Link]=age;
} }

[Link]
import [Link].*;
class AgeComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
if([Link]==[Link])
return 0;
else if([Link]>[Link])
return 1;
else
return -1;
}}

ALL RIGHTS RESERVED TO SVTI 91


[Link]
This class provides comparison logic based on the name. In such case, we are using the compareTo()
method of String class, which internally provides the comparison logic.
import [Link].*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
return [Link]([Link]);
}
}

[Link]
In this class, we are printing the values of the object by sorting on the basis of name and age.
//Java Program to demonstrate the use of Java Comparator
import [Link].*;
import [Link].*;
class TestComparator{
public static void main(String args[]){
//Creating a list of students
ArrayList<Student> al=new ArrayList<Student>();
[Link](new Student(101,"Vijay",23));
[Link](new Student(106,"Ajay",27));
[Link](new Student(105,"Jai",21));

[Link]("Sorting by Name");
//Using NameComparator to sort the elements
[Link](al,new NameComparator());
//Traversing the elements of list
for(Student st: al){
[Link]([Link]+" "+[Link]+" "+[Link]);
}

[Link]("sorting by Age");
//Using AgeComparator to sort the elements
[Link](al,new AgeComparator());
//Travering the list again
for(Student st: al){
[Link]([Link]+" "+[Link]+" "+[Link]);
} } }

Output:
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23

ALL RIGHTS RESERVED TO SVTI 92


Sorting by Age
105 Jai 21
101 Vijay 23
106 Ajay 27

However, there are many differences between Comparable and Comparator interfaces that are given
below.

Comparable Comparator

1) Comparable provides a single sorting sequence. The Comparator provides multiple sorting
In other words, we can sort the collection on the basis sequences. In other words, we can sort the
of a single element such as id, name, and price. collection on the basis of multiple elements
such as id, name, and price etc.

2) Comparable affects the original class, i.e., the Comparator doesn't affect the original class,
actual class is modified. i.e., the actual class is not modified.

3) Comparable provides compareTo() method to Comparator provides compare() method to


sort elements. sort elements.

4) Comparable is present in [Link] package. A Comparator is present in


the [Link] package.

5) We can sort the list elements of Comparable type We can sort the list elements of Comparator
by [Link](List) method. type by [Link](List,
Comparator) method.

Java List sort() Method


The sort() method of List Interface sorts the given list according to the order specified in the comparator.
The list must be modifiable else it will throw an exception.

Syntax
default void sort(Comparator<? super E> c)

Parameters
The parameter 'c' represents the Comparator used to compare list elements. And for null values, natural
ordering is used.
Return
NA
Throws:
ClassCastException- If the list contains elements that are not mutually comparable using the comparator
UnsupportedOperationException- If the list's list-iterator does not support the sort operation
IllegalArgumentException- If the comparator is found to violate the Comparator protocols.
Example 1

ALL RIGHTS RESERVED TO SVTI 93


import [Link];
import [Link];
import [Link];
public class JavaListSubListExample3 {
public static void main(String[] args) {
List<String> list= new LinkedList<>();
[Link]("Renu");
[Link]("Heera");
[Link]("Vijay");
[Link]("Geetanjali");
[Link]("List : "+list);
//will sort the string acc to the alphabets
[Link](list);
[Link]("Sorted List : "+list);
} }

Output:
List : [Renu, Heera, Vijay, Geetanjali]
Sorted List : [Geetanjali, Heera, Renu, Vijay]

Sort an Array in Java


The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending
or descending order. The numerical and lexicographical (alphabetical) order is a widely used order.
In this section, we will learn how to sort array in Java in ascending and descending order using
the sort() method and without using the sort() method. Along with this, we will also learn how to sort
subarray in Java.

Sort Array in Ascending Order


The ascending order arranges the elements in the lowest to highest order. It is also known as natural
order or numerical order. We can perform sorting in the following ways:
 Using the sort() Method
 Without using the method
 Using the for Loop
 Using the User Defined Method

Using the sort() Method


In Java, Arrays is the class defined in the [Link] package that provides sort() method to sort an array in
ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is
a static method that parses an array as a parameter and does not return anything. We can invoke it directly
using the class name. It accepts an array of type int, float, double, long, char, byte.

History of Java
Syntax:
public static void sort(int[] a)

ALL RIGHTS RESERVED TO SVTI 94


Where a is an array to be short.
Note: Like the Arrays class, the Collections class also provides the sort() method to sort the array.
But there is a difference between them. The sort() method of the Arrays class works for primitive
type while the sort() method of the Collections class works for objects Collections, such as
LinkedList, ArrayList, etc.

Let's sort an array using the sort() method of the Arrays class.
In the following program, we have defined an array of type integer. After that, we have invoked the sort()
method of the Arrays class and parses the array to be sort. For printing the sorted array, we have used for
loop.

[Link]
import [Link];
public class SortArrayExample1
{
public static void main(String[] args)
{
//defining an array of integer type
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
//invoking sort() method of the Arrays class
[Link](array);
[Link]("Elements of array sorted in ascending order: ");
//prints array using the for loop
for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}} }

Output:
Array elements in ascending order:
5
12
22
23
34
67
90
109

In the above program, we can also use the toSting() method of the Arrays class to print the array, as shown
in the following statement. It returns a string representation of the specified array.

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

ALL RIGHTS RESERVED TO SVTI 95


Without Using the Method
Using the for Loop
In the following example, we have initialized an array of integer type and sort the array in ascending order.
[Link]
public class SortArrayExample2
{
public static void main(String[] args)
{
//creating an instance of an array
int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};
[Link]("Array elements after sorting:");
//sorting logic
for (int i = 0; i < [Link]; i++)
{
for (int j = i + 1; j < [Link]; j++)
{
int tmp = 0;
if (arr[i] > arr[j])
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}}
//prints the sorted element of the array
[Link](arr[i]);
}} }

Output:
Array elements after sorting:
-65
-4
-1
1
3
6
20
34
34
55
78
90

ALL RIGHTS RESERVED TO SVTI 96


Java Collections class/Methods
Java collection class/methods is used exclusively with static methods that operate on or return collections.
It inherits Object class.

The important points about Java Collections class are:


Java Collection class/methods supports the polymorphic algorithms that operate on collections.
Java Collection class/methods throws a NullPointerException if the collections or class objects provided
to them are null.

Collections class declaration


Let's see the declaration for [Link] class.
public class Collections extends Object

SN Modifier & Type Methods Descriptions

1) static <T> Boolean addAll() It is used to adds all of the specified


elements to the specified collection.

2) static <T> Queue<T> asLifoQueue() It returns a view of a Deque as a Last-


in-first-out (LIFO) Queue.

3) static <T> int binarySearch() It searches the list for the specified
object and returns their position in a
sorted list.

4) static <E> Collection<E> checkedCollection() It is used to returns a dynamically


typesafe view of the specified
collection.

5) static <E> List<E> checkedList() It is used to returns a dynamically


typesafe view of the specified list.

6) static <K,V> Map<K,V> checkedMap() It is used to returns a dynamically


typesafe view of the specified map.

7) static <K,V> checkedNavigableMap() It is used to returns a dynamically


NavigableMap<K,V> typesafe view of the specified
navigable map.

8) static <E> checkedNavigableSet() It is used to returns a dynamically


NavigableSet<E> typesafe view of the specified
navigable set.

9) static <E> Queue<E> checkedQueue() It is used to returns a dynamically


typesafe view of the specified queue.

10) static <E> Set<E> checkedSet() It is used to returns a dynamically


typesafe view of the specified set.

ALL RIGHTS RESERVED TO SVTI 97


Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It
is found in the [Link] package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use
all the methods of List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.

The important points about Java ArrayList class are:


 Difference between JDK, JRE, and JVM
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index basis.
 In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.

Java ArrayList Example


import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object

ALL RIGHTS RESERVED TO SVTI 98


[Link](list);
} }

Output:
[Mango, Apple, Banana, Grapes]

Java HashMap

Java HashMap class implements the Map interface which allows us to store key and value pair, where
keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding
key. It is easy to perform operations using the key index like updation, deletion, etc. HashMap class is
found in the [Link] package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null
elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>,
where K stands for key and V for value. It inherits the AbstractMap class and implements the Map
interface.

Points to remember
 Java HashMap contains values based on the key.
 Java HashMap contains only unique keys.
 Java HashMap may have one null key and multiple null values.
 Java HashMap is non synchronized.
 Java HashMap maintains no order.
 The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Java HashMap Example


Let's see a simple example of HashMap to store key and value pair.
import [Link].*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
[Link](1,"Mango"); //Put elements in Map
[Link](2,"Apple");

ALL RIGHTS RESERVED TO SVTI 99


[Link](3,"Banana");
[Link](4,"Grapes");

[Link]("Iterating Hashmap...");
for([Link] m : [Link]()){
[Link]([Link]()+" "+[Link]());
} } }

Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes

Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet
class and implements Set interface.

The important points about Java HashSet class are:


 HashSet stores the elements by using a mechanism called hashing.
 HashSet contains unique elements only.
 HashSet allows null value.
 HashSet class is non synchronized.
 HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their
hashcode.
 HashSet is the best approach for search operations.
 The initial default capacity of HashSet is 16, and the load factor is 0.75.
ALL RIGHTS RESERVED TO SVTI 100
Java HashSet Example
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
import [Link].*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Five
One
Four
Two
Three

ALL RIGHTS RESERVED TO SVTI 101


CHAPTER 11

JAVA EE OVERVIEW
Introduction
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is currently
known as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard Edition). The Java
EE provides a platform for developers with enterprise features such as distributed computing and web
services. Java EE applications are usually run on reference run times such as microservers or application
servers. Examples of some contexts where Java EE is used are e-commerce, accounting, banking
information systems.
Setting up Java EE

Requirements
For the installation of latest SDK of Java EE which is Java EE 6 SDK on windows, you require to have a
minimum memory of 1GB, minimum Disk space of 250MB free and JVM Java SE 6. For setting up Java
EE, you require to have a JDK and then have an IDE preferably Eclipse as it is free.

Install a Java Development Kit


Browse to Oracle's Java SE Development Kit downloads
In the section titled Java SE Development Kit 9.0.1, read the license and, if you agree, click Accept

License Agreement
Still, in that section, click on JDK-9.0.1_windows-x64_bin.exe (or the right download for your OS)
Run the downloaded JDK installer, using Run As Administrator
Add the Windows (or Linux) Environment Variable JAVA_HOME. Set it to the root folder of your
newly-installed JDK, which looks like C:\Program Files\Java\jdk1.8.0_51.

Install Eclipse for Java EE


1. Browse to Eclipse Downloads
2. Click on the Download button under Get Eclipse.
3. On the resulting page, click on the Download button.
Note: The version of Eclipse (32-bit or 64-bit) which you download should match the version
of your JDK. You installed JDK-9.0.1_windows-x64 above, so download the 64-bit Eclipse.

4. Run the downloaded installer using Run as Administrator.


5. Choose the version of Eclipse you wish to install. Eclipse IDE for Java EE developers is preferable
for Java work.
6. If the installation fails, try again with real-time virus scanning temporarily turned off. Remember to
turn it on again when it's done.

Java SE
The SE stands for Java Standard Edition is a computing platform in which we can execute software,
and it can be used for development and deployment of portable code for desktop and server environments.
It has the Java programming language in use. It is part of Java software-platform family. Java SE has a
ALL RIGHTS RESERVED TO SVTI 102
variety of general purpose APIs and the Java Class Library. It is the core Java programming platform and
provides all the libraries and APIs such as [Link], [Link], [Link], [Link], [Link] etc.

The following are the few APIs which Java SE has -

 Applet- An applet is a small application, especially a utility program performing one or a few
simple functions. This API provides the classes necessary to create an applet. The applet
framework contains two entities. One is applet and the other is applet context. The applet is an
embeddable window with a few extra methods which the applet context uses to initialize, start and
stop the applet.

 AWT- AWT stands for Abstract window toolkit. This package contains all the classes for creating
a user interface and for painting graphics and images. Any UI object like button and scrollbar is
called as a component.

 RMI- RMI stands for Remote Method Invocation enables the programmer to create distributed
Java technology-based to Java technology-based application. RMI uses object serialization to
marshal and unmarshal parameters and does not shorten types.

 JDBC- It stands for Java Database Connectivity. It allows you to fetch data from any data source
be its relational database, be it a spreadsheet, be it flat file.

 Swing- Swing provides a set of 'lightweight' components mainly used for graphical user interface
enhancement. All swing components and related classes should be accessed on the dispatching
thread.

 Collections- Collection refers to a group of objects, known as its elements. There are many
methods in the collections Framework interface which depend on the equals method. For example-
the contains(Object o) method says that it will return true if the collection contains an element
which satisfies the condition that (o==null ? e==null: [Link](e))

 xml binding- It provides a run-time binding framework for client-side user application allowing
the user to Marshall, unmarshal, and validation capabilities. JAXBContext is the client-entry point
to the runtime binding framework.

 JavaFX (Merged to Java SE 8)- This contains several packages within it like
[Link](provides set of classes for ease of animation), [Link](provides set of
classes for application life-cycle classes ) and [Link]() etc.

 Java 8 Collections Streaming API- It contains classes to support functional-style operations on


streams of elements. Such as map-reduce transformation on collections. Stream operations are
divided into two parts namely intermediate and terminal operations which are combined together
to form pipelines.

 Java 9 Reactive Streams API- Reactive Stream initiative was taken by giants like Netflix in order
to standardize the asynchronous exchange of data within an application. They are a part of JDK in
the form of [Link].
ALL RIGHTS RESERVED TO SVTI 103
 Java 9 HTTP/2 API- This API solved various problems which were with the previous HTTP/1.1
API. Previously we cannot have more than 6 connections at a time. This made it complex as other
requests had to wait till previous calls get sorted. This got sorted with this API.

Web Application and Services


A web application is computer software that can be accessed using any web browser. Usually, the frontend
of a web application is created using the scripting languages such as HTML, CSS, and JavaScript,
supported by almost all web browsers. In contrast, the backend is created by any of the programming
languages such as Java, Python, Php, etc., and databases. Unlike the mobile application, there is no specific
tool for developing web applications; we can use any of the supported IDE for developing the web
application.

Web Server and Client


The web server is a process that handles the client's request and responds. It processes the request made
by the client by using the related protocols. The main function of the webserver is to store the request and
respond to them with web pages. It is a medium between client and server. For example, Apache is a
leading webserver.

A client is a software that allows users to request and assist them in communicating with the server. The
web browsers are the clients in a web application; some leading clients are Google Chrome, Firefox,
Safari, Internet Explorer, etc.

HTML and HTTP


The HTML stands for HyperText Markup Language; it is a common language for Web Server and Web
Client communication. Since both the web server and web client are two different software components
of the web, we need a language that communicates between them.
The HTTP stands for HyperText Transfer Protocol; it is a communication protocol between the client and
the server. It runs on top of the TCP/IP protocol.
Some of the integral components of an HTTP Request are as following:
 HTTP Method: The HTTP method defines an action to be performed; usually, they are GET,
POST, PUT, etc.
 URL: URL is a web address that is defined while developing a web application. It is used to access
a webpage.
 Form Parameters: The form parameter is just like an argument in a Java method. It is passed to
provide the details such as user, password details on a login page.

What is URL
URL stands for Universal Resource Locator used to locate the server and resource. It is an address of a
web page. Every web page on a project must have a unique name.
A URL looks like as follows:
[Link]

Where,
http or https: It is the starting point of the URL that specifies the protocol to be used for communication.

ALL RIGHTS RESERVED TO SVTI 104


Localhost: The localhost is the address of the server. When we run our application locally, it is called
localhost; if we deployed our project over the web, then it is accessed by using the domain name like
"[Link]". The domain name maps the server to IP addresses.
8080: This is the port number for the local server; it is optional and may differ in different machines. If
we do not manually type the port number in the URL, then by default, the request goes to the default port
of the protocol. Usually, the port no between 0 to 1023 are reserved for some well-known services such
as HTTP, HTTPS, FTP, etc.
Enterprise JavaBeans
EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems to develop
secured, robust and scalable distributed applications.
To get information about distributed applications, visit RMI Tutorial first.
To run EJB application, you need an application server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
 life cycle management,
 security,
 transaction management, and
 object pooling.
EJB application is deployed on the server, so it is called server side component also.

Difference between JDK, JRE, and JVM


EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from Java Bean,
RMI and Web Services.

When use Enterprise Java Bean?


 Application needs Remote Access. In other words, it is distributed.
 Application needs to be scalable. EJB applications supports load balancing, clustering and fail-over.
 Application needs encapsulated business logic. EJB application is separated from presentation and
persistent layer.

Types of Enterprise Java Bean


There are 3 types of enterprise bean in java.
1. Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice client.

2. Message Driven Bean


Like Session Bean, it contains the business logic but it is invoked by passing message.

3. Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced with JPA
(Java Persistent API).

Additional J2EE
J2EE (Java Enterprise Edition ) is a platform-independent, Java-centric environment from Sun for
developing, building and deploying Web-based enterprise applications online. The J2EE platform consists
ALL RIGHTS RESERVED TO SVTI 105
of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-
based applications. Core java is the basic java programming and is called as the J2SE(Java standard
edition.)This is basically used to develop standalone programs. Based on this sun had released the
J2EE(Java enterprise edition.)This is basically used to develop the enterprise applications and also web
applications.J2EE consists of SERVLETS,JSP,JDBC,EJB.

POJO
POJO in Java stands for Plain Old Java Object. It is an ordinary object, which is not bound by any special
restriction. The POJO file does not require any special classpath. It increases the readability & re-usability
of a Java program. POJOs are now widely accepted due to their easy maintenance. They are easy to read
and write. A POJO class does not have any naming convention for properties and methods. It is not tied
to any Java Framework; any Java Program can use it.

The term POJO was introduced by Martin Fowler ( An American software developer) in 2000. It is
available in Java from the EJB 3.0 by sun microsystem.
Generally, a POJO class contains variables and their Getters and Setters. The POJO classes are similar to
Beans as both are used to define the objects to increase the readability and re-usability. The only difference
between them that Bean Files have some restrictions but, the POJO files do not have any special
restrictions.

Example:
POJO class is used to define the object entities. For example, we can create an Employee POJO class to
define its objects.
Below is an example of Java POJO class:
[Link]:
// POJO class Exmaple
package [Link];
public class Employee {
private String name;
private String id;
private double sal;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getId() {
return id;
}
public void setId(String id) {
[Link] = id;
}
public double getSal() {

ALL RIGHTS RESERVED TO SVTI 106


return sal;
}
public void setSal(double sal) {
[Link] = sal;
} }

The above employee class is an example of an employee POJO class. If you are working on Eclipse, you
can easily generate Setters and Getters by right click on the Java Program and navigate to Source->
Generate Getters and Setters.

Right-click on the Java Program and Select Generate Getters and Setters.

Now, click on the Generate option given at the bottom of the Generate window. It will auto-generate
setters and getters.

Dependency Injection
The way we usually solve this problem is to use a technique called dependency injection. It’s not a
technique unique to Java, but because of the aforementioned issues, Java is in particularly dire need of it.
Dependency injection simply means receiving collaborators as constructor parameters instead of fetching
them ourselves. So Payroll would look like this instead:

public class Payroll {


...

EmployeeDatabase mEmployeeDatabase;

public Payroll(EmployeeDatabase employeeDatabase) {


mEmployeeDatabase = employeeDatabase;
}

public long getWithholding(long payInDollars) {


...

ALL RIGHTS RESERVED TO SVTI 107


return withholding;
}

public long getAfterTaxPay(Employee employee) {


long basePay = [Link](employee);
long withholding = getWithholding(basePay);

return basePay - withholding;


} }

JAVA ANNOTATIONS
Basically, an annotation is created based on Java interface. The following example shows how to declare
a simple annotation, named myAnnotation:

@interface MyAnnotation {
String str();
int val();
}

The symbol of @ preceding the keyword interface indicates this is an annotation type.
The myAnnotation consists solely of method declarations. However, it is not necessary to provide bodies
for these methods since Java implements these methods. All annotation types are automatically extended
from the annotation interface, which is a member of [Link].
After myAnnotation is defined, it may be used to annotate something. Any type of declaration may be
annotated by it. For examples, classes, methods, fields, parameters, and enum constants may be annotated.
Even an annotation may be annotated. In all cases the annotation precedes the rest of the declaration.
@myAnnotation(str = "Example", val = 1)
public static void myMethod() { ... }

To use the annotation, we need to put @ before the annotation name, myAnnotation. The member of the
annotation is given value by assignment to the member name. For example, str is given value
of "Example". Note that, because there are no parentheses, the assignment is more like a member field
assignment.

Java EE
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is currently
known as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard Edition). The Java
EE provides a platform for developers with enterprise features such as distributed computing and web
services. Java EE applications are usually run on reference run times such as microservers or application
servers. Examples of some contexts where Java EE is used are e-commerce, accounting, banking
information systems.

Specifications of Java EE
Java EE has several specifications which are useful in making web pages, reading and writing from
database in a transactional way, managing distributed queues. The Java EE contains several APIs which
have the functionalities of base Java SE APIs such as Enterprise JavaBeans, connectors, Servlets, Java
Server Pages and several web service technologies.

ALL RIGHTS RESERVED TO SVTI 108


1. Web Specifications of Java EE
Servlet- This specification defines how you can manage HTTP requests either in a synchronous or
asynchronous way. It is low level, and other specifications depend on it WebSocket- WebSocket is a
computer communication protocol, and this API provides a set of APIs to facilitate WebSocket
connections.
Java Server Faces- It is a service which helps in building GUI out of components.
Unified Expression Language- It is a simple language which was designed to facilitate web application
developers.

2. Web Service Specifications of Java EE


Java API for RESTful Web Services- It helps in providing services having Representational State Transfer
schema.
Java API for JSON Processing- It is a set of specifications to manage the information provided in JSON
format.
Java API for JSON Binding- It is a set of specifications provide for binding or parsing a JSON file into
Java classes.
Java Architecture for XML Binding- It allows binding of xml into Java objects.
Java API for XML Web Services- SOAP is an xml based protocol to access web services over http. This
API allows you to create SOAP web services.

3. Enterprise Specifications of Java EE


Contexts and Dependency Injection- It provides a container to inject dependencies as in Swing.
Enterprise JavaBean- It is a set of lightweight APIs that an object container possesses in order to provide
transactions, remote procedure calls, and concurrency control.
Java Persistence API- These are the specifications of object-relational mapping between relational
database tables and Java classes.
Java Transaction API- It contains the interfaces and annotations to establish interaction between
transaction support offered by Java EE. The APIs in this abstract from low-level details and the interfaces
are also considered low-level.
Java Message Service- It provides a common way to Java program to create, send and read enterprise
messaging system's messages.

ALL RIGHTS RESERVED TO SVTI 109


4. Other Specifications of Java EE
Validation- This package contains various interfaces and annotations for declarative validation support
offered by Bean Validation API.
Batch applications- It provides the means to run long running background tasks which involve a large
volume of data and which need to be periodically executed.
Java EE Connector Architecture- This is a Java-based technological solution for connecting Java servers
to Enterprise Information System.

ALL RIGHTS RESERVED TO SVTI 110


CHAPTER 12

JDBC
Introduction
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with
the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with
the database. There are four types of JDBC drivers:

1. JDBC-ODBC Bridge Driver,


2. Native Driver,
3. Network Protocol Driver, and
4. Thin Driver
JDBC Architecture

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete and fetch data from the database. It is like Open Database Connectivity
(ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the
X/Open SQL Call Level Interface. The [Link] package contains classes and interfaces for JDBC API.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of
thin driver.

ALL RIGHTS RESERVED TO SVTI 111


In Java 8, the JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
 Easy to use.
 Can be easily connected to any database.

Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.

Advantage:
 Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.

ALL RIGHTS RESERVED TO SVTI 112


3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
 No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.

ALL RIGHTS RESERVED TO SVTI 113


Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following informations for the
mysql database:
 Driver class: The driver class for the mysql database is [Link].
 Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is
the server name on which mysql is running, we may also use IP address, 3306 is the port number
and sonoo is the database name. We may use any database, in such case, we need to replace the
sonoo with our database name.
 Username: The default username for the mysql database is root.
 Password: It is the password given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create database
first.
o create database sonoo;
o use sonoo;
o create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database


In this example, sonoo is the database name, root is the username and password both.

Features of Java
import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
} }

The above example will fetch all the records of emp table.

To connect java application with the mysql database, [Link] file is required to be loaded.
download the jar file [Link]

ALL RIGHTS RESERVED TO SVTI 114


Two ways to load the jar file:
Paste the [Link] file in jre/lib/ext folder
Set classpath

1) Paste the [Link] file in JRE/lib/ext folder:


Download the [Link] file. Go to jre/lib/ext folder and paste the jar file here.

2) Set classpath:
There are two ways to set the classpath:
temporary
permanent

How to set the temporary classpath


open command prompt and write:
C:>set classpath=c:\folder\[Link];.;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name write classpath and in variable value
paste the path to the [Link] file by appending [Link];.; as C:\folder\mysql-
[Link];.;

To start developing with JDBC, you should setup your JDBC environment by following the steps shown
below. We assume that you are working on a Windows platform.
Install Java
Java SE is available for download for free. To download click here, please download a version compatible
with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have
installed Java on your machine, you would need to set environment variables to point to correct installation
directories.

Setting Up the Path for Windows


Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example,
if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin
Install Database
The most important thing you will need, of course is an actual running database with a table that you can
query and modify.
Install a database that is most suitable for you. You can have plenty of choices and most common are −
MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We
recommend downloading the full Windows installation.

ALL RIGHTS RESERVED TO SVTI 115


In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are
GUI based tools that will make your development much easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory.
For the purpose of this tutorial we will assume that you have installed the driver at C:\Program
Files\MySQL\mysql-connector-java-5.1.8.
Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-
[Link]. Your driver version may vary based on your installation.

Set Database Credential


When we install MySQL database, its administrator ID is set to root and it gives provision to set a
password of your choice.
Using root ID and password you can either create another user ID and password, or you can use root ID
and password for your JDBC application.
There are various database operations like database creation and deletion, which would need administrator
ID and password.
For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password.
If you do not have sufficient privilege to create new users, then you can ask your Database Administrator
(DBA) to create a user ID and password for you.

Create Database
To create the TUTORIALSPOINT database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Note − The path to [Link] may vary depending on the install location of MySQL on your system.
You can also check documentation on how to start and stop your database server.

Step 2
Start the database server by executing the following command, if it is already not running.
C:\Program Files\MySQL\bin>mysqld
C:\Program Files\MySQL\bin>

Step 3
Create the TUTORIALSPOINT database by executing the following command −
C:\Program Files\MySQL\bin> mysqladmin create TUTORIALSPOINT -u guest -p
Enter password: ********
C:\Program Files\MySQL\bin>

Create Table
To create the Employees table in TUTORIALSPOINT database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>

ALL RIGHTS RESERVED TO SVTI 116


C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u guest -p
Enter password: ********
mysql>

Step 3
Create the table Employees as follows −
mysql> use TUTORIALSPOINT;
mysql> create table Employees
-> (
-> id int not null,
-> age int not null,
-> first varchar (255),
-> last varchar (255)
-> );
Query OK, 0 rows affected (0.08 sec)
mysql>

Create Data Records


Finally you create few records in Employee table as follows −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');


Query OK, 1 row affected (0.00 sec)

mysql>
For a complete understanding on MySQL database, study the MySQL Tutorial.
Now you are ready to start experimenting with JDBC. Next chapter gives you a sample example on JDBC
Programming.

ALL RIGHTS RESERVED TO SVTI 117


JDBC Resources
To build and execute JDBC applications, Enterprise Developer must have access to a certain set of
resources. The specific resources required vary depending on the type of database and type of application
server used by the application.
To store, organize, and retrieve data, most applications use relational databases. J2EE applications access
relational databases through the JDBC API. Before an application can access a database, it must get a
connection.
At runtime, here’s what happens when an application connects to a database:
The application gets the JDBC resource (data source) associated with the database by making a call
through the JNDI API.
Given the resource’s JNDI name, the naming and directory service locates the JDBC resource. Each JDBC
resource specifies a connection pool.
Via the JDBC resource, the application gets a database connection.
Behind the scenes, the application server retrieves a physical connection from the connection pool that
corresponds to the database. The pool defines connection attributes such as the database name (URL),
user name, and password.
Now that it’s connected to the database, the application can read, modify, and add data to the database.
The applications access the database by making calls to the JDBC API. The JDBC driver translates the
application’s JDBC calls into the protocol of the database server.
When it’s finished accessing the database, the application closes the connection.
The application server returns the connection to the connection pool. Once it’s back in the pool, the
connection is available for the next application.

JDBC Exception handling


Exception handling allows you to handle exceptional conditions such as program-defined errors in a
controlled fashion.
When an exception condition occurs, an exception is thrown. The term thrown means that current program
execution stops, and the control is redirected to the nearest applicable catch clause. If no applicable catch
clause exists, then the program's execution ends.
JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common
exception you'll deal with is [Link].
SQLException Methods
An SQLException can occur both in the driver and the database. When such an exception occurs, an object
of type SQLException will be passed to the catch clause.

ALL RIGHTS RESERVED TO SVTI 118


The passed SQLException object has the following methods available for retrieving additional
information about the exception −
Method Description

getErrorCode( ) Gets the error number associated with the exception.

getMessage( ) Gets the JDBC driver's error message for an error, handled by the driver
or gets the Oracle error number and message for a database error.

getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful
information is returned from this method. For a database error, the five-
digit XOPEN SQLstate code is returned. This method can return null.

getNextException( ) Gets the next Exception object in the exception chain.

printStackTrace( ) Prints the current exception, or throwable, and it's backtrace to a


standard error stream.

printStackTrace(PrintStream Prints this throwable and its backtrace to the print stream you specify.
s)

printStackTrace(PrintWriter Prints this throwable and it's backtrace to the print writer you specify.
w)

By utilizing the information available from the Exception object, you can catch an exception and continue
your program appropriately. Here is the general form of a try block −
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}

Example
Study the following example code to understand the usage of try....catch...finally blocks.
import [Link];
import [Link];
import [Link];
import [Link];

ALL RIGHTS RESERVED TO SVTI 119


public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "{call getEmpName (?, ?)}";

public static void main(String[] args) {


// Open a connection
try(Connection conn = [Link](DB_URL, USER, PASS);
CallableStatement stmt = [Link](QUERY);
){
// Bind values into the parameters.
[Link](1, 1); // This would set ID
// Because second parameter is OUT so register it
[Link](2, [Link]);
//Use execute method to run stored procedure.
[Link]("Executing stored procedure..." );
[Link]();
//Retrieve employee name with getXXX method
String empName = [Link](2);
[Link]("Emp Name with ID: 1 is " + empName);
} catch (SQLException e) {
[Link]();
}
}
}

Now, let us compile the above example as follows −


C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result if there is no problem, otherwise the
corresponding error would be caught and error message would be displayed −
C:\>java JDBCExample
Executing stored procedure...
Emp Name with ID: 1 is Zara
C:\>
Try the above example by passing wrong database name or wrong username or password and check the
result.

ALL RIGHTS RESERVED TO SVTI 120


CHAPTER 13

PERFORMING BASIC CRUD OPERATIONS USING JDBC


Executing Static SQL Statements
In a database, you can execute SQL statements statically or dynamically. Static execution requires
configuring the database to run an SQL statement but delivers more consistent performance. Dynamic
execution of SQL statements is more flexible because it does not require any special preparation on the
database. Static SQL refers to those SQL statements which are fixed and can be hard coded into the
application. As static sqls are fixed queries, these statements can be analysed and optimized and do not
require any specific handling for security purpose.

Sr. No. Key Static SQL

Database Access In Static SQL, database access procedure is predetermined in the


1
statement.

2 Efficiency Static SQL statements are more faster and efficient.

3 Compilation Static SQL statements are compiled at compile time.

Application Plan Application Plan parsing, validation, optimization and generation are
4
compile time activities.

5 Use Cases Static SQL is used in case of uniformly distributed data.

Dynamic Statements like EXECUTE IMMEDIATE, EXECUTE, PREPARE are


6
Statements not used.

7 Flexibility Static SQL is less flexible.

Iterating Through Result Sets


The ResultSet object are basically three types. The iteration depends on the types of the result set object
1. Forward Only.- In this type of result set object we move only from start to end i.e in forward direction.
[Link] sensitive- This type of object have the capability to move the cursor in both the direction. i.e it
us capable for scrolling.
3. Scroll insensitive. This type of result set object is not capable for scrolling. i.e the cursor moves in
only one direction.

Example- [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];

ALL RIGHTS RESERVED TO SVTI 121


import [Link];
public class ScrollSensitiveExample {
public static void main(String[] args) throws SQLException {
Connection connection = null; // connection reference variable for// getting
// connection
Statement statement = null; // Statement reference variable for query// Execution
ResultSet resultSet = null; // ResultSet reference variable for saving
// query// result
String conUrl = "jdbc:mysql://localhost:3306/";
String driverName = "[Link]";
String databaseName = "student";
String usrName = "root";
String usrPass = "root";
try { // Loading Driver
[Link](driverName);}
catch (ClassNotFoundException e) {
[Link]([Link]());}
try { // Getting Connection
connection = [Link](conUrl + databaseName,
usrName, usrPass);// Getting reference to connection object and Setting ResultSet
// object types
statement = connection
.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);// creating Query String
String query = "SELECT * FROM student";// excecuting query
resultSet = [Link](query);// Getting Results ifrom ForWard only direction
[Link]("From First to lat ");
while ([Link]()) {
[Link]("Roll No " + [Link]("RollNo")
+ ", Name " + [Link]("Name") + ", Course "
+ [Link]("Course") + ", Address "
+ [Link]("Address"));}
[Link]("Printing lastValue ");
[Link]();// Didplaying data of tables
[Link]("Roll No " + [Link]("RollNo")
+ ", Name " + [Link]("Name") + ", Course "
+ [Link]("Course") + ", Address "
+ [Link]("Address"));// [Link]();
[Link]();
[Link]("From Last to first\n");
while ([Link]()) {
[Link]("Roll No " + [Link]("RollNo")
+ ", Name " + [Link]("Name") + ", Course "
+ [Link]("Course") + ", Address "
+ [Link]("Address"));}}

ALL RIGHTS RESERVED TO SVTI 122


catch (Exception e) { [Link]([Link]());}
finally { // Closing connection
[Link]();
[Link]();
[Link]();}}}

When you run this application it will display message as shown below:

From First to lat


Roll No 1, Name Rajan, Course MCA, Address Motihari
Roll No 3, Name Rohan, Course MCA, Address Mumbai
Printing lastValue
Roll No 3, Name Rohan, Course MCA, Address Mumbai
From Last to first

Roll No 3, Name Rohan, Course MCA, Address Mumbai


Roll No 1, Name Rajan, Course MCA, Address Motihari

Understanding Scrollable Result Sets


By default, result sets are not scrollable or updatable. If you use the following code:
String sql = "SELECT * FROM student";

Statement statement = [Link]();


ResultSet result = [Link](sql);
The ResultSet object returned is not scrollableor updatable. To obtain a scrollable result set, you must
create a different Statement object with the following method:
Statement statement = [Link](int resultSetType, int resultSetConcurrency);
For a prepared statement, us the following method:
PreparedStatement statement = [Link](
String sql, int resultSetType, int resultSetConcurrency);

Scrollable ResultSet
Let’s first make the ResultSet object scrollable. Scrollable means that once the ResultSet object has been
created, we can traverse through fetched records in any direction, forward and backward, as we like. This
provides the ability to read the last record, first record, next record, and the previous record.
package [Link];
import [Link].*;
public class App
{
static final String JDBC_DRIVER =
"[Link]";
static final String DB_URL =
"jdbc:mysql://localhost:3306/employees";

ALL RIGHTS RESERVED TO SVTI 123


static final String USER = "root";
static final String PASS = "secret";
static final String SQL =
"SELECT * FROM employees ORDER BY first_name";

public static void main( String[] args )


{
Connection connection = null;
ResultSet rs = null;
try {
[Link](JDBC_DRIVER);
connection = [Link]
(DB_URL, USER, PASS);
[Link]("n1. Connection established");
}catch(Exception ex) {
[Link]();
}

try (PreparedStatement pstmt =


[Link](SQL,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);){
[Link]("n2.
Executing SQL query...");
rs = [Link]();
[Link]("n3.
ResultSet object created successfully.");
[Link]("n4.
Now some RecordSet scrolling starts...");

[Link]();
show(rs);
[Link]();
show(rs);
[Link]();
[Link]();
show(rs);
[Link]();
show(rs);

[Link]("nn5. That's all.


RecordSet scrolling ends.");
}catch(SQLException ex){
[Link]();
}finally{

ALL RIGHTS RESERVED TO SVTI 124


try {
[Link]();
}catch(SQLException ex){
}
}
}
public static void show(ResultSet rs) throws
SQLException{
[Link]
("n--------------------------------"+
"-------------------------------------");
[Link]("n%7d | %10s | %10s | %s
| %s | %s ",[Link]("emp_no"),
[Link]("first_name"),
[Link]("last_name"),
[Link]("birth_date").toString(),
[Link]("hire_date"),
[Link]("gender"));
[Link]
("n---------------------------------"+
"------------------------------------");
}
}
Output
Connection established.
Executing SQL query…
ResultSet object created successfully.
Now, some RecordSet scrolling starts…
-------------------------------------------------------------
497615 | Aamer | McDermid | 1954-11-18 | 1985-04-24 | M
-------------------------------------------------------------
484995 | Zvonko | Lakshmanan | 1964-11-04 | 1992-12-04 | M
-------------------------------------------------------------
482000 | Zvonko | Cannata | 1960-11-23 | 1986-08-13 | M
-------------------------------------------------------------
-------------------------------------------------------------
483497 | Zvonko | Pollacia | 1961-12-26 | 1985-08-01 | M
-------------------------------------------------------------
That’s all. RecordSet scrolling ends.
Note that the scrollable ResultSet object is the result of the execution of the executeQuery() method
obtained through the instance of Statement or PreparedStatement. The type of ResultSet object we like to
create must be explicitly declared to the Statement object through defined scroll type constants.
ResultSet.TYPE_FORWARD_ONLY: This is the default type.
ResultSet.TYPE_SCROLL_INSENSITIVE: Enables back and forth movement, but is insensitive
to ResultSet updates.

ALL RIGHTS RESERVED TO SVTI 125


ResultSet.TYPE_SCROLL_SENSITIVE: Enables back and forth movement, but is sensitive
to ResultSet updates.
There are other constants used, such as CONCUR_READ_ONLY, which means that the ResultSet is not
updatable. There is another constant, CONCUR_UPDATABLE, which signifies the opposite, meaning
the ResultSet is updatable.
Updatable ResultSet
Creating an updatable ResultSet means that the record it points to is not only be traversable but also be
updatable. The changes will immediately be persisted in the database and reflected by the ResultSet object
in real time.
package [Link];
import [Link].*;
public class App
{
static final String JDBC_DRIVER =
"[Link]";
static final String DB_URL =
"jdbc:mysql://localhost:3306/employees";
static final String USER = "root";
static final String PASS = "secret";
static final String SQL =
"SELECT * FROM employees WHERE emp_no = ?";
public static void main( String[] args )
{
Connection connection = null;
ResultSet rs = null;
long emp_no = 484995;
try {
[Link](JDBC_DRIVER);
connection = [Link]
(DB_URL, USER, PASS);
[Link]("n1.
Connection established");
}catch(Exception ex) {
[Link]();
}
try(PreparedStatement pstmt =
[Link](SQL,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);){
[Link](1,emp_no);
[Link]("n2.
Executing SQL query...");
rs = [Link]();
[Link]("n3.
ResultSet object created successfully.");

ALL RIGHTS RESERVED TO SVTI 126


while([Link]()){
show(rs);
String fname = [Link]("first_name");
[Link]("n4.
Updating name "+fname+" to Subham");
[Link]("first_name", "Subham");
[Link]();
}
[Link]("nn5.
Record updated. See below.");
[Link]();
show(rs);
}catch(SQLException ex){
[Link]();
}finally{
try {
[Link]();
[Link]();
}catch(SQLException ex){
}
}
}
public static void show(ResultSet rs)
throwsSQLException{
[Link]
("n--------------------------------"+
"-------------------------------------");
[Link]("n%7d | %10s | %10s | %s
| %s | %s ",[Link]("emp_no"),
[Link]("first_name"),
[Link]("last_name"),
[Link]("birth_date").toString(),
[Link]("hire_date"),
[Link]("gender"));
[Link]("n---------"+"--------");
}}

The updatable ResultSet is particularly useful when we want to update certain values after doing some
comparison by traversing back and forth through the fetched records. The process of creation is similar to
the preceding program, but the ResultSet constants used here
are TYPE_SCROLL_SENSITIVE and CONCUR_UPDATABLE.

ALL RIGHTS RESERVED TO SVTI 127


Prepared Statement
It takes time for a database to parse an SQL string, and create a query plan for it. A query plan is an
analysis of how the database can execute the query in the most efficient way.
If you submit a new, full SQL statement for every query or update to the database, the database has to
parse the SQL and for queries create a query plan. By reusing an existing PreparedStatement you can reuse
both the SQL parsing and query plan for subsequent queries. This speeds up query execution, by
decreasing the parsing and query planning overhead of each execution.

There are two levels of potential reuse for a PreparedStatement.


 Reuse of PreparedStatement by the JDBC driver.
 Reuse of PreparedStatement by the database.

First of all, the JDBC driver can cache PreparedStatement objects internally, and thus reuse
the PreparedStatement objects. This may save a little of the PreparedStatement creation time.

Second, the cached parsing and query plan could potentially be reused across Java applications, for
instance application servers in a cluster, using the same database.

Here is a diagram illustrating the caching of statements in the database:

The caching of PreparedStatement's in the database.

Retrieving Data Using Prepared Statement


To retrieve data from a table using a SELECT statement with parameter markers, you use
the [Link] method.

Example
The following code demonstrates how to retrieve rows from the employee table for a specific employee.
The numbers to the right of selected statements correspond to the previously-described [Link] 1.

ALL RIGHTS RESERVED TO SVTI 128


Example of using [Link]
String empnum, phonenum;
Connection con;
PreparedStatement pstmt;
ResultSet rs;

pstmt = [Link](
"SELECT EMPNO, PHONENO FROM EMPLOYEE WHERE EMPNO=?");
// Create a PreparedStatement object
[Link](1,"000010"); // Assign value to input parameter

rs = [Link](); // Get the result table from the query


while ([Link]()) { // Position the cursor
empnum = [Link](1); // Retrieve the first column value
phonenum = [Link](2); // Retrieve the first column value
[Link]("Employee number = " + empnum +
"Phone number = " + phonenum);
// Print the column values
}
[Link](); // Close the ResultSet
[Link](); // Close the PreparedStatement

JDBC Execute INSERT Statement Example


Let’s write code to insert a new record into the table Users with following details:

username: bill
password: secretpass
fullname: Bill Gates
email: [Link]@[Link]
Here’s the code snippet:
1 String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";
2
3 PreparedStatement statement = [Link](sql);
4 [Link](1, "bill");
5 [Link](2, "secretpass");
6 [Link](3, "Bill Gates");
7 [Link](4, "[Link]@[Link]");
8
9 int rowsInserted = [Link]();
10 if (rowsInserted > 0) {
11 [Link]("A new user was inserted successfully!");
12 }

ALL RIGHTS RESERVED TO SVTI 129


In this code, we create a parameterized SQL INSERT statement and create a PreparedStatement from
the Connection object. To set values for the parameters in the INSERT statement, we use
the PreparedStatement‘s setString() methods because all these columns in the table Users are of type
VARCHAR which is translated to String type in Java. Note that the parameter index is 1-based (unlike 0-
based index in Java array).

The PreparedStatement interface provides various setXXX() methods corresponding to each data type, for
example:

setBoolean(int parameterIndex, boolean x)


setDate(int parameterIndex, Date x)
setFloat(int parameterIndex, float x)

And so on. Which method to be used is depending on the type of the corresponding column in the database
table.

Finally we call the PreparedStatement’s executeUpdate() method to execute the INSERT statement. This
method returns an update count indicating how many rows in the table were affected by the query, so
checking this return value is necessary to ensure the query was executed successfully. In this
case, executeUpdate() method should return 1 to indicate one record was inserted.

JDBC Executing UPDATE Statement Example


The following code snippet will update the record of “Bill Gates” as we inserted previously:
1 String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";
2
3 PreparedStatement statement = [Link](sql);
4 [Link](1, "123456789");
5 [Link](2, "William Henry Bill Gates");
6 [Link](3, "[Link]@[Link]");
7 [Link](4, "bill");
8
9 int rowsUpdated = [Link]();
10 if (rowsUpdated > 0) {
11 [Link]("An existing user was updated successfully!");
12 }
This code looks very similar to the INSERT code above, except the query type is UPDATE.

JDBC Execute DELETE/Remove Statement Example


The following code snippet will delete a record whose username field contains “bill”:
1 String sql = "DELETE FROM Users WHERE username=?";
2 PreparedStatement statement = [Link](sql);
3 [Link](1, "bill");
4 int rowsDeleted = [Link]();
5 if (rowsDeleted > 0) {

ALL RIGHTS RESERVED TO SVTI 130


6 [Link]("A user was deleted successfully!");
7 }

So far we have one through some examples demonstrating how to use JDBC API to execute SQL INSERT,
SELECT, UPDATE and DELETE statements. The key points to remember are:

Using a Statement for a static SQL query.


Using a PreparedStatement for a parameterized SQL query and using setXXX() methods to set values for
the parameters.
Using execute() method to execute general query.
Using executeUpdate() method to execute INSERT, UPDATE or DELETE query
Using executeQuery() method to execute SELECT query.
Using a ResultSet to iterate over rows returned from a SELECT query, using its next() method to advance
to next row in the result set, and using getXXX() methods to retrieve values of columns.

ALL RIGHTS RESERVED TO SVTI 131

You might also like