0% found this document useful (0 votes)
127 views83 pages

Java Notes 2024

Java note

Uploaded by

justcallmemrx9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
127 views83 pages

Java Notes 2024

Java note

Uploaded by

justcallmemrx9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 83

UNIT - 1

History of Java
Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time.
The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for
digital devices such as set-top boxes, televisions, etc. However, it was
suited for internet programming. After some time Java technology was
joined by Netscape.

The objective to create Java Programming Language was it should be


"Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Object-Oriented, Interpreted, and Dynamic".

Java was developed in Sun Microsystem by James Ghosling, Patrick


Naughton, Mike Sheridan in 1991. It took 18 months to develop the first
working version. James Ghosling is also known as the Father of Java.

Initially, Java was called "Greentalk" by James Gosling and at that time
the file extension was .gt.

Later on Oak was developed as a part of the Green Team project. Oak is a
symbol for strength and Oak is also a national tree in many countries like
the USA, Romania etc.

Oak was renamed as Java in 1995 because Oak was already a trademark
by Oak Technologies. Before selecting the Java word the team suggested
many names like dynamic, revolutionary, Silk, jolt, DNA, etc.

Java is an island in Indonesia, here the first coffee was produced or we


call Java coffee. Java coffee is a type of espresso bean. James gosling
chose this name while having coffee near his office.

Features of Java

The features of Java are also known as java buzzwords. They are:

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Compiled and Interpreted
9. High Performance
10. Multithreaded
11. Distributed
1

12. Dynamic
Page
Simple:

Java is very easy to learn, and its syntax is simple, clean and easy to
understand.

Object-oriented:

Java is an object-oriented programming language. Everything in Java is


an object.

Portable:

Java is portable because it facilitates you to carry the Java bytecode to


any platform. It doesn't require any implementation.

Platform Independent:

Java is platform independent because it is different from other languages


like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language.

Secured:

Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

Robust

Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java
Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
o There are exception handling and the type checking mechanism in
Java. All these points make Java robust.

Architecture-neutral:

Java is architecture neutral because there are no implementation


dependent features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit


architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Compiled and Interpreted:

First of all The Program of java is compiled then after Compilation it


2

creates Bytes Codes rather than Machine Language.


Page
Then After Bytes Codes are converted into the Machine Language is
converted into the Machine Language with the help of the Interpreter.

High-performance:

Java is faster than other traditional interpreted programming languages


because Java bytecode is "close" to native code.

Multithreaded:

Java allows multiple concurrent threads of execution to be active at once.


This means that you could be listening to an audio clip while scrolling the
page and in the background downloading an image.

Distributed:

Java is distributed because it facilitates users to create distributed


applications in Java. This feature of Java makes us able to access files by
calling the methods from any machine on the internet.

Dynamic:

Java is a dynamic language. It supports dynamic loading of classes. It


means classes are loaded on demand.

C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system Java is mainly used for application
programming. programming.
C++ supports Java doesn't support the goto
the goto statement. statement.
C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It can
be achieved by interfaces in java.
C++ supports operator Java doesn't support operator
overloading. overloading.
C++ supports pointers. You can Java supports pointer internally.
write pointer program in C++. However, you can't write the
pointer program in java.
C++ supports both call by value Java supports call by value only.
and call by reference. There is no call by reference in
java.
C++ supports structures and Java doesn't support structures
unions. and unions.

C++ doesn't support Java supports documentation


documentation comment. comment (/** ... */) to create
3

documentation for java source


Page

code.
C++ supports virtual keyword Java has no virtual keyword. We
so that we can decide whether can override all non-static
or not override a function. methods by default.

First Java Program


To create a simple java program, you need to create a class that contains
the main method.

For executing any java program, you need to

o Install the JDK(any version)


o Set path of the jdk/bin directory.
o Create the java program
o Compile and run the java program

Creating Hello World Example:


Simple.java
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
To compile: javac Simple.java
To execute: java Simple

Output: Hello Java

What is the meaning of class, public, static, void, main, String[],


System.out.println()?

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


o public keyword is an access modifier which represents visibility. It
means it is visible to all.
o 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.
o void is the return type of the method. It means it doesn't return
any value.
o main represents the starting point of the program.
o String[] args is used for command line argument.
o System.out.println() is used to print statement. Here, System is
a class, out is the object of PrintStream class, println() is the
method of PrintStream class.
4
Page
What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not
interact with OS) and converts the java code into bytecode.

What happens at runtime?

At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files.


Bytecode Verifier: checks the code fragments for illegal code that can
violate access right to objects.
Interpreter: read bytecode stream then execute the instructions.
5
Page
Java Virtual Machine (JVM) & its Architecture

What is JVM?

JVM (Java Virtual Machine) acts as a run-time engine to run Java


applications. JVM is the one that actually calls the main method present
in a java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This
means a programmer can develop Java code on one system and can
expect it to run on any other Java enabled system without any
adjustment. This is all possible because of JVM.

The JVM performs following operation:

• Loads code
• Verifies code
• Executes code
• Provides runtime environment

JVM Architecture

1. Classloader : Classloader is a subsystem of JVM that is used to load


class files.

2. Class(Method) Area : Class(Method) Area stores per-class structures


such as the runtime constant pool, field and method data, the code for
methods.

3. Heap : It is the runtime data area in which objects are allocated.

4. Stack : Java Stack stores frames.It holds local variables and partial
6

results, and plays a part in method invocation and return.


Page
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is
destroyed when its method invocation completes.

5. Program Counter Register : PC (program counter) register. It


contains the address of the Java virtual machine instruction currently
being executed.

6. Native Method Stack : It contains all the native methods used in the
application.

7. Execution Engine : It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler.

Java Keywords:
keywords are also known as reserved words. These are predefined words
by Java so it cannot be used as a variable or object name.

Abstract Assert boolean break byte


Case Catch char class const
continue Default do double else
Enum Extends final finally float
For Goto if implements import
instanceof Int interface long native
New Package private protected public
Return Short static strictfp super
Switch Synchronized this throw throws
transient Try void volatile While

Keywords goto and const are reserved, but never used.

Variable
Variable is name of reserved area allocated in memory. In other words, it
is a name of memory location.

It is a combination of "vary + able" that means its value can be changed.

int x=50;//Here x is variable

Types of Variables

There are three types of variables in Java:


7
Page

o local variable
o instance variable

o 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.

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 instance variable.

It is not declared as static.

It is called instance variable because its value is instance specific and is


not shared among instances.

3) Static variable

A variable which is declared as static is called static variable.

It cannot be local.

You can create a single copy of static variable and share among all the
instances of the class. Memory allocation for static variable happens only
once when the class is loaded in the memory.

Example:

class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}

Data Types in Java

Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.

2. Non-primitive data types: The non-primitive data types


include Classes, Interfaces, and Arrays.
8
Page
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.

There are 8 types of primitive data types:

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

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive
into object and object into primitive.

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.

The eight classes of the java.lang package are known as wrapper classes
in Java. The list of eight wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Autoboxing:

The automatic conversion of primitive data type into its corresponding


wrapper class is known as autoboxing.

For example, byte to Byte, char to Character, int to Integer, long to Long,
float to Float, boolean to Boolean, double to Double, and short to Short.
9
Page
Since Java 5, we do not need to use the valueOf() method of wrapper
classes to convert the primitive into objects.

//Java program to convert primitive into objects

//Autoboxing example of int to Integer

public class WrapperExample1


{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer
explicitly
Integer j=a; //autoboxing, now compiler will write
Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}

OUTPUT

20 20 20

Unboxing

The automatic conversion of wrapper type into its corresponding primitive


type is known as unboxing. It is the reverse process of autoboxing.

Since Java 5, we do not need to use the intValue() method of wrapper


classes to convert the wrapper type into primitives.

//Java program to convert object into primitives

//Unboxing example of Integer to int

public class WrapperExample2


{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(10);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}
}
10

Output
Page

10 10 10
Operators in Java
Operator is a symbol which is used to perform operations. For example:
+, -, *, / etc.

There are many types of operators in Java which are given below:

• Arithmetic operators

• Relation operators

• Logical operators

• Bitwise operators

• Assignment operators

• Conditional operators

Type Casting in Java


Casting is a process of changing one type value to another type. In Java,
we can cast one type of value to another type. It is known as type
casting.

In Java, type casting is classified into two types,

• Widening Casting(Implicit)

• Narrowing Casting(Explicitly done)

Widening or Automatic type conversion

Automatic Type casting take place when,


11

• the two types are compatible


Page

• the target type is larger than the source type


Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
OUTPUT

Int value 100


Long value 100
Float value 100.0

Narrowing or Explicit type conversion

When you are assigning a larger type value to a variable of smaller type,
then you need to perform explicit type casting. If we don't perform
casting then compiler reports compile time error.

Example:

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}

OUTPUT

Double value 100.04


Long value 100
Int value 100

Decision Making Statements


Decision making statement used to control the flow of execution of
program depending upon condition, means if condition is true then the
12

block will execute and if condition is false then block will not execute.
Page
Types of Decision Making Statement

In java there are four types of decision making statement.

1. if statements
2. if-else statements
3. if...else if... statement
4. Nested if-else statement
5. Switch statements

The if statement

It is one of the simplest decision-making statement which is used to


decide whether a block of JavaScript code will execute if a certain
condition is true.

Syntax:

if (condition)
{
// block of code will execute if the condition is true
}
If the condition evaluates to true, the code within if statement will
execute, but if the condition evaluates to false, then the code after the
end of if statement (after the closing of curly braces) will execute.

The if….else statement

An if statement can be followed by an optional else statement, which


executes when the Boolean expression is false.

Syntax:
if (condition)
{
// block of code will execute if the condition is true
}
else
{
// block of code will execute if the condition is false
}

If the condition is true, then the statements inside if block will be


executed, but if the condition is false, then the statements of the else
block will be executed.

The if….else if…..else statement

It is used to test multiple conditions. The if statement can have multiple or


zero else if statements and they must be used before using the else
statement. You should always be kept in mind that the else statement must
come after the else if statements.
13
Page
Syntax:

if (condition1)
{
// block of code will execute if condition1 is true
}
else if (condition2)
{
// block of code will execute if the condition1 is false and
condition2 is true
}
else
{
// block of code will execute if the condition1 is false and
condition2 is false
}

The nested if statement

It is an if statement inside an if statement.

Syntax:
if (condition1)
{
Statement 1; //It will execute when condition1 is true
if (condition2)
{
Statement 2; //It will execute when condition2 is true
}
else
{
Statement 3; //It will execute when condition2 is false
}
}

Switch Statement

A switch statement allows a variable to be tested for equality against a


list of values. Each value is called a case, and the variable being switched
on is checked for each case.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
14

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

}
Looping Statement

Loops are used to execute a set of instructions/functions repeatedly when


some conditions become true.

In other words, Looping in Java is defined as performing some lines of


code in an ordered fashion until a condition is false.

There are three types of loops in Java.


o for loop
o while loop
o do-while loop

for loop
Java for loop consists of 3 primary factors which define the loop itself.
These are the initialization statement, a testing condition, an increment or
decrement part for incrementing/decrementing the control variable.

A for loop is useful when you know how many times a task is to be
repeated.

Syntax:

for (initializing statement; testing condition; increment/decrement)


{
//code to be iterated
}

While Loop

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
}

do while loop

The 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 do-while loop is executed at least once because condition is checked


after loop body.
15
Page
Syntax:

do
{
//code to be executed
}
while(condition);

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. The method is executed
only when we call or invoke it.

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.

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:

o Public: The method is accessible by all classes when we use public


specifier in our application.
16

o Private: When we use a private access specifier, the method is


Page

accessible only in the classes in which it is defined.


o Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
o 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.

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. It is enclosed within the pair of curly braces.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

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.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}

Output:

The maximum number is: 9

User-defined Method
17

The method written by the user or programmer is known as a user-


defined method. These methods are modified according to the
Page

requirement.
public class Addition
{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b);
System.out.println("The sum of a and b is = " + c);
}
//user defined method
public static int add(int n1, int n2)
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

Output:

The sum of a and b is = 24

Passing Parameters by Value

While working under calling process, arguments is to be passed. These


should be in the same order as their respective parameters in the method
specification.

Example:
class Main
{
public int addNumbers(int a, int b)
{
int sum = a + b;
return sum;
}
public static void main(String[] args)
{
int num1 = 25;
int num2 = 15;

Main obj = new Main();

int result = obj.addNumbers(num1, num2);


System.out.println("Sum is: " + result);
}
}

Output
18

Sum is: 40
Page
Command line argument
The command line argument is the argument that passed to a program
during runtime.

It is the way to pass argument to the main method in Java. These


arguments store into the String type args parameter which is main
method parameter.

To access these arguments, you can simply traverse the args parameter
in the loop or use direct index value because args is an array of type
String.

For example, if we run a HelloWorld class that contains main method and
we provide argument to it during runtime, then the syntax would be like.

java HelloWorld arg1 arg2 ...

We can pass any number of arguments because argument type is an


array.
Example:
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
Compile: javac cmd.java
Run: java cmd 10 20 30

Output:
10
20
30

BufferedReader Class

Java BufferedReader class is used to read the text from a character-based


input stream. It can be used to read data line by line by readLine()
method. It makes the performance fast. It inherits Reader class.

BufferedReader class declaration:


19

public class BufferedReader extends Reader


Page
BufferedReader class methods:

Method Description

int read() It is used for reading a single character.

String It is used for reading a line of text.


readLine()
boolean It is used to test whether the input stream is ready to be
ready() read.
void reset() It repositions the stream at a position the mark method
was last called on this input stream.
void close() It closes the input stream and releases any of the
system resources associated with the stream.

Example:

import java.io.*;
public class BufferedReaderExample
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name: ");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Output
Enter your name:
Sachin Tendulkar
Welcome Sachin Tendulkar
20
Page
Scanner class

The Scanner class is mainly used to get the user input, and it belongs to
the java.util package.

Java provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter
which is whitespace by default. It provides many methods to read and
parse various primitive values.

Scanner Class Methods:

There are various methods of Scanner class which can be used for
various data types.

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads an int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Example:

import java.util.*;
public class ScannerExample
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}

Output:

Enter your name: Rahul Nayak


Name is: Rahul Nayak

***End of UNIT-1***
21
Page
UNIT – 2
OOPs – Object Oriented Programming
Object-oriented programming (OOP) refers to a programming
methodology based on objects, instead of just functions and procedures.
The objects contain the data and the methods (or behaviour).

In OOPs concepts, abstraction, encapsulation, inheritance and


polymorphism are known as four pillars of the object oriented
programming paradigm.

OOPs concepts:

Object:

Any entity that has state and behaviour is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.

An Object can be defined as an instance of a class.

Class:

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.

Inheritance:

When one object acquires all the properties and behaviours of a parent
object, it is known as inheritance. It provides code reusability. It is used
to achieve runtime polymorphism.

Polymorphism:

If one task is performed in different ways, it is known as polymorphism.

In Java, we use method overloading and method overriding to achieve


polymorphism.

Abstraction:

Hiding internal details and showing functionality is known as abstraction.


For example phone call, we don't know the internal processing.

Encapsulation:

Binding (or wrapping) code and data together into a single unit are known
as encapsulation. For example, a capsule, it is wrapped with different
medicines.
22
Page

A java class is the example of encapsulation.


What is a 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:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

class <class_name>
{
field;
method;
}

Static (or class) Variable

Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block. There
would only be one copy of each class variable per class, regardless of how
many objects are created from it.

Example:

public class VariableExample


{
int myVariable;
static int data = 30;

public static void main(String args[])


{
int a = 100;
VariableExample obj = new VariableExample();

System.out.println("Instance variable = "+obj.myVariable);


System.out.println("Static variable = "+VariableExample.data);
System.out.println("Local variable = "+a);
}
}

Output
Instance variable = 0
Static variable = 30
Local variable = 100
23
Page
Methods 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.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

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.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}

Output:

The maximum number is: 9

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.

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b);
System.out.println("The sum of a and b is = " + c);
}
//user defined method
public static int add(int n1, int n2)
{
24

int s;
s=n1+n2;
Page

return s; //returning the sum


}
}

Output:

The sum of a and b is = 24

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.

Object:

An entity that has state and behaviour is known as an object e.g., chair,
bike, marker, pen, table, car, etc.

Object and Class Example: main within the class

class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference
variable
System.out.println(s1.name);
}
}

Output:

O
null

Object and Class Example: main outside the class

class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
25

}
Page
Objects as Parameters:

A method can take an object as a parameter.

In Java, when a primitive type is passed to a method, it is done by use of


call-by-value. Objects are implicitly passed by use of call-by-reference.
This means when we pass primitive data types to method it will pass only
values to function parameters so any change made in parameter will not
affect the value of actual parameters.

Whereas Objects in java are reference variables, so for objects a value


which is the reference to the object is passed. Hence the whole object is
not passed but its referenced gets passed. All modification to the object in
the method would modify the object in the Heap.

class Add
{
int a;
int b;

Add (int x, int y)// parametrized constructor


{
a=x;
b=y;
}
void sum(Add A1) // object 'A1' passed as parameter in function
'sum'
{
int sum1=A1.a+A1.b;
System.out.println("Sum of a and b :"+sum1);
}
}

public class classExAdd


{
public static void main(String arg[])
{
Add A=new Add(5,8);
/* Calls the parametrized constructor
with set of parameters*/
A.sum(A);
}
}

Output:

Sum of a and b : 13
26
Page
Garbage Collection

Garbage Collection in Java is a process by which the programs perform


memory management automatically. The Garbage Collector (GC) finds the
unused objects and deletes them to reclaim the memory.

In Java, dynamic memory allocation of objects is achieved using the new


operator that uses some memory and the memory remains allocated until
there are references for the use of the object.

When there are no references to an object, it is assumed to be no longer


needed, and the memory, occupied by the object can be reclaimed. There
is no explicit need to destroy an object as Java handles the de-allocation
automatically. The technique that accomplishes this is known as Garbage
Collection.

Programs that do not de-allocate memory can eventually crash when


there is no memory left in the system to allocate. These programs are
said to have memory leaks.

Garbage collection in Java happens automatically during the lifetime


of the program, eliminating the need to de-allocate memory and thereby
avoiding memory leaks.

To do so, we were using free() function in C language and delete() in


C++. But, in java it is performed automatically. So, java provides better
memory management.

Advantages:
o It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM)
so we don't need to make extra efforts.

How can an object be unreferenced?

There are many ways:


o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
27

Employee e1=new Employee();


Employee e2=new Employee();
Page
e1=e2; //now the first object referred by e1 is available for
garbage collection
3) By anonymous object:
new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing.

This method is defined in Object class as:


protected void finalize(){}

gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}

Simple Example of garbage collection in java

public class TestGarbage1


{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

Output:
object is garbage collected
object is garbage collected

Constructor
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.
28
Page
Rules for creating a Java Constructor

1. It has the same name as the class


2. It should not return a value not even void

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

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

Syntax of default constructor:


class_name()
{
-----
-----
}

Example1:

class Demo
{
Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[])
{
Demo obj = new Demo();
}
}
Example2:
class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
29

s1.display();
Page

s2.display();
}
}
Output:
0 null
0 null

Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.

Example:
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()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
//creating objects and passing values
Student4 s1 = new Student4(111,"Saurav");
Student4 s2 = new Student4(222,"Gaurav");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Saurav
222 Gaurav

What is this Keyword in Java?

‘this’ keyword in Java is a reference variable that refers to the current


object of a method or a constructor.

The main purpose of using this keyword in Java is to remove the


confusion between class attributes and parameters that have same
names.
30
Page
Usage of java this keyword

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.

Example: Understanding the problem without this keyword

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output:

0 null 0.0
31

0 null 0.0
Page
In this example, parameters (formal arguments) and instance variables
are same. So, we are using this keyword to distinguish local variable and
instance variable.

Solution of the above problem by this keyword

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output:

111 ankit 5000


112 sumit 6000

N.B: - If local variables (formal arguments) and instance variables are


different, there is no need to use this keyword.

Method Overloading in Java

If a class has multiple methods having same name but different in


parameters, it is known as Method Overloading.

Advantages: Method overloading increases the readability of the program.

Different ways to overload the method


32

There are two ways to overload the method in java


1. By changing number of arguments
Page

2. By changing the data type


1) Method Overloading: changing no. of arguments

class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

In this example, we have created two methods, first add() method


performs addition of two numbers and second add method performs
addition of three numbers.

In this example, we are creating static methods so that we don't need to


create instance for calling methods.

2) Method Overloading: changing data type of arguments

class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
33

In this example, we have created two methods that differs in data type.
The first add method receives two integer arguments and second add
Page

method receives two double arguments.


Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can
also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one


constructor with different parameter lists.

They are arranged in a way that each constructor performs a different


task. They are differentiated by the compiler by the number of
parameters in the list and their types.

Example: program to overload constructors

class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:

111 Karan 0
222 Aryan 25
34
Page
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object.

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

The syntax of Java Inheritance:

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.

A class which is inherited is called a parent or superclass, and the new


class is called child or subclass.

Difference between extends and implements keywords

The keywords extends and implements are used to inherit the features of
an already existing parent block in newly created child block. Using
extends keyword, a newly created class (subclass) can inherit the
features of an existing class (superclass). Using implements keyword a
newly created class can implement all the methods of an interface.

extends implements
The extends keyword is used to The implements keyword is used for
create a subclass using features of the implementation of an interface
a super class.
The extends keyword may not The implements keyword has to
override all the methods of a super implement all the methods of an
class. implemented interface.
A class can extend only one super A class can implement multiple
class. interafaces.
An interface can extend more than An interface cannot implement
one interface. another interface.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java:


single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported


through interface only.
35
Page
Single Inheritance

When a class inherits another class, it is known as a single inheritance.

Example:
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Multilevel Inheritance

When there is a chain of inheritance, it is known as multilevel inheritance.

In Multilevel Inheritance, one class can inherit from a derived class.


Hence, the derived class becomes the base class for the new class.

Example:
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
36

{
Page

System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

Hierarchical Inheritance

When two or more classes inherit a single class, it is known


as hierarchical inheritance.

Example:
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class JavaExample
{
public static void main(String args[])
{
37

B obj1 = new B();


C obj2 = new C();
Page

//All classes can access the method of class A


obj1.methodA();
obj2.methodA();
}
}

Multiple Inheritance

Multiple inheritance in java is the capability of creating a single class with


multiple superclasses. Unlike some other popular object oriented
programming languages like C++, java doesn’t provide support for
multiple inheritance in classes.

Java doesn’t support multiple inheritances in classes because it can lead


to diamond problem.

Diamond Problem in Java

Let’s say SuperClass is an abstract class declaring some method and


ClassA, ClassB are concrete classes.

Example:
public abstract class SuperClass
{
public abstract void doSomething();
}

public class ClassA extends SuperClass


{
public void doSomething()
{
System.out.println("doSomething implementation of A");
}
//ClassA own method
public void methodA()
{
}
}
public class ClassB extends SuperClass
38

{
public void doSomething()
Page

{
System.out.println("doSomething implementation of B");
}
//ClassB own method
public void methodB()
{
}
}
public class ClassC extends ClassA, ClassB
{
public void test()
{
//calling super class method
doSomething();
}
}

Here, test() method is making a call to superclass doSomething()


method. This leads to the ambiguity as the compiler doesn’t know which
superclass method to execute. Because of the diamond-shaped class
diagram, it’s referred to as Diamond Problem in java. The diamond
problem in Java is the main reason java doesn’t support multiple
inheritances in classes.

Aggregation (HAS-A relationship)


Aggregation is a term which is used to refer one way
relationship between two objects.

For example, Student class can have reference of Address class but
vice versa does not make sense.

In Java, aggregation represents HAS-A relationship, which means when


a class contains reference of another class known to have aggregation.

The HAS-A relationship is based on usage, rather than inheritance. In


other words, class A has-a relationship with class B, if class A has a
reference to an instance of class B.

Class Address
{
int street_no;
String city;
String state;
int pin;
Address(int street_no, String city, String state, int pin )
{
this.street_no = street_no;
this.city = city;
this.state = state;
this.pin = pin;
}
}
39
Page
class Student
{
String name;
Address ad;
}

Here in the above code, we can see Student class has-a relationship
with Address class.

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be


only abstract methods in the Java interface, not method body. It is used
to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.

Syntax for Declaring Interface

interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}

To use an interface in your class, append the keyword "implements" after


your class name followed by the interface name.

Example:
interface B
{

}
Class A implements B
{

The relationship between classes and interfaces


40
Page
A class extends another class, an interface extends another interface, but
a class implements an interface.

Example:

interface printable
{
void print();
}
class Derived implements printable
{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])


{
Derived obj = new Derived();
obj.print();
}
}

Output:

Hello

Difference between Class and Interface

Class Interface
In class, you can instantiate In an interface, you can't instantiate
variable and create an object. variable and create an object.
Class can contain concrete(with The interface cannot contain
implementation) methods concrete (with implementation)
methods.
The access specifiers used with In Interface only one specifier is
classes are private, protected and used- Public.
public.

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
41
Page
Example:

interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Derived implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
Derived obj = new Derived();
obj.print();
obj.show();
}
}

Output:

Hello
Welcome

Upcasting and Downcasting in Java


Casting: Taking an object of one type and assigning it to reference
variable of another type.
42
Page
Upcasting:

Upcasting is the typecasting of a child object to a parent object.


Upcasting can be done implicitly.

class A
{

}
class B extend A
{

A a1 = new B();

This operation is a upcasting it happens automatically and no need to


do anything explicitly.

Here we can call the methods defined/declared in class ‘A’ but during
runtime it will call class B’s class overridden methods.

If the method is not overridden in child’s class then only parent’s method
which will be inherited to child will be called.

But same is not applicable to variables because variables decision


happens at a compile time, so always class A’s variables (not child’s
inherited variables) will be accessed.

Example:

class Parent
{
int x=10;
void show()
{
System.out.println("parent-show");
}

void OnlyParentShow()
{
System.out.println("OnlyParentShow");
}
}

class Child extends Parent


{
int x=20;
void show()
{
System.out.println("child-show");
43

}
void OnlyChildShow()
Page

{
System.out.println("OnlyChildShow");
}
}

class ParentChild
{

public static void main(String[] args)


{
Parent p = new Child();
p.show();
p.OnlyParentShow();
System.out.println(p.x);
}
}
Output:

child-show
OnlyParentShow
10

N.B:
show() is a method and overridden in child so child’s method is called.

OnlyParentShow() is a method not overridden but inherited to child


and called as it is.

But in case of variable, x is 10 in parent and 20 in child, even though


child has overridden ‘x’ but variable of parent is choosen.

Downcasting:

Downcasting means the typecasting of a parent object to a child


object. Downcasting cannot be implicitly.

Downcasting is not directly possible in Java.

Example:

Child c = new Parent();

The above program will not work. it is compile time error.

This is not possible because all the members of child class are not
available in parent.

If we call c.OnlyChildShow();

It compiles successfully but at runtime there is no such method with


parent’s object.

So, no direct downcasting is supported in Java but we can do


44

upcasting and then we can use that variable for downcasting as:
Page
Parent p = new Child();
Child c =(Child) p;

Downcasting will not happen automatically like upcasting, we have to cast


it explicitly like we did above (Child)p.

It is almost equivalent to

Child c = new Child();

N.B:

Whenever upcasting happens always remember

1) Parent's variables will be accessed

2) Child's methods (overridden methods if overriding happened else


inherited methods as it is from parent) will be called.

Polymorphism
Polymorphism is one of the OOPs feature that allows us to perform a
single action in different ways.

Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means
many forms.

There are two types of polymorphism in Java: compile-time polymorphism


and runtime polymorphism.

We can perform polymorphism in java by method overloading and method


overriding.

Method Overriding
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the


method that has been declared by one of its parent class, it is known as
method overriding.

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example:
class Animal
45

{
public void eat()
Page

{
System.out.println("Eat all eatables");
}
}

class Dog extends Animal


{
public void eat() //eat() method overridden by Dog class.
{
System.out.println("Dog like to eat meat");
}
public static void main(String[] args)
{
Dog d = new Dog();
d.eat();
}
}

Output:

Dog like to eat meat

Package
Package in Java is a collection of classes, sub-packages, and interfaces. It
helps organize your classes into a folder structure and make it easy to
locate and use them.

Package in java can be categorized in two form, built-in package and


user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.

Syntax:

package nameOfPackage;

The package keyword is used to create a package in java.

Example:

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

To Compile: javac -d . Simple.java


46

To Run: java mypack.Simple


Page
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.

Types of Packages in Java

Just like datatypes, packages are also of two types:


1. in-built
2. User-Defined

In-Built Packages in Java

1. java.lang – This package consists of classes that help in performing


input out operations in the program. It also contains language support for
data types and math operations. Whenever you create a class, this
package is automatically imported.

2. java.io – This package contains classes that specialize in input and


output operations only. One popular thing class you might have seen in
programs is the InputStreamReader class and the BufferedReader class.

3. java.util – This class contains basic utilities that can be useful while
implementing LinkedLists, Trees, HashMaps, and so on. It also has a
Scanner class for input-output operations to the program. It also contains
support for date and time.

4. java.applet – This package contains necessary classes for creating


applets.

5. java.awt – This package specializes in providing support for designing


GUI elements in Java.

6. java.net – This package contains classes which help in performing


network operations.

User-Defined Packages in Java

As the name suggests, user-defined packages in Java are essentially


packages, which the programmer-defined explicitly.

Whenever you need to add a class within a package, just specify the
package name along with the “package” keyword at the beginning of the
program.

packages Mypack;

public class UserDefinedPackages


{
public static void main(String[] args)
{
System.out.println(“This class is inside the Mypack package.”);
}
}
47
Page
Subpackage in Java

A package defined inside another package is known as sub package. Sub


packages are nothing different than packages except that they are
defined inside another package.

Sub packages are similar as sub directories which is a directory created


inside another directory.

Sub packages in itself are packages, so you have to use/access them


similar as packages.

Example:

package mypack.testpack;

class MySubPackageProgram
{
public static void main(String args [])
{
System.out.println("My sub package program");
}
}

Compile: javac –d . MySubPackageProgram.java

Run: java mypack.testpack.MySubPackageProgram

Output:

My sub package program

UNIT – 3
Arrays
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.

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.
48
Page
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.

Types of Array

There are two types of array.

• Single Dimensional Array

• Multidimensional Array(2D and 3D)

Single Dimensional Array

Syntax to Declare an Array:

dataType[] arr;

(or)

dataType []arr;

(or)

dataType arr[];

Instantiation of an Array

arrayRefVar=new datatype[size];

Example:
int a[]=new int[5];//declaration and instantiation

/* Java Program to illustrate how to declare, instantiate, initialize and


traverse the Java array. */

class Testarray
{
49

public static void main(String args[])


{
Page

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<a.length;i++)
{
System.out.println(a[i]);
}
}
}

Output
10
20
30
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


Example:

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

Multidimensional Array in Java (2D Array)

In such case, data is stored in row and column based index (also known
as matrix form).
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


50

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


Page
Example:
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++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Output:

123
245
445

Q: write a program to enter data into a 3x3 matrix and display it.

import java.util.Arrays;
import java.util.Scanner;

public class DisplayMatrix


{
public static void main(String[] args)
{
int matrix[][] = null ;
matrix = new int[3][3];

// create Scanner class object to read input


Scanner obj = new Scanner(System.in);

// read matrix
System.out.println("Enter 3x3 Matrix elements: ");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
matrix[i][j] = obj.nextInt();
}
}

System.out.println("Entered Matrix: ");


for(int i=0; i<3; i++)
51

{
for(int j=0; j<3; j++)
Page

{
System.out.print(matrix[i][j]+ " ");
}
System.out.println();
}
}
}

Output
Enter 3x3 Matrix elements:
123456789
Entered Matrix:
123
456
789

3D array in Java

A three dimensional can be defined as an array of two-dimensional


arrays. Three-dimensional array is also called the multidimensional array.

The general definition of a Three-dimensional array is given


below:

data_type [] [] [] array_name = new data_type [d1][d2][d3];

Here,
d1, d2, d3 = sizes of the dimensions
data_type = data type of the elements of the array
array_name = name of the 3d array

Example:

int [] [] [] intArray = new int[2][3][4];

The above definition of 3d array can be interpreted as having 2 tables or


arrays, 3 rows and 4 columns that totals up to 2x3x4 = 24 elements.
This means that in a 3d array, the three dimensions are interpreted as:
• The number of Tables/Arrays: The first dimension indicates how
many tables or arrays a 3d array will have.
• The number of Rows: The second dimension signifies the total
number of rows an array will have.
• The number of Columns: The third dimension indicates the total
columns in the 3d array.

How to initialize 3D arrays


// First approach
int[][][] matrix = new int[2][2][2];

matrix[0][0][0] = 10;
matrix[0][0][1] = 20;
matrix[0][1][0] = 30;
52

matrix[0][1][1] = 40;
Page

matrix[1][0][0] = 80;
matrix[1][0][1] = 90;
matrix[1][1][0] = 15;
matrix[1][1][1] = 25;

// 2nd approach
int[][][] a = {{{15,20},{30,40}},{{25,50},{60,80}}};

Program:
public class ThreeDArrayEx
{
public static void main(String[] args)
{
//initialize 3-d array
int[][][] myArray = { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 1, 4, 9 }, { 16,
25, 36 } }, { { 1, 8, 27 }, { 64, 125, 216 } } };
System.out.println("3x2x3 array is given below:");
//print the 3-d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
System.out.print(myArray[i][j][k] + "\t");
}
System.out.println();
}
System.out.println();
}
}
}

Output
3x2x3 array is given below:

1 2 3
4 5 6

1 4 9
16 25 36

1 8 27
64 125 216

Jagged Array in Java


A multi-dimensional array with different sizes child array is called a
Jagged array. It creates a table with different sizes of columns in a row.

Representation of Jagged array:


53
Page
Jagged Array Creation in Java

1) Jagged array creation in Java with explicit values.

We can directly create jagged array with values. Example:-


int[][] arr = {{10,9,8},{7,5,6,88},{30,15},{50},{10,20,30,40,50}};

String
String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters.

The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal

2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:


54

1. String s="welcome";
Page
1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the
pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool.

For example:

1. String s1="Welcome";

2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool,
that is why it will create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new object but will
return the reference to the same instance.

2) By new keyword

String s=new String("Welcome");//creates two objects and one


reference variable

In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-pool).

Example:
55

public class StringExample


{
Page

public static void main(String args[])


{
String s1="java";
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);
String s3=new String("Hello");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
output
java
strings
Hello

Java String class methods


The java.lang.String class provides many useful methods to perform
operations on sequence of char values.

charAt()

The java string charAt() method returns a char value at the given index
number.
The index number starts from 0 and goes to n-1, where n is length of the
string.

Example:
public class CharAtExample
{
public static void main(String args[])
{
String name="HelloJava";
char ch=name.charAt(4);//returns the char value at the 4th
index
System.out.println(ch);
}
}

OUTPUT
o

length()

The java string length() method length of the string. It returns count of
total number of characters. The length of java string is same as the
unicode code units of the string.

Example:
public class LengthExample
{
56

public static void main(String args[])


{
Page

String s1="Hello";
String s2="java";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}

OUTPUT
5
4

substring()

The java string substring() method returns a part of the string.

We pass begin index and end index number position in the java substring
method where start index is inclusive and end index is exclusive. In other
words, start index starts from 0 whereas end index starts from 1.

Example:
public class SubstringExample
{
public static void main(String args[])
{
String s1="Hellojava";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint
}
}

OUTPUT
ll
llojava

Immutable String in Java


In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new
string object is created.

Example:

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

{
String s="Sachin";
Page

s.concat(" Tendulkar");
System.out.println(s);
}
}
OUTPUT

Sachin

Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with sachintendulkar. That is why
string is known as immutable.

Why string objects are immutable in java?

Because java uses the concept of string literal. Suppose there are 5
reference variables, all refers to one object "sachin". If one reference
variable changes the value of the object, it will be affected to all the
reference variables. That is why string objects are immutable in java.

String compare
We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by


compareTo() method), reference matching (by == operator) etc.

There are three ways to compare string in java:

1. By equals() method
58

2. By = = operator
Page

3. By compareTo() method
1) String compare by equals() method

The String equals() method compares the original content of the string.

It compares values of string for equality.

Example:
class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
OUTPUT
true
true
false

2) String compare by == operator


The = = operator compares references not values.

Example:
class Teststringcomparison3
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to
same instance)
System.out.println(s1==s3);//false(because s3 refers to instance
created in nonpool)
}
}

OUTPUT
true
false

3) String compare by compareTo() method


59

The String compareTo() method compares values lexicographically and


returns an integer value that describes if first string is less than, equal to
Page

or greater than second string.


Suppose s1 and s2 are two string variables. If:
o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value

Example:

class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
OUTPUT
0
1
-1

StringBuffer class in Java

StringBuffer class is used to create a mutable string object. It means, it


can be changed after it is created. It represents growable and writable
character sequence.

It is similar to String class in Java both are used to create string, but
stringbuffer object can be changed.

So StringBuffer class is used when we have to make lot of modifications


to our string. It is also thread safe i.e multiple threads cannot access it
simultaneously.

Example: Creating a StringBuffer Object

public class Demo


{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb);
// modifying object
sb.append("Java");
System.out.println(sb); // Output: HelloJava

}
60

}
Page
OUTPUT

Hello
HelloJava

Java StringBuilder class

StringBuilder is identical to StringBuffer except for one important


difference that it is not synchronized, which means it is not thread safe.

StringBuilder also used for creating string object that is mutable and non
synchronized. The StringBuilder class provides no guarantee of
synchronization. StringBuffer and StringBuilder both are mutable but if
synchronization is not required then it is recommend to use StringBuilder
class.

Example: Creating a StringBuilder Object

public class Demo


{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Hello");
System.out.println(sb);
// modifying object
sb.append("Java");
System.out.println(sb);
}
}
OUTPUT
Hello
HelloJava

Java IO Stream
Java performs I/O through Streams.

In general, a stream means continuous flow of data.

Java encapsulates Stream under java.io package. Java defines two types
of streams. They are,

1. Byte Stream : It provides a convenient means for handling input


and output of byte.

2. Character Stream : It provides a convenient means for handling


input and output of characters.

Java Byte Stream Classes

Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.
61
Page
These two abstract classes have several concrete classes that handle
various devices such as disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

Contains method for reading java standard


DataInputStream
datatype

An output stream that contain method for


DataOutputStream
writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

Output Stream that


PrintStream
contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.

2. write() : Writes byte of data.

Java Character Stream Classes

Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
62
Page
These two abstract classes have several concrete classes that handle
unicode character.

Some important Charcter stream classes are:

Stream class Description


BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
Output stream that translate character to
OutputStreamReader
byte.
Output Stream that
PrintWriter
contain print() and println() method.
Abstract class that define character stream
Reader
input
Abstract class that define character stream
Writer
output

UNIT - 4
Exception Handling in Java

The exception handling is one of the powerful mechanisms provided in


java. It provides the mechanism to handle the runtime errors so that
normal flow of the application can be maintained.

In this page, we will know about exception, its type and the difference
between checked and unchecked exceptions.

Exception

• Dictionary Meaning: Exception is an abnormal condition.


63

• In java, exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime.
Page
Exception Handling

Exception Handling is a mechanism to handle runtime errors.

Exception handling is used to handle the exceptions ,which are


caused abnormal termination of the program, in java we can handle
these exceptions by the mechanism called Exception Handling.

In Java we can Handle the exceptions by the following keywords


try
catch
throw
throws
finally

Advantage of Exception Handling

The core advantage of exception handling is that normal flow of the


application is maintained. Exception normally disrupts the normal flow of
the application that is why we use exception handling. Let's take a
scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;

Suppose there is 10 statements in your program and there occurs an exception


at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will
not run. If we perform exception handling, rest of the exception will be
executed. That is why we use exception handling.
64
Page
Hierarchy of Exception classes

Types of Exception:
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says
there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

What is the difference between checked and unchecked exceptions ?

1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.

2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.

3)Error
65

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


Page

AssertionError etc.
Common scenarios of Exception Handling where exceptions may occur
There are given some scenarios where unchecked exceptions can occur.
They are as follows:

1) Scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the
variable occurs an NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];

a[10]=50; //ArrayIndexOutOfBoundsException

Use of try-catch block in Exception handling:

Five keywords used in Exception handling:

1. try
2. catch
3. finally
4. throw
5. throws

try block
Java try block is used to enclose the code that might throw an exception.
It must be used within the method.

If an exception occurs at the particular statement of try block, the rest of


the block code will not execute. So, it is recommended not to keeping the
code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try
66

{
//code that may throw an exception
Page

}
catch(Exception_class_Name ref)
{
}

Syntax of try-finally block

try
{
//code that may throw an exception
}
finally
{
}

Example:

public class TryCatchExample2


{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
OUTPUT
java.lang.ArithmeticException: / by zero
rest of the code

Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-
catch block.

Example:

public class MultipleCatchBlock1


{
public static void main(String[] args)
{
try
{
67

int a[]=new int[5];


a[5]=30/0;
Page

}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

OUTPUT
Arithmetic Exception occurs
rest of the code

finally block

Java finally block is a block that is used to execute important code such
as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Case 1
Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
68

System.out.println("finally block is always executed");


Page

}
System.out.println("rest of the code...");
}
}

OUTPUT
5
finally block is always executed
rest of the code...

Case 2
Let's see the java finally example where exception occurs and not handled.

class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

Case 3
Let's see the java finally example where exception occurs and handled.

public class TestFinallyBlock2


{
69

public static void main(String args[])


Page

{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw


keyword. The throw keyword is mainly used to throw custom exception.

The syntax of java throw keyword is:


throw exception;

Example of throw IOException:


throw new IOException("sorry device error);

Example:
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
70

System.out.println("welcome to vote");
}
Page
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword


The Java throws keyword is used to declare the exception information
that may occur during the program execution.
Syntax of java throws:
return_type method_name() throws exception_class_name
{
//method code
}

Example:
import java.io.IOException;
class TestThrow1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
71

}
public static void main(String args[])
Page
{
TestThrow1 obj=new TestThrow1();
obj.p();
System.out.println("normal flow...");
}
}
OUTPUT
exception handled
normal flow...

Difference between throw and throws in Java

throw throws
Java throw keyword is used to Java throws keyword is used to
explicitly throw an exception. declare an exception.
Checked exception cannot be Checked exception can be
propagated using throw only. propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method
signature.
You cannot throw multiple You can declare multiple
exceptions. exceptions e.g.
public void method() throws
IOException, SQLException.

What is Thread?
A thread is a lightweight sub-process, the smallest unit of processing. It is
a separate path of execution.

Threads are independent. If there occurs exception in one thread, it


doesn't affect other threads. It uses a shared memory area.

Multithreading in Java
Multithreading in Java is a process of executing two or more threads
simultaneously to maximum utilization of CPU.

Multithreaded applications execute two or more threads run concurrently.


Hence, it is also known as Concurrency in Java. Each thread runs parallel
to each other.

Multiple threads don't allocate separate memory area, hence they save
memory.

Advantages of Java Multithreading


72

1) It doesn't block the user because threads are independent and you
Page

can perform multiple operations at the same time.


2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an


exception occurs in a single thread.

Life cycle of a Thread (Thread States)

There are various stages of life cycle of thread. They are:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)
73

This is the state when the thread is still alive, but is currently not eligible
to run.
Page
5) Terminated

A thread is in terminated or dead state when its run() method exits.

Creating a thread in Java

To implement multithreading, Java defines two ways by which a thread


can be created.
• By implementing the Runnable interface.
• By extending the Thread class.

Implementing the Runnable Interface


The easiest way to create a thread is to create a class that implements
the runnable interface. After implementing runnable interface, the class
needs to implement the run() method.

Example:

class MyThread implements Runnable


{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

class MyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}

Extending Thread class

This is another way to create a thread by a new class that


extends Thread class and create an instance of that class. The extending
class must override run() method which is the entry point of new thread.

class MyThread extends Thread


{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

classMyThreadDemo
{
74

public static void main(String args[])


Page

{
MyThread mt = new MyThread();
mt.start();
}
}

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number


between 1 and 10. In most cases, thread scheduler schedules the threads
according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that which scheduling
it chooses.

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of


MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread


{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThrea
d().getName());
System.out.println("running thread priority is:"+Thread.currentThre
ad().getPriority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}
Output
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
75
Page
Java Synchronization

Synchronization is a process of handling resource accessibility by multiple


thread requests. The main purpose of synchronization is to avoid thread
interference. At times when more than one thread try to access a shared
resource, we need to ensure that resource will be used by only one thread
at a time. The process by which this is achieved is called synchronization.

General Syntax:
synchronized (object)
{
//statement to be synchronized
}

Types of Synchronization
There are two types of synchronization:

1) Process Synchronization
Process Synchronization involves multiple processes or threads executing
simultaneously. They ultimately reach a state where these processes or
threads commit to a specific sequence of actions.

2) Thread Synchronization
In Thread Synchronization, more than one thread is trying to access a
shared space. The threads are synchronized in such a manner that the
shared space is accessed only by one thread at a time.

Interthread Communication

Java provides benefits of avoiding thread pooling using inter-thread


communication. The wait(), notify(), and notifyAll() methods of Object
class are used for this purpose.

These method are implemented as final methods in Object, so that all


classes have them. All the three method can be called only from within
a synchronized context
• wait() tells calling thread to give up monitor and go to sleep until
some other thread enters the same monitor and call notify.
• notify() wakes up a thread that called wait() on same object.
• notifyAll() wakes up all the thread that called wait() on same
object.

JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API
for database-independent connectivity between the Java programming
language and a wide range of databases.

The JDBC API consists of classes and methods that are used to perform
76

various operations like: connect, read, write and store data in the
Page

database.
JDBC Architecture:

The JDBC API supports both two-tier and three-tier processing models for
database access. JDBC Architecture consists of two layers:

• JDBC API: This provides the application-to-JDBC Manager


connection.
• JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.

The JDBC API uses a driver manager and database-specific drivers to


provide transparent connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases.

Common JDBC Components:

The JDBC API provides the following interfaces and classes:

• DriverManager: This class manages a list of database drivers.


• Driver: This interface handles the communications with the
database server.
• Connection : This interface with all methods for contacting a
database.
• Statement : You use objects created from this interface to submit
the SQL statements to the database.
• ResultSet: These objects hold data retrieved from a database after
you execute an SQL query using Statement objects
• SQLException: This class handles any errors that occur in a
database application.
77
Page
JDBC Driver
JDBC Driver is a software component that enables java application to
interact with the database. There are 4 types of JDBC drivers:

• Type-1 Driver or JDBC-ODBC bridge

• Type-2 Driver or Native API Partly Java Driver

• Type-3 Driver or Network Protocol Driver

• Type-4 Driver or Thin Driver

Type-1 Driver or JDBC-ODBC bridge

Type-1 Driver acts as a bridge between JDBC and other database


connectivity mechanism (ODBC). This driver converts JDBC calls into
ODBC calls and redirects the request to the ODBC driver.

Advantage

• Easy to use

• Allow easy connectivity to all database supported by the ODBC


Driver.

Disadvantage

• Slow execution time

• Dependent on ODBC Driver.

Type-2 Driver or Native API Partly Java 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.
78
Page
Advantage

• Faster as compared to Type-1 Driver

• Contains additional features.

Disadvantage

• Requires native library

• Increased cost of Application

Type-3 Driver or Network Protocol Driver

This driver translates the JDBC calls into a database server independent
and Middleware server-specific calls. Middleware server further translates
JDBC calls into database specific calls. It is fully written in java.

Advantage

• Does not require any native library to be installed.


• Database Independency.
79

• Provide facility to switch over from one database to another


Page

database.
Disadvantage

• Slow due to increase number of network call.

Type-4 Driver or 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.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
80
Page
1) Register the driver class
The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.

Example to register the OracleDriver class:

Here, Java program is loading oracle driver to esteblish database


connection.

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object

The getConnection() method of DriverManager class is used to establish


connection with the database.

Example to establish connection with the Oracle database:

Connection con=DriverManager.getConnection
( "jdbc:oracle:thin:@localhost:1521:xe", "system", "password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create


statement. The object of statement is responsible to execute queries with
the database.
81
Page
Example to create the statement object:

Statement stmt=con.createStatement();

4) Execute the query

The executeQuery() method of Statement interface is used to execute


queries to the database. This method returns the object of ResultSet that
can be used to get all the records of a table.

Example to execute query:

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to
close the connection.
Example to close connection:

con.close();

Example to Connect Java Application with Oracle database


import java.sql.*;
class OracleCon
{
public static void main(String args[])
{
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


82

ResultSet rs=stmt.executeQuery("select * from emp");


Page

while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));

//step5 close the connection object


con.close();

}
catch(Exception e)
{
System.out.println(e);
}
}
}
In this example, we are connecting to an Oracle database and getting
data from emp table. Here, system and oracle are the username and
password of the Oracle database.

83
Page

You might also like