0% found this document useful (0 votes)
8 views332 pages

24CSK42 OOPs Using Java All Module Notes

The document outlines the course material for Object Oriented Programming using Java for the academic year 2025-2026, detailing the course structure, key components, and features of Java. It covers essential topics such as the Java Development Kit (JDK), Java Virtual Machine (JVM), and various data types and variables in Java programming. Additionally, it includes historical context and the evolution of the Java language, along with practical examples of Java code.

Uploaded by

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

24CSK42 OOPs Using Java All Module Notes

The document outlines the course material for Object Oriented Programming using Java for the academic year 2025-2026, detailing the course structure, key components, and features of Java. It covers essential topics such as the Java Development Kit (JDK), Java Virtual Machine (JVM), and various data types and variables in Java programming. Additionally, it includes historical context and the evolution of the Java language, along with practical examples of Java code.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COURSE MATERIAL
Academic year: 2025-2026
Semester: 4
Course Code & Name: 24CSK42– Object Oriented
Programming using Java
Course Coordinator: Dr Karthiyayini

Prepared by: Approved by:


[Link]. Karthiyayini Dr. B Rajalakshmi
Dr. Asha Joseph
[Link]. Bhimaraya Patil
Dr. Vandana C P
[Link]. Umamaheshwaran
HOD-CSE
[Link]. Chitra C

[Link]. Swathi
Object Oriented Programming using Java 24CSK42

MODULE 1
Introduction to Java

The Java Language, Java Development Kit (JDK); Java


Buzzwords, Byte Code, JVM, JRE and Java environment,
Data types, variables and Arrays, Operators,
Control statement, command line Arguments, Object
Oriented concepts, Classes, Objects and Methods,
Access specifiers, Method Overloading, Constructor,
Implicit this.

1. 1 Java Programming Language

Here are important landmarks from the history of the Java language:

• The Java language was initially called OAK.


• Originally, it was developed for handling portable devices and set-top boxes. Oak was a
massive failure.
• In 1995, Sun changed the name to "Java" and modified the language to take
advantage of the burgeoning www (World Wide Web) development business.
• Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of
three key Sun software assets: Java, MySQL, and Solaris.

1.2 Components of Java Programming Language

Java Development kit (JDK)

JDK is a software development environment used for making applets and Java applications.
The full form of JDK is Java Development Kit. Java developers can use it on Windows, macOS,
Solaris, and Linux. JDK helps them to code and run Java programs. It is possible to install
more than one JDK version on the same computer.

Why use JDK?


Object Oriented Programming using Java 24CSK42
Here are the main reasons for using JDK:

• JDK contains tools required to write Java programs and JRE to execute them.
• It includes a compiler, Java application launcher, Appletviewer, etc.
• Compiler converts code written in Java into byte code.
• Java application launcher opens a JRE, loads the necessary class, and executes its
main method.

Java Virtual Machine (JVM):

Java Virtual Machine (JVM) is an engine that provides a runtime environment to drive the Java
Code or applications. It converts Java bytecode into machine language. JVM is a part of the
Java Run Environment (JRE). In other programming languages, the compiler produces machine
code for a particular system. However, the Java compiler produces code for a Virtual Machine
known as Java Virtual Machine.

Why use JVM?

Here are the important reasons of using JVM:

• JVM provides a platform-independent way of executing Java source code.

• It has numerous libraries, tools, and frameworks.

• Once you run a Java program, you can run on any platform and save lots of time.

• JVM comes with JIT (Just-in-Time) compiler that converts Java source code into low- level
machine language. Hence, it runs faster than a regular application.

Java Runtime Environment (JRE)

JRE is a piece of software that is designed to run other software. It contains the class libraries,
loader class, and JVM. In simple terms, if you want to run a Java program, you need JRE. If
you are not a programmer, you don't need to install JDK, but just JRE to run Java programs.

Why use JRE?

Here are the main reasons of using JRE:

• JRE contains class libraries, JVM, and other supporting files. It does not include any
tool for Java development like a debugger, compiler, etc.
Object Oriented Programming using Java 24CSK42
• It uses important package classes like math, swing, util, lang, awt, and runtime
libraries.
• If you have to run Java applets, then JRE must be installed in your system.

Different Types of Java Platforms

There are four different types of Java programing language platforms:

1. Java Platform, Standard Edition (Java SE): Java SE's API offers the Java programming
language's core functionality. It defines all the basis of type and object to high-level classes. It
is used for networking, security, database access, graphical user interface (GUI) development,
and XML parsing.

2. Java Platform, Enterprise Edition (Java EE): The Java EE platform offers an API and
runtime environment for developing and running highly scalable, large-scale, multi-tiered,
reliable, and secure network applications.
Object Oriented Programming using Java 24CSK42
3. Java Programming Language Platform, Micro Edition (Java ME): The Java ME
platform offers an API and a small-footprint virtual machine running Java programming
language applications on small devices, like mobile phones.

4. Java FX: JavaFX is a platform for developing rich internet applications using a lightweight
user-interface API. It user hardware-accelerated graphics and media engines that help Java take
advantage of higher-performance clients and a modern look-and-feel and high- level APIs for
connecting to networked data sources.

1.3 Features of Java- Java Buzzwords


The primary objective of Jav1a programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java
are also known as java buzzwords.

A list of most important features of Java language is given below.

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

1.4 Java Variables

A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Object Oriented Programming using Java 24CSK42

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 data=50;//Here data is variable

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable
Object Oriented Programming using Java 24CSK42

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

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 to understand the types of variables in java

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

Java Variable Example: Add Two Numbers

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

Output:
20
Object Oriented Programming using Java 24CSK42

Java Variable Example: Widening

1. class Simple{
2. public static void main(String[] args){
3. int a=10;
4. float f=a;
5. [Link](a);
6. [Link](f);
7. }}

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)

1. class Simple{
2. public static void main(String[] args){
3. float f=10.5f;
4. //int a=f;//Compile time error
5. int a=(int)f;
6. [Link](f);
7. [Link](a);
8. }}

Output:

10.5
10

Java Variable Example: Overflow

1. class Simple{
2. public static void main(String[] args){
3. //Overflow
4. int a=130;
5. byte b=(byte)a;
6. [Link](a);
7. [Link](b);
8. }}

Output:

130
-126
Object Oriented Programming using Java 24CSK42

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

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared


before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Object Oriented Programming using Java 24CSK42
Object Oriented Programming using Java 24CSK42

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
Object Oriented Programming using Java 24CSK42

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.

The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.

Example: short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L


Object Oriented Programming using Java 24CSK42

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating-point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is
0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest
range of Unicode system.

Java program to demonstrate


// primitive data types in Java

classGeeksforGeeks {
publicstaticvoidmain(String args[])
{
// declaring character
chara = 'G';
Object Oriented Programming using Java 24CSK42

// Integer data type is generally


// used for numeric values
inti = 89;

// use byte and short


// if memory is a constraint
byteb = 4;

// this will give error as number is


// larger than byte range
// byte b1 = 7888888955;

shorts = 56;

// this will give error as number is


// larger than short range
// short s1 = 87878787878;

// by default fraction value


// is double in java
doubled = 4.355453532;

// for float use 'f' as suffix


floatf = 4.7333434f;

[Link]("char: "+ a);


[Link]("integer: "+ i);
[Link]("byte: "+ b);
[Link]("short: "+ s);
[Link]("float: "+ f);
[Link]("double: "+ d);
}
}
Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532

1.6 JAVA ARRAYS

Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
Object Oriented Programming using Java 24CSK42

useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable −

Syntax

dataType[] arrayRefVar; // preferred way.

or

dataType arrayRefVar[]; // works but not preferred way.

Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++
programmers.

Example

The following code snippets are examples of this syntax −

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays

You can create an array by using the new operator with the following syntax −

Syntax
Object Oriented Programming using Java 24CSK42

arrayRefVar = new dataType[arraySize];

The above statement does two things −

• It creates an array using new dataType[arraySize].


• It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows −

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to [Link]-1.

Example

Following statement declares an array variable, myList, creates an array of 10 elements of


double type and assigns its reference to myList −

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Object Oriented Programming using Java 24CSK42

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of
the elements in an array are of the same type and the size of the array is known.

Example

Here is a complete example showing how to create, initialize, and process arrays −
public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < [Link]; i++) {
[Link](myList[i] + " ");
}

// Summing all elements


double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}
[Link]("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < [Link]; i++) {
if (myList[i] > max) max = myList[i];
}
[Link]("Max is " + max);
}
}

This will produce the following result −

Output

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Object Oriented Programming using Java 24CSK42

1.7 Types of Operators in Java


1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %


+ is for addition.

– is for subtraction.

* is for multiplication.

/ is for division.

% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0

Example of Arithmetic Operators

public class ArithmeticOperatorDemo {


public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

[Link]("num1 + num2: " + (num1 + num2) );


[Link]("num1 - num2: " + (num1 - num2) );
[Link]("num1 * num2: " + (num1 * num2) );
Object Oriented Programming using Java 24CSK42

[Link]("num1 / num2: " + (num1 / num2) );


[Link]("num1 % num2: " + (num1 % num2) );
}
}
Output:

num1 + num2: 120


num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0
Checkout these java programs related to arithmetic Operators in Java:

1. Java Program to Add two numbers


2. Java Program to Multiply two Numbers

2) Assignment Operators

Assignments operators in java are: =, +=, -=, *=, /=, %=


num2 = num1 would assign value of variable num1 to the variable.

num2+=num1 is equal to num2 = num2+num1

num2-=num1 is equal to num2 = num2-num1

num2*=num1 is equal to num2 = num2*num1

num2/=num1 is equal to num2 = num2/num1

num2%=num1 is equal to num2 = num2%num1

Example of Assignment Operators

public class AssignmentOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
[Link]("= Output: "+num2);

num2 += num1;
[Link]("+= Output: "+num2);

num2 -= num1;
[Link]("-= Output: "+num2);
Object Oriented Programming using Java 24CSK42

num2 *= num1;
[Link]("*= Output: "+num2);

num2 /= num1;
[Link]("/= Output: "+num2);

num2 %= num1;
[Link]("%= Output: "+num2);
}
}
Output:

= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0
3) Auto-increment and Auto-decrement Operators

++ and —

num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

public class AutoOperatorDemo {


public static void main(String args[]){
int num1=100;
int num2=200;
num1++;
num2--;
[Link]("num1++ is: "+num1);
[Link]("num2-- is: "+num2);
}
}
Output:

num1++ is: 101


num2-- is: 199
4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.

Logical operators in java are: &&, ||, !


Object Oriented Programming using Java 24CSK42

Let’s say we have two boolean variables b1 and b2.

b1&&b2 will return true if both b1 and b2 are true else it would return false.

b1||b2 will return false if both b1 and b2 are false else it would return true.

!b1 would return the opposite of b1, that means it would be true if b1 is false and it would
return false if b1 is true.

Example of Logical Operators

public class LogicalOperatorDemo {


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

[Link]("b1 && b2: " + (b1&&b2));


[Link]("b1 || b2: " + (b1||b2));
[Link]("!(b1 && b2): " + !(b1&&b2));
}
}
Output:

b1 && b2: false


b1 || b2: true
!(b1 && b2): true
5) Comparison(Relational) operators

We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal

!= returns true if left side is not equal to the right side of operator.

> returns true if left side is greater than right.

< returns true if left side is less than right side.

>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.

Example of Relational operators

Note: This example is using if-else statement which is our next tutorial, if you are finding it
difficult to understand then refer if-else in Java.
Object Oriented Programming using Java 24CSK42

public class RelationalOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if (num1==num2) {
[Link]("num1 and num2 are equal");
}
else{
[Link]("num1 and num2 are not equal");
}

if( num1 != num2 ){


[Link]("num1 and num2 are not equal");
}
else{
[Link]("num1 and num2 are equal");
}

if( num1 > num2 ){


[Link]("num1 is greater than num2");
}
else{
[Link]("num1 is not greater than num2");
}

if( num1 >= num2 ){


[Link]("num1 is greater than or equal to num2");
}
else{
[Link]("num1 is less than num2");
}

if( num1 < num2 ){


[Link]("num1 is less than num2");
}
else{
[Link]("num1 is not less than num2");
}
Object Oriented Programming using Java 24CSK42

if( num1 <= num2){


[Link]("num1 is less than or equal to num2");
} }
else{
[Link]("num1 is greater than num2");

}
}

6) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.


num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits
are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the
binary form of num1 and num2 only second last bits are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is
1, else it returns 0. In our case it would return 31 which is 00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not
equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our example
it would return -12 which is signed 8 bit equivalent to 11110100

num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to 00101100

Note: In the example below we are providing 2 at the right side of this shift operator that is the
reason bits are moving two places to the left side. We can change this number and bits would
be moved by the number of bits specified on the right side of the operator. Same applies to the
right side operator.
Object Oriented Programming using Java 24CSK42

num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and
assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010

Example of Bitwise Operators

public class BitwiseOperatorDemo {


public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


[Link]("num1 & num2: "+result);

result = num1 | num2;


[Link]("num1 | num2: "+result);

result = num1 ^ num2;


[Link]("num1 ^ num2: "+result);

result = ~num1;
[Link]("~num1: "+result);

result = num1 << 2;


[Link]("num1 << 2: "+result); result = num1 >> 2;
[Link]("num1 >> 2: "+result);
}
}
Output:

num1 & num2: 2


num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2
Check out this program: Java Program to swap two numbers using bitwise operator

7) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.
Object Oriented Programming using Java 24CSK42
Example of Ternary Operator

public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
[Link]( "num2: "+num2);

/* num1 is equal to 25 that's why


* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 25) ? 100: 200;
[Link]( "num2: "+num2);
}
}
Output:

num2: 200
num2: 100

1.8 Control Statement- Decision Making in Java (if, if-else, switch, break, continue,
jump)

Decision Making in programming is similar to decision making in real life. In programming,


also we face some situations where we want a certain block of code to be executed when some
condition is fulfilled. A programming language uses control statements to control the flow of
execution of program based on certain conditions. These are used to cause the flow of execution
to advance and branch based on changes to the state of a program.
Java’s Selection statements:

if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
Object Oriented Programming using Java 24CSK42

These statements allow you to control the flow of your program’s execution based
upon conditions known only during run time.

if:
if statement is the simplest decision-making statement. It is used to decide whether a certain statement or
block of statements will be executed or not i.e if a certain condition is true then a block of statement
is executed otherwise not.
Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it. If
we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For exampl

if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.

Flow chart:
Object Oriented Programming using Java 24CSK42

Example:
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;

if (i > 15)
[Link]("10 is less than 15");

// This statement will be executed


// as if considers one statement by default
[Link]("I am Not in if");
}
}
Output:
I am Not in if

if-else

The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else if the condition
is false. Here comes the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.

Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Object Oriented Programming using Java 24CSK42
Flowchart:

Example:

// Java program to illustrate if-else statement


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

int i = 10;

if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}

Output:
i is smaller than 15
Object Oriented Programming using Java 24CSK42

nested-if

A nested if is an if statement that is the target of another if or else. Nested if statements mean
an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.

Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Flowchart:
Object Oriented Programming using Java 24CSK42

Example:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)
{
// First if statement
if (i < 15)
[Link]("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12 too");
else
[Link]("i is greater than 15");
}
}
}
Output:

i is smaller than 15
i is smaller than 12 too

if-else-if ladder:
Here, a user can decide among multiple [Link] if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed.
Syntax:
Object Oriented Programming using Java 24CSK42

Flowchart:

Example:

// Java program to illustrate if-else-if ladder


class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
Object Oriented Programming using Java 24CSK42

[Link]("i is not present");


}
}
Output:
i is 20

switch-case
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}

Expresion can be of type byte, short, int char or an enumeration. Beginning with JDK7,
expression can also be of type String.
Dulplicate case values are not allowed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional. If omitted, execution will continue on into the next case.
Object Oriented Programming using Java 24CSK42
Flowchart:
Object Oriented Programming using Java 24CSK42
Example:

// Java program to illustrate switch-case


class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
case 2:
[Link]("i is two.");
break;
default:
[Link]("i is greater than 2.");
}
}
}
Output:
i is greater than 2.
jump
Java supports three jump statement: break, continue and return. These three statements
transfer control to other part of the program.

Break:

In Java, break is majorly used for:


• Terminate a sequence in a switch statement (discussed above). To exit a loop.
• Used as a “civilized” form of goto.
• Using break to exit a Loop

Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the innermost
loop.
Object Oriented Programming using Java 24CSK42

Flowchartr:

Example:
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;

[Link]("i: " + i);


}
[Link]("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
Object Oriented Programming using Java 24CSK42

i: 4
Loop complete.

Using break as a Form of Goto

Java does not have a goto statement because it provides a way to branch in an arbitrary
and unstructured manner. Java uses label. A Label is use to identifies a block of code.

Syntax:
label:
{
statement1;
statement2;
statement3;
.
.

Now,
} break statement can be use to jump out of target block.
Note: You cannot break to any label which is not defined for an enclosing block.
Syntax:
break label;
Example:
// Java program to illustrate using break with goto
class BreakLabelDemo
{
public static void main(String args[])
{
boolean t = true;

// label first
first:
{
// Illegal statement here as label second is not
// introduced yet break second;
second:
{
third:
{
// Before break
[Link]("Before the break statement");

// break will take the control out of


Object Oriented Programming using Java 24CSK42

// second label
if (t)
break second;
[Link]("This won't execute.");
}
[Link]("This won't execute.");
}

// First block
[Link]("This is after second block.");
}
}
}
Output:
Before the break.
This is after second block.
Continue:

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue
running the loop but stop processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The
continue statement performs such an action.
Flowchart:

Example:
// Java program to illustrate using
// continue in an if statement
class ContinueDemo
{
Object Oriented Programming using Java 24CSK42

public static void main(String args[])


{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;

// If number is odd, print it


[Link](i + " ");
}
}
}
Output:
13579
 Return:The return statement is used to explicitly return from a method. That is, it
causes a program control to transfer back to the caller of the method.
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate using return
class Return
{
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
[Link]("This won't execute.");
}
}
Output:
Before the return.
Object Oriented Programming using Java 24CSK42

1.9 Loops in Java


Looping in programming languages is a feature which facilitates the execution of a set of
instructions/functions repeatedly while some condition evaluates to true.

Java provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time.

while loop:
A while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition. The while loop can be thought of as a repeating if statement.

Syntax:

Flowchart:
Object Oriented Programming using Java 24CSK42

• While loop starts with the checking of condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason, it is also called Entry control loop
• Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for
the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life
cycle.

// Java program to illustrate while loop


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

int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
[Link]("Value of x:" + x);

// Increment the value of x for


// next iteration
x++;
}
}
}
Output:

Value of x:1
Value of x:2
Value of x:3
Value of x:4
Object Oriented Programming using Java 24CSK42

for loop:

for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}
Flowchart:
Object Oriented Programming using Java 24CSK42

 Initialization condition: Here, we initialize the variable in use. It marks the start of a for
loop. An already declared variable can be used or a variable can be declared, local to
loop only.
 Testing Condition: It is used for testing the exit condition for a loop. It must return
a boolean value. It is also an Entry Control Loop as the condition is checked prior
to the execution of the loop statements.
 Statement execution: Once the condition is evaluated to true, the statements in the
loop body are executed.
 Increment/ Decrement: It is used for updating the variable for next iteration.
 Loop termination: When the condition becomes false, the loop terminates
marking the end of its life cycle.

// Java program to illustrate for loop.


class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
[Link]("Value of x:" + x);
}
}
Output:
Value of x:2
Value of x:3
Value of x:4

Enhanced For loop


Java also includes another version of for loop introduced in Java 5. Enhanced for loop
provides a simpler way to iterate through the elements of a collection or array. It is
inflexible and should be used only when there is a need to iterate through the elements
in sequential manner without knowing the index of currently processed element.
Also note that the object/variable is immutable when enhanced for loop is used i.e it
ensures that the values in the array cannot be modified, so it can be said as read only loop
where you can’t update the values as opposite to other loops where values can be modified.
We recommend using this form of the for statement instead of the general form whenever
possible. (as per JAVA doc.)
Syntax:
Object Oriented Programming using Java 24CSK42

for (T element:Collection obj/array)


{
statement(s)
}

Let’s take an example to demonstrate how enhanced for loop can be used to simplify the
work. Suppose there is an array of names and we want to print all the names in that
array. Let’s see the difference with these two examples

Enhanced for loop simplifies the work as follows-

// Java program to illustrate enhanced for loop


public class enhancedforloop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};

//enhanced for loop


for (String x:array)
{
[Link](x);
}

/* for loop for same function


for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}
*/
}
}

Output:
Ron
Harry
Hermoine
Object Oriented Programming using Java 24CSK42
do while:
do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.

Syntax:

do
{
statements..
}
while (condition);

Flowchart:
Object Oriented Programming using Java 24CSK42

• do while loop starts with the execution of the statement(s). There is no


checking of any condition for the first time.
• After the execution of the statements, and update of the variable value, the
condition is checked for true or false value. If it is evaluated to true, next
iteration of loop starts.
• When the condition becomes false, the loop terminates which marks the end of
its life cycle.
• It is important to note that the do-while loop will execute its statements atleast
once before any condition is checked, and therefore is an example of exit
control loop.

// Java program to illustrate do-while loop


class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
[Link]("Value of x:" + x);
x++;
}
while (x < 20);
}
}
Output:
Value of x: 21
Object Oriented Programming using Java 24CSK42

1.10 What is Command Line Argument?


Command Line Argument is information passed to the program when you run the program.
The passed information is stored as a string array in the main method. Later, you can use the
command line arguments in your program.

Example While running a class Demo, you can specify command line arguments as

java Demo arg1 arg2 arg3 …

Command Line Arguments in Java: Important Points

o Command Line Arguments can be used to specify configuration information while


launching your application.
o There is no restriction on the number of java command line arguments. You can
specify any number of arguments
o Information is passed as Strings.
o They are captured into the String args of your main method

Example:
To Learn java Command Line Arguments

Step 1) Copy the following code into an editor.


class Demo{
public static void main(String b[]){
[Link]("Argument one = "+b[0]);
[Link]("Argument two = "+b[1]);
}
}

Step 2) Save & Compile the code

Step 3) Run the code as java Demo apple orange.

Step 4) You must get an output as below.


Object Oriented Programming using Java 24CSK42

Program for Command Line Arguments;

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

[Link]("Number of arguments: " + [Link]);

for(int i = 0; i < [Link]; i++) {


[Link]("Argument " + i + ": " + args[i]);
}
}
}

Output:

Number of arguments: 3
Argument 0: Hello
Argument 1: 123
Argument 2: Java
Object Oriented Programming using Java 24CSK42

1.11Object Oriented Programming (OOPs) Concept in Java

Object-oriented programming: As the name suggests, Object-Oriented Programming or


OOPs refers to languages that uses objects in programming. Object-oriented programming
aims to implement real-world entities like inheritance, hiding, polymorphism etc. in
programming. The main aim of OOP is to bind together the data and the functions that operate
on them so that no other part of the code can access this data except that function.

OOPs Concepts:

Polymorphism
Inheritance
Encapsulation
Abstraction
Class
Object
Method
Message Passing
Object Oriented Programming using Java 24CSK42

Let us learn about the different characteristics of an Object-Oriented Programming language:

Polymorphism

Polymorphism refers to the ability of OOPs programming languages to differentiate between entities
with the same name efficiently. This is done by Java with the help of the signature and declaration of
these entities.

For example:
// Java program to demonstrate Polymorphism

// This class will contain

// 3 methods with same name,


// yet the program will
// compile & run successfully
public

class Sum {

// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
Object Oriented Programming using Java 24CSK42
}
}

Output:

Polymorphism in Java are mainly of 2 types:


• Overloading in Java
• Overriding in Java

Encapsulation:

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. Another way to think about encapsulation is, it is a protective
shield that prevents the data from being accessed by the code outside this shield.

• Technically in encapsulation, the variables or data of a class is hidden from any


other class and can be accessed only through any member function of own class
in which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
• Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables.
Object Oriented Programming using Java 24CSK42
Abstraction

Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
The trivial or the non-essentials units are not displayed to the user.
Example: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of
an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it
from other objects of similar type and also help in classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of car or applying brakes will stop the car but he does not know about how on
pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is. In java, abstraction
is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

Inheritance

Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in java
by which one class is allow to inherit the features (fields and methods) of another class.
Important terminology:

o Super Class: The class whose features are inherited is known as superclass(or a base
class or a parent class).
o Sub Class: The class that inherits the other class is known as subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
o Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.

The keyword used for inheritance is extends.

Syntax:

class derived-class extends base-class


{
//methods and fields
}
Object Oriented Programming using Java 24CSK42

Class:

A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:

 Modifiers: A class can be public or has default access (Refer this for details).
 Class name: The name should begin with a initial letter (capitalized by
convention).
 Superclass (if any): The name of the class’s parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
 Interfaces (if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
 Body: The class body surrounded by braces, { }.

Before you create objects in Java, you need to define a class. A class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors,
doors, windows etc. Based on these descriptions we build the house. House is the object.

Since, many houses can be made from the same description, we can create many objects from
a class.

How to define a class in Java?

Here's how a class is defined in Java:

1. class ClassName {
2. // variables
3. // methods
4. }
Object Oriented Programming using Java 24CSK42
Object:

It is a basic unit of Object-Oriented Programming and represents the real-life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods.
An object consists of:
 State: It is represented by attributes of an object. It also reflects the properties of
an object.
 Behavior: It is represented by methods of an object. It also reflects the response
of an object with other objects.
 Identity: It gives a unique name to an object and enables one object to interact
with other objects.

Let's take few examples:


• Lamp is an object
• It can be in on or off state.
• You can turn on and turn off lamp (behavior).
• Bicycle is an object
• It has current gear, two wheels, number of gear etc. states.
• It has braking, accelerating, changing gears etc. behavior.

Example of an object: dog

Method:

A method is a collection of statements that perform some specific task and return result to the caller. A
method can perform some specific tasks without returning anything. Methods allow us to reuse the
code without retyping the code. In Java, every method must be part of some class which is different from
languages like C, C++ and Python. Methods are time savers and help us to reuse the code without
retyping the code.

Method Declaration

In general, method declarations have six components:

• Access Modifier: Defines access type of the method i.e. from where it can be accessed
in your application. In Java, there 4 types of the access specifiers.
▪ public: accessible in all class in your application.
Object Oriented Programming using Java 24CSK42
▪ protected: accessible within the package in which it is defined and, in its
subclass,(es)(including subclasses declared outside the package)
▪ private: accessible only within the class in which it is defined.
▪ default (declared/defined without using any modifier): accessible within
same class and package within which its class is defined.

• The return type: The data type of the value returned by the method or void if does not
return a value.
• Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
• Parameter list: Comma separated list of the input parameters are defined, preceded
with their data type, within the enclosed parenthesis. If there are no parameters, you
must use empty parentheses ().
• Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).
• Method body: It is enclosed between braces. The code you need to be executed
to perform your intended operations.
Object Oriented Programming using Java 24CSK42

Message Passing:
Objects communicate with one another by sending and receiving information to each other. A message
for an object is a request for execution of a procedure and therefore will invoke a function in the
receiving object that generates the desired results. Message passing involves specifying the name of
the object, the name of the function and the information to be sent.

Example:

Create a class named Lamp.


The class should contain:
• an instance variable isOn
• three methods: turnOn(), turnOff(), and displayLightStatus()
In the main() method, create two objects of the Lamp class: l1 and l2.
Call [Link]() — this should set the isOn variable of object l1 to true.
Call [Link]() — this should set the isOn variable of object l2 to false.
Finally:
[Link](); should print “Light on? true” because isOn holds true for l1.
[Link](); should print “Light on? false” because isOn holds false for l2.

When class is defined, only the specification for the object is defined; no memory or storage
is allocated.

To access members defined within the class, you need to create objects. Let's create objects
of Lamp class.

Here's an example:
1. class Lamp {
2.
3. // instance variable
4. private boolean isOn;
5.
6. // method
7. public void turnOn() {
8. isOn = true;
9. }
10.
11. // method
12. public void turnOff() {
13. isOn = false;
14. }
15. }
Object Oriented Programming using Java 24CSK42

Here, we defined a class named Lamp.


The class has one instance variable (variable defined inside class) isOn and two
methods turnOn() and turnOff(). These variables and methods defined within a class are
called members of the class.

Notice two keywords, private and public in the above program. These are access modifiers
which will be discussed in detail in later chapters. For now, just remember:
• The private keyword makes instance variables and methods private which can be
accessed only from inside the same class.
• The public keyword makes instance variables and methods public which can be
accessed from outside of the class.

In the above program, isOn variable is private whereas turnOn() and turnOff() methods are
public.
If you try to access private members from outside of the class, compiler throws error.
Object Oriented Programming using Java 24CSK42
1. class Lamp {
2. boolean isOn;
3.
4. void turnOn() {
5. isOn = true;
6. }
7.
8. void turnOff() {
9. isOn = false;
10. }
11. }
12.
13. class ClassObjectsExample {
14. public static void main(String[] args) {
15. Lamp l1 = new Lamp(); // create l1 object of Lamp class
16. Lamp l2 = new Lamp(); // create l2 object of Lamp class
17. }
18. }

This program creates two objects l1 and l2 of class Lamp.

How to access members?

You can access members (call methods and access instance variables) by using. operator.
For example,

[Link]();

This statement calls turnOn() method inside Lamp class for l1 object.
We have mentioned word method quite a few times. You will learn about Java methods in detail in the
next chapter. Here's what you need to know for now:
When you call the method using the above statement, all statements within the body
of turnOn() method are executed. Then, the control of program jumps back to the statement following
[Link]();
Similarly, the instance variable can be accessed as:

[Link] = false;

It is important to note that, the private members can be accessed only from inside the class. If
the code [Link] = false; lies within the main() method (outside of the Lamp class), compiler
will show error.
Object Oriented Programming using Java 24CSK42

Example: Java Class and Objects


1. class Lamp {
2. boolean isOn;
3.
4. void turnOn() {
5. isOn = true;
6. }
7.
8. void turnOff() {
9. isOn = false;
10. }
11.
12. void displayLightStatus() {
13.
14. [Link]("Light on? " + isOn);
15. }
16. }
17.
18.
19. class ClassObjectsExample {
20. public static void main(String[] args) {
21.
22. Lamp l1 = new Lamp(), l2 = new Lamp();
23.
24. [Link]();
25. [Link]();
26.
27. [Link]();
28. [Link]();
29. }
30. }

When you run the program, the output will be:

Light on? true


Light on? false

In the above program,

• Lamp class is created.


• The class has an instance variable isOn and three methods turnOn(), turnOff() and
displayLightStatus().
• Two objects l1 and l2 of Lamp class are created in the main() function.
• Here, turnOn() method is called using l1 object: [Link]();
Object Oriented Programming using Java 24CSK42
• This method sets isOn instance variable of l1 object to true.
• And, turnOff() method is called using l2 object: [Link]();
• This method sets isOff instance variable of l2 object to false.
• Finally, [Link](); statement displays Light on? true because isOn variable
holds true for l1 object.
• And, [Link](); statement displays Light on? false because isOn variable holds
false for l2 object

Note, variables defined within a class are called instance variable for a reason.
When an object is initialized, it's called an instance. Each instance contains its own copy of
these variables. For example, isOn variable for objects l1 and l2 are different
Object Oriented Programming using Java 24CSK42

1.10 Method Overloading in Java


Methods are used in Java to describe the behavior of an object. Methods are a collection of
statements that are group together to operate. In Java, it is possible to create methods that
have the same name, but different argument lists in various definitions, i.e., method
overloading is possible in Java, which is one of the unique features of Object-Oriented
Programming (OOP). In this chapter, we will learn about how method overloading is written
and how it helps us within a Java program.
What is Method Overloading in Java?

If a class of a Java program has a plural number of methods, and all of them have the same
name but different parameters (with a change in type or number of arguments), and
programmers can use them to perform a similar form of functions, then it is known as method
overloading. If programmers what to perform one operation, having the same name, the
method increases the readability if the program.
Let us take an example where you can perform multiplication of given numbers, but there can
be any number of arguments a user can put to multiply, i.e., from the user point of view the
user can multiply two numbers or three numbers or four numbers or so on. If you write the
method such as multi(int, int) with two parameters for multiplying two values, multi(int, int,
int), with three parameters for multiplying three values and so on. A programmer does
method overloading to figure out the program quickly and efficiently. Method Overloading is
applied in a program when objects are required to perform similar tasks but different input
parameters. Every time an object calls a method, Java matches up to the method name first
and then the number and type of parameters to decide what definitions to execute. This
process of assigning multiple tasks to the same method is known as Polymorphism. There are
different ways to overload a method in Java. They are:

o Based on the number of parameters: In this case, the entire overloading concept
depends on the number of parameters that are placed within the parenthesis of the
method.
o Based on the data type of the parameter: With the arrangement of data type, within the
parameter, overloading of the method can take place.

o Based on the sequence of data types in parameters: The method overloading also
depends on the ordering of data types of parameters within the method.
To create overloaded methods, programmers need to develop several different method definitions
in the class, all have the same name, but the parameters list is different.
Object Oriented Programming using Java 24CSK42
Syntax:
public classStudent{

public void add(int i,int j){

....

public void add(int i){

....

The static polymorphism is also called compile-time binding or early binding. Static binding
happens at compile time, and Method overloading is an example of static binding where
binding of the method call to its definition occurs at Compile time.

Program for Method Overloading in Java


Example:
class Multiply{

void mul(int a,int b){

[Link]("Sum of two="+(a * b));

void mul(int a,int b,int c){


Object Oriented Programming using Java 24CSK42

[Link]("Sum of three="+(a * b * c));

public class Polymorphism{

public static void main(String args[]){

Multiply m =new Multiply();

[Link](6,10);

[Link](10,6,5);

Output:
Sum of two=60

Sum of three=300

Why Method Overloading is not possible if the return type of method is changed?

In Java, method overloading is not possible by changing the return type of the method
because there may arise some ambiguity. Let's see how ambiguity may occur:
Example:
class overloadRetType {

int sum(int g,int h){

[Link](g + h);

double sum(int g,int h){

[Link](g + h);

publicstaticvoid main(String args[]){


Object Oriented Programming using Java 24CSK42

overloadRetType ob =new overloadRetType();

int result = [Link](20,20);

//The above line will produce a compile Time Error ....

The above program will generate a compile-time error. Here, Java cannot determine which
sum() method to call and hence creates an error if you want to overload like this by using the
return type. Overloading methods offer no specific benefit to the JVM, but it is useful to the
program to have several ways do the same things but with different parameters.
Here are some other examples to show Method Overloading:

Program to Demonstrate Method Overloading Based on the Number of Parameters


Example:
class DispOvrload

public void show(char ch)

[Link] ("You have typed the letter: "+ch);

public void show(char ch, char ch1)

[Link]("You have typed the letter: "+ch+", and "+ ch1);

class Main

{
Object Oriented Programming using Java 24CSK42

public static void main (String args[])

DispOvrload o1 =new DispOvrload();

[Link]('G');

[Link]('S','J');

Output:
You have typed the letter: G

You have typed the letter: S, and J

Program to Demonstrate Method Overloading Based on the Sequence of Data Type in the
Parameters
Example:
class DispOvrload

public void show(char ch,int numb)

[Link] ("The 'show method' is defined for the first time.");

public void show(int numb ,char ch)

[Link] ("The 'show method' is defined for the second time.");

class Main
Object Oriented Programming using Java 24CSK42

public static void main (String args[])

DispOvrload o1 =new DispOvrload();

[Link]('G',62);

[Link](46,'S');

Output:
The 'show method' is defined for the first time.

The 'show method' is defined for the second time.

Advantages of Method Overloading

• It is used to perform a task efficiently with smartness in programming.


• It increases the readability of the program.
• The Method overloading allows methods that perform proximately related functions to
be accessed using a common name with slight variation in argument number or types.
• They can also be implemented on constructors allowing different ways to initialize
objects of a class.

Disadvantages of Method Overloading

• It's esoteric. Not very easy for the beginner to opt this programming technique and go
with it.
• It requires more significant effort spent on designing the architecture (i.e., the
arguments' type and number) to up front, at least if programmers' want to avoid
massive code from rewriting.
Object Oriented Programming using Java 24CSK42

1.11 Constructor in java

Constructor is a block of code that initializes the newly created object. A constructor resembles an
instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and
method are different (More on this at the end of this guide). People often refer constructor as special
type of method in Java.

Constructor has same name as the class and looks like this in a java code.

public class MyClass{


//This is the constructor
MyClass(){
}
..
}
Note that the constructor name matches with the class name and it doesn’t have a return type.

How does a constructor work


To understand the working of constructor, lets take an example. lets say we have a class MyClass.
When we create the object of MyClass like this:

MyClass obj =newMyClass()


The new keyword here creates the object of class MyClass and invokes the constructor to initialize this
newly created object.
You might feel a bit confused at this point because we haven’t discussed initialization examples yet.
So let’s look at a simple constructor example to understand how initialization works in Java.
In this program, we create an object obj of the class Hello and then print its instance variable name.

The output is: [Link]

This happens because the value "[Link]" was passed to the constructor when the object
was created, and the constructor assigned this value to the instance variable name. This clearly shows
that the constructor gets invoked automatically at the time of object creation.
In this example, this keyword is used inside the constructor. The keyword this refers to the current
object, which in our case is the object obj. We will study this keyword in detail in the next tutorial.
Object Oriented Programming using Java 24CSK42

public class Hello{


String name;
//Constructor
Hello(){
[Link] ="[Link]";
}
public static void main(String[] args){
Hello obj =new Hello();
[Link]([Link]);
}

}
Output:

[Link]

Types of Constructors

There are three types of constructors: Default, No-arg constructor and Parameterized.
Object Oriented Programming using Java 24CSK42
Default constructor
If you do not implement any constructor in your class, Java compiler inserts a default constructor into
your code on your behalf. This constructor is known as default constructor. You would not find it in
your source code (the java file) as it would be inserted into the code during compilation and exists in
.class file. This process is shown in the diagram below:

If you implement any constructor then you no longer receive a default constructor from Java compiler.

no-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor; however, body can have any code unlike default constructor where the body of the
constructor is empty.

Although you may see some people claim that that default and no-arg constructor is same but in fact
they are not, even if you write public Demo() { } in your class Demo it cannot be called default
constructor since you have written the code of it.

Example: no-arg constructor

classDemo
{
publicDemo()
{
[Link]("This is a no argument constructor");
}
publicstaticvoid main(String args[]){
newDemo();
}
}

Output:
This is a no argument constructor
Object Oriented Programming using Java 24CSK42

Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized


constructor.
Example 1: parameterized constructor
In this example we have a parameterized constructor with two parameters id and name.
While creating the objects obj1 and obj2 I have passed two arguments so that this
constructor gets invoked after creation of obj1 and obj2.

Output:
public class Employee{

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id,String name){
[Link] = id;
[Link] =
name;
}
void info(){
[Link]("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 =new Employee(10245,"Chaitanya");
Employee obj2 =new Employee(92232,"Negan");
[Link]();
[Link]();
}
}
Output:

Id:10245Name:Chaitanya
Id:92232Name:Negan
Object Oriented Programming using Java 24CSK42

Example2: parameterized constructor

In this example, we have two constructors, a default constructor and a parameterized


constructor. When we do not pass any parameter while creating the object using new
keyword then default constructor is invoked, however when you pass a parameter then
parameterized constructor that matches with the passed parameters list gets invoked.

class Example2
{
private intvvar;
//default constructor
public Example2()
{
[Link]=10;
}
//parameterized constructor
public Example2(int num)
{
[Link]= num;
}

public int getValue()


{
return var;
}
public static void main(String args[])
{
Example2 obj =new Example2();
Example2 obj2 =new Example2(100);
[Link]("var is: "+[Link]());
[Link]("var is: "+[Link]());
}
}

Output:

varis:10
varis:100
Object Oriented Programming using Java 24CSK42

What if you implement only parameterized constructor in class

classExample3
{
privateintvar;
publicExample3(int num)
{
var=num;
}
publicint getValue()
{
returnvar;
}
publicstaticvoid main(String args[])
{
Example3 myobj =newExample3();
[Link]("value of var is: "+[Link]());
}
}
Output:
It will throw a compilation error. The reason is, the statement Example3 myobj = new Example3() is invoking a
default constructor which we don’t have in our program. when you don’t implement any constructor in your
class, compiler inserts the default constructor into your code, however when you implement any constructor (in
above example I have implemented parameterized constructor with int parameter), then you don’t receive the
default constructor by compiler into your code.

If we remove the parameterized constructor from the above code then the program would run fine, because then
compiler would insert the default constructor into your code
Object Oriented Programming using Java 24CSK42

1.14 Static method in java

Java static keyword

1. Static variable
2. Program of the counter without static variable
3. Program of the counter with static variable
4. Static method
5. Restrictions for the static method
6. Why is the main method static?
7. Static block
8. Can we execute a program without main method?

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
Object Oriented Programming using Java 24CSK42

Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college" refers to the common property
of all objects. If we make it static, this field will get the memory only once.

Java static property is shared to all objects.

Example of static variable

//Java Program to demonstrate the use of static variable


class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
Object Oriented Programming using Java 24CSK42

void display (){[Link](rollno+" "+name+" "+college);}


}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");

Student s2 = new Student(222,"Aryan");


//we can change the college of all objects by the single line of code
//[Link]="BBDIT";
[Link]();
[Link]();
}
}

Output:

111 Karan ITS


222 Aryan ITS
Object Oriented Programming using Java 24CSK42

Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object
will have the value 1 in the count variable.
Object Oriented Programming using Java 24CSK42
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.

class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
[Link](count);

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:

1
1
1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new
Counter2(); Counter2
c2=new Counter2();
Object Oriented Programming using Java 24CSK42
Counter2 c3=new
Counter2();
}
}

Output:

1
2
3

Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method

//Java Program to demonstrate the use of a static method.

class Student{ int


rollno; String
name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){ college
= "BBDIT";
}
//constructor to initialize the variable Student(int
r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){[Link](rollno+" "+name+" "+college);}
}
Object Oriented Programming using Java 24CSK42

//Test class to create and display the values of object


public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}}

Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of a static method that performs a normal calculation

//Java Program to get the cube of a given number using the static method

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=[Link](5);
[Link](result);
}
}
Output:125

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method cannot use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
Object Oriented Programming using Java 24CSK42
class A{
int a=40;//non static

public static void main(String args[]){


[Link](a);
}
}
Output:
Compile Time Error

Q) Why is the Java main method static?

Ans) It Q) Why is the


is because the Java main
object method
is not static?
required to call a static method. If it were a non-static
method,Ans)
JVMItcreates an object
is because first then
the object callrequired
is not main() to
method
call athat will
static lead theIf problem
method. it of
were a allocation.
extra memory non-static method, JVM creates an object first then call main()
method that will lead the problem of extra memory allocation.
Java static block

o Is used to initialize the static data member.


o It is executed before the main method at the time of classloading.

Example of static block

1. class A2{
2. static{[Link]("static block is invoked");}
3. public static void main(String args[]){
4. [Link]("Hello main");
5. }
6. }
Output:
static block is invoked
Hello main

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK
1.7, it is not possible to execute a Java class without the main method.

1. class A3{
static{
2. [Link]("static block is invoked");
3. [Link](0);
4. }
5. }
Output:
static block is invoked
Object Oriented Programming using Java 24CSK42

1.15 this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.

Usage of java this keyword

Here is given the 6 usages of java this keyword.

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


ii. this can be used to invoke current class method (implicitly)
iii. this() can be used to invoke current class constructor.
iv. this can be passed as an argument in the method call.
v. this can be passed as argument in the constructor call.
vi. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.
Object Oriented Programming using Java 24CSK42

1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:
1. class Student{
2. int rollno;
Object Oriented Programming using Java 24CSK42
3. String name;

4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){[Link](rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. [Link]();
17. [Link]();
18. }}

Output:

0 null 0.0
0 null 0.0

In the above 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

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=fee;
9. }
10. void display(){[Link](rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. [Link]();
18. [Link]();
19. }}
Object Oriented Programming using Java 24CSK42

Output:

111 ankit 5000


112 sumit 6000

If local variables(formal arguments) and instance variables are different, there


is no need to use this keyword like in the following program:
Object Oriented Programming using Java 24CSK42

Question Bank:
Sl No Questions Marks
1 Define the Java Development Kit (JDK). 5 marks
2 List the primary Java buzzwords and their meanings. 5 marks
3 What is bytecode in Java? 5 marks
4 Define JVM and explain its role. 5 marks
5 List different Java primitive data types. 5 marks
6 State the syntax rules for declaring arrays in Java. 5 marks

7 What are control statements in Java? Name any three. 5 marks


8 Define method overloading with a simple example. 5 marks
9 What is the purpose of a constructor in Java? 5 marks
10 What is the function of the this keyword? 5 marks
11 Define the Java Development Kit (JDK). 5 marks
12 List the primary Java buzzwords and their meanings. 5 marks
13 What is bytecode in Java? 5 marks
14 Define JVM and explain its role. 5 marks
15 List different Java primitive data types. 5 marks
16 State the syntax rules for declaring arrays in Java. 5 marks
17 What are control statements in Java? Name any three. 5 marks
18 Define method overloading with a simple example. 5 marks
19 What is the purpose of a constructor in Java? 5 marks
20 Explain the relationship between JVM, JDK, and JRE. 10 marks
21 Describe how Java achieves platform independence. 10 marks

22 Explain how arrays are stored and accessed in Java. 10 marks

23 Illustrate the use of command-line arguments in Java with an example. (10) 10 marks
Object Oriente Programming using Java 24CSK42

2
24CSK42 OOPs with Java

79
Object Oriented Programming using JAVA 24CSK42

MODULE 2
Inheritance and Interfacing

Inheritance, Method Overriding, Annotations, Static


members, Inner Classes, Abstract Classes, Final
members and classes, The Object Class, Interfaces,
Package Fundamentals, Reflections

2.1 INTRODUCTION TO INHERITANCE:

Inheritance in Java is a core OOP concept that allows a class to acquire properties and
behaviours from another class. Inheritance is a mechanism in which one object acquires all
the properties and behaviors of parent object. Inheritance represents the IS-A relationship,
also known as parent- child relationship. It helps in creating a new class from an existing
class, promoting code reusability and better organization.

• A subclass can reuse the fields and methods of the parent class without rewriting the
code

• A subclass can add its own fields and methods or modify existing ones to extend
functionality.

Why use inheritance in java:

• For Method Overriding (so runtime polymorphism can be achieved).


• For Code Reusability.

Syntax of Java Inheritance

class Base_class_name

{ //Access_specifier data declaration

//Access_specifier member_function(parameter_list);

Page 1 of 102
Object Oriented Programming using JAVA 24CSK42

class Subclass_name extends Superclass_name

{ //methods and fields

Inheritance:

• One class can acquire the properties of another class.


• A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.

Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance


variables and methods defined by the superclass and adds its own, unique elements.

To inherit a class, simply incorporate the definition of one class into another by using the
extends keyword. The following program creates a superclass called A and a subclass called
B. The keyword extends is used to create a subclass of A.

// Create a Base class or superclass.

class A

{ int i, j;

void showij()

{ [Link]("i and j: " + i + " " + j);

// Create a subclass by extending class A.

class B extends A

{ int k;

void showk()
Page 2 of 102
Object Oriented Programming using JAVA 24CSK42

{ [Link]("k: " + k);

void sum()
{ [Link]("i+j+k: " + (i+j+k));

class SimpleInheritance {

public static void main(String args[])

{ A superOb = new A();

B subOb = new B(); // The superclass may be used by itself.

superOb.i = 10;

superOb.j = 20;

[Link]("Contents of superOb: ");

[Link]();

[Link]();

/* The subclass has access to all public members of its superclass. */

subOb.i = 7; subOb.j = 8; subOb.k = 9;

[Link]("Contents of subOb: ");

[Link]();

[Link]();

[Link]();

[Link]("Sum of i, j and k in subOb:");

[Link]();

Page 3 of 102
Object Oriented Programming using JAVA 24CSK42

output: Contents of superOb: i and j: 10 20

Contents of subOb: i and j: 7 8 k: 9

Sum of i, j and k in subOb: i+j+k: 24

The subclass B includes all of the members of its superclass, A. This is why subOb can access
i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if they were
part of B.

Even though A is a superclass for B, it is also a completely independent, stand-alone class.


Being a superclass for a subclass does not mean that the superclass cannot be used by itself.

A subclass can be a superclass for another subclass. Java does not support the inheritance of
multiple super classes into a single subclass. But a subclass can become a superclass of
another subclass. However, no class can be a superclass of itself.

Advantages of Inheritance in Java

[Link] of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code

[Link] in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.

[Link] can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a method
is super class

[Link] - facility to use public methods of base class without rewriting the same.

[Link] - extending the base class logic as per business logic of the derived class.

Disadvantages of Inheritance in Java

• Complexity: Inheritance can make the code more complex and harder to understand.
This is especially true if the inheritance hierarchy is deep or if multiple inheritances
is used.
Page 4 of 102
Object Oriented Programming using JAVA 24CSK42

• Tight Coupling: Inheritance creates a tight coupling between the superclass and
subclass, making it difficult to make changes to the superclass without affecting the
subclass.

Types of Inheritance:

Java supports three primary types of inheritance with classes: single, multilevel,
and hierarchical. Multiple and hybrid inheritance are only achievable through the use
of interfaces, not classes.

Here are the types of inheritance in Java:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance

Figure: Types of Inheritance in Java

• Single Inheritance: In single inheritance, a sub-class is derived from only one super
class. It inherits the properties and behavior of a single-parent class. Sometimes, it is
also known as simple inheritance. In this type, a single subclass extends one
superclass. This is the simplest form of inheritance and represents a direct "is-a"
relationship (e.g., a Dog is an Animal).

Program Code:

Page 5 of 102
Object Oriented Programming using JAVA 24CSK42

//Super class

class Vehicle {

Vehicle() {

[Link]("This is a Vehicle");

// Subclass

class Car extends Vehicle {

Car() {

[Link]("This Vehicle is Car");

public class Test {

public static void main(String[] args) {

// Creating object of subclass invokes base class constructor

Car obj = new Car();

Output:

This is a Vehicle

This Vehicle is Car

Page 6 of 102
Object Oriented Programming using JAVA 24CSK42

• Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a


base class and as well as the derived class also acts as the base class for other classes.
This involves a chain of inheritance, where a class inherits from a class which itself
inherits from another class (e.g., Puppy extends Dog extends Animal). The subclass
has access to members of all ancestor classes in the chain.

Program Code:

class Vehicle {

Vehicle() {

[Link]("This is a Vehicle");

class FourWheeler extends Vehicle {

FourWheeler() {

[Link]("4 Wheeler Vehicles");

class Car extends FourWheeler {

Car() {

[Link]("This 4 Wheeler Vehicle is a Car");

public class Geeks {

public static void main(String[] args) {

Page 7 of 102
Object Oriented Programming using JAVA 24CSK42

Car obj = new Car(); // Triggers all constructors in order

Output:

This is a Vehicle

4 Wheeler Vehicles

This 4 Wheeler Vehicle is a Car

• Hierarchical Inheritance: In hierarchical inheritance, more than one subclass is


inherited from a single base class. i.e. more than one derived class is created from a
single base class. In this structure, multiple subclasses inherit from a single parent
class (e.g., both Car and Bus extend the Vehicle class). This is useful for creating
multiple specialized classes that share common base functionality. For example, cars
and buses both are vehicle.

Program Code:

class Vehicle {

Vehicle() {

[Link]("This is a Vehicle");

class Car extends Vehicle {

Car() {

[Link]("This Vehicle is Car");

Page 8 of 102
Object Oriented Programming using JAVA 24CSK42

class Bus extends Vehicle {

Bus() {

[Link]("This Vehicle is Bus");

public class Test {

public static void main(String[] args) {

Car obj1 = new Car();

Bus obj2 = new Bus();

Output:

This is a Vehicle

This Vehicle is Car

This is a Vehicle

This Vehicle is Bus

Java does not support following inheritance types:

• Multiple Inheritance: Java does not support a class inheriting directly from more
than one superclass to avoid ambiguity issues (known as the "diamond problem").
• Hybrid Inheritance: This is a combination of two or more types of inheritance. Since
it can involve multiple inheritance paths, it is not directly supported with classes in
Java but can be achieved using a combination of class inheritance and interfaces.

Page 9 of 102
Object Oriented Programming using JAVA 24CSK42

Member Access and Inheritance

Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.

// Create a superclass.

Class A

{ int i; // public by default private

int j; // private to A

void setij(int x, int y)

{ i = x; j = y;

} // A's j is not accessible here.

class B extends A

{ int total;

void sum()

{ total = i + j; // ERROR, j is not accessible here

class Access

{ public static void main(String args[])

{ B subOb = new B();

[Link](10, 12);

[Link]();

[Link]("Total is " + [Link]);


Page 10 of 102
Object Oriented Programming using JAVA 24CSK42

This program will not compile because the reference to j inside the sum( ) method of B causes
an access violation. Since j is declared as private, it is only accessible by other members of its
own class. Subclasses have no access to it.

Practical Example: The Box class developed will be extended to include a fourth component
called weight. Thus, the new class will contain a box’s width, height, depth, and weight.

// This program uses inheritance to extend Box.

class Box

{ double width; double height; double depth;

// construct clone of an object

Box(Box ob)

{ // pass object to constructor

width = [Link];

height = [Link];

depth = [Link];

// constructor used when all dimensions specified

Box(double w, double h, double d)

{ width = w; height = h; depth = d;

Page 11 of 102
Object Oriented Programming using JAVA 24CSK42

// constructor used when no dimensions specified

Box()

{ width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

// constructor used when cube is created

Box(double len)

{ width = height = depth = len;

// compute and return volume

double volume()

{ return width * height * depth;

// Here, Box is extended to include weight.

class BoxWeight extends Box

{ double weight; // weight of box

// constructor for BoxWeight

BoxWeight(double w, double h, double d, double m)

{ width = w; height = h; depth = d; weight = m; }

Page 12 of 102
Object Oriented Programming using JAVA 24CSK42

class DemoBoxWeight

{ public static void main(String args[])

{ BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);

BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);

double vol;

vol = [Link]();

[Link]("Volume of mybox1 is " + vol);

[Link]("Weight of mybox1 is " + [Link]);


[Link]();

vol = [Link]();

[Link]("Volume of mybox2 is " + vol);

[Link]("Weight of mybox2 is " + [Link]);

Output:

Volume of mybox1 is 3000.0 Weight of mybox1 is

34.3 Volume of mybox2 is

24.0 Weight of mybox2 is 0.076

A Superclass Variable Can Reference a Subclass Object

A reference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.

Class RefDemo

{ public static void main(String args[])

Page 13 of 102
Object Oriented Programming using JAVA 24CSK42

{ BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);

Box plainbox = new Box();

double vol;

vol = [Link]();

[Link]("Volume of weightbox is " + vol);

[Link]("Weight of weightbox is " + [Link]);


[Link]();

// assign BoxWeight reference to Box reference

plainbox = weightbox;

vol = [Link](); // OK, volume() defined in Box


[Link]("Volume of plainbox is " + vol);

/* The following statement is invalid because plainbox does not define a weight
member.*/

[Link]("Weight of plainbox is " + [Link]);

Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box


objects. Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference
to the weightbox object.

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent
class object. Whenever you create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.

Page 14 of 102
Object Oriented Programming using JAVA 24CSK42

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal

{ String color="white";

class Dog extends Animal

{ String color="black";

void printColor()

{ [Link](color);//prints color of Dog class

[Link]([Link]);//prints color of Animal class

class TestSuper

{ public static void main(String args[])

{ Dog d=new Dog();

[Link]();

}
Page 15 of 102
Object Oriented Programming using JAVA 24CSK42

Output:

black

white

In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

class Animal

{ void eat()

{ [Link]("eating...");

class Dog extends Animal

{ void eat()

{ [Link]("eating bread...");

void bark()

{ [Link]("barking...");

Page 16 of 102
Object Oriented Programming using JAVA 24CSK42

void work()

{ [Link]();

bark();

class TestSuper

{ public static void main(String args[])

{ Dog d=new Dog();

[Link]();

Output:

eating...

barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local. To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor. The super keyword can also be used
to invoke the parent class constructor. Let's see a simple example:

class Animal

{ Animal()

{ [Link]("animal is created");}

Page 17 of 102
Object Oriented Programming using JAVA 24CSK42

class Dog extends Animal

{ Dog()

{ super();

[Link]("dog is created");

class TestSuper

{ public static void main(String args[])

{ Dog d=new Dog();

Output:

animal is created

dog is created

Creating a Multilevel Hierarchy: Given three classes called A, B, and C, C can be a subclass
of B, which is a subclass of A. When this type of situation occurs, each subclass inherits all of
the traits found in all of its super classes.

In this case, C inherits all aspects of B and A. In it, the subclass BoxWeight is used as a
superclass to create the subclass called Shipment. Shipment inherits all of the traits of
BoxWeight and Box, and adds a field called cost, which holds the cost of shipping such a
parcel.

class Box

{ private double width; private double height;

private double depth;

Page 18 of 102
Object Oriented Programming using JAVA 24CSK42

// construct clone of an object

Box(Box ob)

{ width = [Link]; height = [Link]; depth = [Link];

Box(double w, double h, double d)

{ width = w; height = h; depth = d; }

// constructor used when no dimensions specified

Box()

{ width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

Box(double len)

{ width = height = depth = len; }

double volume()

{ return width * height * depth;

// Add weight.

class BoxWeight extends Box

{ double weight;

BoxWeight(BoxWeight ob)

Page 19 of 102
Object Oriented Programming using JAVA 24CSK42

{ super(ob);

weight = [Link];

BoxWeight(double w, double h, double d, double m)

{ super(w, h, d);

weight = m;

BoxWeight()

{ super();

weight = -1;

BoxWeight(double len, double m)

{ super(len);

weight = m;

// Add shipping costs.

class Shipment extends BoxWeight

{ double cost;

Shipment(Shipment ob)

{ super(ob);

cost = [Link];

Page 20 of 102
Object Oriented Programming using JAVA 24CSK42

Shipment(double w, double h, double d,double m, double c)

{ super(w, h, d, m); // call superclass constructor

cost = c;

Shipment()

{ super(); cost = -1;

Shipment(double len, double m, double c)

{ super(len, m);

cost = c;

class DemoShipment

{ public static void main(String args[])

{ Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);

Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);

double vol;

vol = [Link]();

[Link]("Volume of shipment1 is " + vol);

[Link]("Weight of shipment1 is " + [Link]);


[Link]("Shipping cost: $" + [Link]);

[Link]();
Page 21 of 102
Object Oriented Programming using JAVA 24CSK42

vol = [Link]();

[Link]("Volume of shipment2 is " + vol);


[Link]("Weight of shipment2 is " + [Link]);
[Link]("Shipping cost: $" + [Link]);

Output : Volume of shipment1 is 3000.0

Weight of shipment1 is 10.0

Shipping cost: $3.41

Volume of shipment2 is 24.0

Weight of shipment2 is 0.76

Shipping cost: $1.28

When Constructors Are Called: Given a subclass called B and a superclass called A, is A’s
constructor called before B’s, or vice versa? The answer is that in a class hierarchy,
constructors are called in order of derivation, from superclass to subclass.

Further, since super( ) must be the first statement executed in a subclass’ constructor, this
order is the same whether or not super( ) is used.

class A

{ A()

{ [Link]("Inside A's constructor.");

class B extends A

{ B()

{ [Link]("Inside B's constructor.");

Page 22 of 102
Object Oriented Programming using JAVA 24CSK42

class C extends B

{ C()

{ [Link]("Inside C's constructor.");

class CallingCons

{ public static void main(String args[])

{ C c = new C();

Output :

Inside A’s constructor

Inside B’s constructor

Inside C’s constructor

2,2 METHOD OVERRIDING:

Method overriding allows us to achieve run-time polymorphism and is used for writing
specific definitions of a subclass method that is already defined in the superclass. The method
is superclass and overridden method in the subclass should have the same declaration
signature such as parameters list, type, and return type.

When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.

Example: Program Code

Page 23 of 102
Object Oriented Programming using JAVA 24CSK42

class A

{ int i, j;

A(int a, int b)

{ i = a;

j = b;

// display i and j

void show()

{ [Link]("i and j: " + i + " " + j);

class B extends A

{ int k

B(int a, int b, int c)

{ super(a, b); k = c;

void show()

{ [Link]("k: " + k);

class Override

{ public static void main(String args[])

Page 24 of 102
Object Oriented Programming using JAVA 24CSK42

{ B subOb = new B(1, 2, 3);

[Link](); // this calls show() in B

Output: k: 3

The version of show( ) inside B overrides the version declared in A. To access the superclass
version of an overridden method can be called using super.

class B extends A

{ int k;

B(int a, int b, int c)

{ super(a, b); k = c;

void show()

{ [Link](); // this calls A's show()

[Link]("k: " + k);

Output: i and j: 1 2 k: 3

Here, [Link]( ) calls the superclass version of show( ).

Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded.

class A

{ int i, j;

Page 25 of 102
Object Oriented Programming using JAVA 24CSK42

A(int a, int b)

{ i = a; j = b;

// display i and j

void show()

{ [Link]("i and j: " + i + " " + j);

// Create a subclass by extending class A.

class B extends A

{ int k;

B(int a, int b, int c)

{ super(a, b);

k = c;

// overload show()

void show(String msg)

{ [Link](msg + k);

class Override

{ public static void main(String args[])

{ B subOb = new B(1, 2, 3);

Page 26 of 102
Object Oriented Programming using JAVA 24CSK42

[Link]("This is k: "); // this calls show() in B

[Link](); // this calls show() in A

The output produced by this program is shown here:

This is k: 3 i and j: 1 2

Advantage of Method Overriding

The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class code.

This is helpful when a class has several child classes, so if a child class needs to use the parent
class method, it can use it and the other classes that want to have different implementation
can use overriding feature to make changes without touching the parent class code.

Dynamic Method Dispatch

Method Overriding is an example of runtime polymorphism. When a parent class reference


points to the child class object then the call to the overridden method is determined at
runtime, because during method call which method(parent class or child class) is to be
executed is determined by the type of object. This process in which call to the overridden
method is resolved at runtime is known as dynamic method dispatch.

class ABC

{ //Overridden method

public void disp()

{ [Link]("disp() method of parent class");

Page 27 of 102
Object Oriented Programming using JAVA 24CSK42

class Demo extends ABC

{ //Overriding method

public void disp()

{ [Link]("disp() method of Child class");

public void newMethod()

{ [Link]("new method of child class");

public static void main( String args[])

{ /*When Parent class reference refers to the parent class object then in this case
overridden method (the method of parent class) is called. */

ABC obj = new ABC();

[Link]();

/* When parent class reference refers to the child class object then the
overriding method (method of child class) is called. This is called dynamic
method dispatch and runtime polymorphism. */

ABC obj2 = new Demo();

[Link]();

Output:

disp() method of parent class

Page 28 of 102
Object Oriented Programming using JAVA 24CSK42

disp() method of Child class

In the above example the call to the disp() method using second object (obj2) is runtime
polymorphism (or dynamic method dispatch).

Note: In dynamic method dispatch the object can call the overriding methods of child class
and all the non-overridden methods of base class but it cannot call the methods which are
newly declared in the child class. In the above example the object obj2 is calling the disp().
However if you try to call the newMethod() method (which has been newly declared in Demo
class) using obj2 then you would give compilation error .

Super keyword in Method Overriding

The super keyword is used for calling the parent class method/constructor.
[Link]() calls the myMethod() method of base class while super() calls the
constructor of base class. Let’s see the use of super in method Overriding.

As we know that we we override a method in child class, then call to the method using child
class object calls the overridden method. By using super we can call the overridden method
as shown in the example below:

class ABC{

public void myMethod()

[Link]("Overridden method");

class Demo extends ABC{

public void myMethod(){

//This will call the myMethod() of parent class

[Link]();

Page 29 of 102
Object Oriented Programming using JAVA 24CSK42

[Link]("Overriding method");

public static void main( String args[]) {

Demo obj = new Demo();

[Link]();

Output:

Class ABC: mymethod()

Class Test: mymethod()

2.3 ANNOTATIONS IN JAVA:

Annotations in Java are a form of metadata that provide additional information about the
program. They do not change the action of a compiled program but can be used by the
compiler or runtime for processing. An annotation is a form of metadata that provides
information about the code without changing its behavior.

Used by: Compiler, Build tools, Frameworks (Spring, Hibernate, JUnit)

• Annotations start with ‘@’.

• Annotations do not change the action of a compiled program.

• Annotations help to associate metadata (information) to the program elements i.e.


instance variables, constructors, methods, classes, etc.

• Annotations are not pure comments as they can change the way a program is treated
by the compiler. See below code for example.

• Annotations basically are used to provide additional information, so could be an


alternative to XML and Java marker interfaces.

Page 30 of 102
Object Oriented Programming using JAVA 24CSK42

Hierarchy of Annotations in Java

Figure: Hierarchy of Annotations in Java

Java includes several built-in annotations. Here are some of the most commonly used:

Annotation Description

@Override Indicates that a method overrides a method in a superclass

@Deprecated Marks a method or class as outdated or discouraged from use

@SuppressWarnings Tells the compiler to ignore certain warnings

@Override Annotation

The @Override annotation helps the compiler check that a method really overrides a method
from a superclass. It's not required, but it's highly recommended because it helps catch
errors.

In this example, we clearly indicate that we are overriding a method:

class Animal {

void makeSound() {

Page 31 of 102
Object Oriented Programming using JAVA 24CSK42

[Link]("Animal sound");

class Dog extends Animal {

@Override

void makeSound() {

[Link]("Woof!");

Output: Woof!

@Deprecated Annotation

The @Deprecated annotation warns developers not to use a method because it may be
removed or replaced in the future:

public class Main {

@Deprecated

static void oldMethod() {

[Link]("This method is outdated.");

public static void main(String[] args) {

oldMethod(); // This will show a warning in most IDEs

Output: This method is outdated.


Page 32 of 102
Object Oriented Programming using JAVA 24CSK42

@SuppressWarnings Annotation

The @SuppressWarnings annotation tells the compiler to ignore specific warnings, like
"unchecked" or "deprecation":

import [Link];

public class Main {

@SuppressWarnings("unchecked")

public static void main(String[] args) {

ArrayList cars = new ArrayList();

[Link]("Volvo");

[Link](cars);

Output: [Volvo]

Categories of Annotations: There are broadly 5 categories of annotations as listed:

• Marker Annotations
• Single value Annotations
• Full Annotations
• Type Annotations
• Repeating Annotations

1. Marker Annotations: Do not have any elements or values (just presence is enough). Used
to signal the compiler or tools with metadata.

Example: @TestAnnotation()

2. Single value Annotations: Contain only one element (can use shorthand notation). When
specifying value, you don’t need to write the element name.

Page 33 of 102
Object Oriented Programming using JAVA 24CSK42

Example: @TestAnnotation(“testing”);

3. Full Annotations : Contain multiple elements as key-value pairs. All values must be
provided unless defaults are defined.

Example: @TestAnnotation(owner=”Rahul”, value=”Class Geeks”)

4. Type Annotations: Introduced in Java 8 for annotating types (variables, generics, return
types). Useful for stronger type checking and frameworks.

Declared with @Target(ElementType.TYPE_USE).

Example: Java Program to Demonstrate Type Annotation

import [Link];

import [Link];

// Using target annotation to annotate a type

@Target(ElementType.TYPE_USE)

// Declaring a simple type annotation

@interface TypeAnnoDemo{

// Main class

public class GFG {

// Main driver method

public static void main(String[] args) {

// Annotating the type of a string

@TypeAnnoDemo String string = "I am annotated with a type annotation";

[Link](string);

abc();

Page 34 of 102
Object Oriented Programming using JAVA 24CSK42

// Annotating return type of a function

static @TypeAnnoDemo int abc() {

[Link]("This function's return type is annotated");

return 0;

Output

I am annotated with a type annotation

This function's return type is annotated

5. Repeating Annotations: Allow the same annotation to be applied multiple times on a


single element. Declared using @Repeatable with a container annotation.

Example: @Schedule(day="Monday") @Schedule(day="Tuesday").

Example: Java Program to Demonstrate a Repeatable Annotation

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

// Make Words annotation repeatable

@Retention([Link])

@Repeatable([Link])

@interface Words

{
Page 35 of 102
Object Oriented Programming using JAVA 24CSK42

String word() default "Hello";

int value() default 0;

// Create container annotation

@Retention([Link])

@interface MyRepeatedAnnos

Words[] value();

public class Main {

// Repeat Words on newMethod

@Words(word = "First", value = 1)

@Words(word = "Second", value = 2)

public static void newMethod()

Main obj = new Main();

try {

Class<?> c = [Link]();

// Obtain the annotation for newMethod

Method m = [Link]("newMethod");

// Display the repeated annotation

Annotation anno

Page 36 of 102
Object Oriented Programming using JAVA 24CSK42

= [Link]([Link]);

[Link](anno);

catch (NoSuchMethodException e) {

[Link](e);

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

Output:

@MyRepeatedAnnos({@Words(value=1,word="First"),@Words(value=2,
word="Second")})

From [Link]

1. @Documented

Marks annotations to be included in generated Javadoc.

Improves API documentation clarity.

2. @Target

Specifies where the annotation can be applied (class, method, field, etc.).

Prevents misuse of annotations in wrong places.

3. @Inherited

Allows a subclass to inherit an annotation from its parent class.

Useful in frameworks where annotations define behavior across hierarchies.

User-defined (Custom) Annotation


Page 37 of 102
Object Oriented Programming using JAVA 24CSK42

User-defined annotations can be used to annotate program elements, i.e. variables,


constructors, methods, etc. These annotations can be applied just before the declaration of
an element (constructor, method, classes, etc).

Syntax

[Access Specifier] @interface<AnnotationName>

DataType <Method Name>() [default value];

Do keep these certain points as rules for custom annotations before implementing user-
defined annotations.

• AnnotationName is an interface.
• The parameter should not be associated with method declarations and throws clause
should not be used with method declaration.
• Parameters will not have a null value but can have a default value.
• Default value is optional.
• The return type of method should be either primitive, enum, string, class name or
array of primitive, enum, string or class name type.

Example: Java Program to Demonstrate User-defined Annotations

package source;

import [Link];

import [Link];

import [Link];

// User-defined annotation

@Documented

Page 38 of 102
Object Oriented Programming using JAVA 24CSK42

@Retention([Link])

@ interface TestAnnotation

String Developer() default "Rahul";

String Expirydate();

} // will be retained at runtime

// Driver class that uses @TestAnnotation

public class Test

@TestAnnotation(Developer="Rahul", Expirydate="01-10-2020")

void fun1()

[Link]("Test method 1");

@TestAnnotation(Developer="Anil", Expirydate="01-10-2021")

void fun2()

[Link]("Test method 2");

public static void main(String args[])

[Link]("Hello");

Page 39 of 102
Object Oriented Programming using JAVA 24CSK42

Output: Hello

2.4 STATIC MEMBERS:

In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.

The static keyword can be used with methods, fields, classes (inner/nested), blocks.

Static Methods − You can create a static method by using the keyword static. Static methods
can access only static fields, methods. To access static methods there is no need to instantiate
the class, you can do it just using the class name as −

Example

public class MyClass {

public static void sample(){

[Link]("Hello");

public static void main(String args[]){

[Link]();

Output: Hello

Static Fields − You can create a static field by using the keyword static. The static fields have
the same value in all the instances of the class. These are created and initialized when the
class is loaded for the first time. Just like static methods you can access static fields using the
class name (without instantiation).

Page 40 of 102
Object Oriented Programming using JAVA 24CSK42

Example

public class MyClass {

public static int data = 20;

public static void main(String args[]){

[Link]([Link]);

Output: 20

Static Blocks − These are a block of codes with a static keyword. In general, these are used
to initialize the static members. JVM executes static blocks before the main method at the
time of class loading.

Example

public class MyClass {

static{

[Link]("Hello this is a static block");

public static void main(String args[]){

[Link]("This is main method");

Output

Hello this is a static block

This is main method

Page 41 of 102
Object Oriented Programming using JAVA 24CSK42

2.5 INNER CLASS

An inner class is a class declared inside the body of another class. The inner class has access
to all members (including private) of the outer class, but the outer class can access the inner
class members only through an object of the inner class.

The most important type of nested class is the inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class and may refer
to them directly in the same way that other non-static members of the outer class do.

Syntax:

class OuterClass {

// Outer class members

class InnerClass {

// Inner class members

Example1: The following program illustrates how to define and use an inner class. The class
named OuterClass has one instance method named display(), and defines one inner class
called InnerClass.

public class OuterClass {

class InnerClass {

void display() {

[Link]("Hello from Inner Class!");

public static void main(String[] args) {

OuterClass outer = new OuterClass();

Page 42 of 102
Object Oriented Programming using JAVA 24CSK42

InnerClass inner = [Link] InnerClass();

[Link]();

Output: Hello from Inner Class!

Example 2: The following program illustrates how to define and use an inner class. The class
named Outer has one instance variable named outer_x, one instance method named test( ),
and defines one inner class called Inner.

// Demonstrate an inner class.

class Outer {

int outer_x = 100;

void test() {

Inner inner = new Inner();

[Link]();

// this is an inner class

class Inner {

void display() {

[Link]("display: outer_x = " + outer_x);

Page 43 of 102
Object Oriented Programming using JAVA 24CSK42

class InnerClassDemo {

public static void main(String args[]) {

Outer outer = new Outer();

[Link]();

Output:

display: outer_x = 100

In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. An instance
method named display( ) is defined inside Inner. This method displays outer_x on the
standard output stream. The main( ) method of InnerClassDemo creates an instance of
class Outer and invokes its test( ) method. That method creates an instance of class Inner
and the display( ) method is called.

Note: An instance of Inner can be created only in the context of class Outer. The Java compiler
generates an error message otherwise. In general, an inner class instance is often created by
code within its enclosing scope, as the example does.

Although we have been focusing on inner classes declared as members within an outer

class scope, it is possible to define inner classes within any block scope. For example, you

can define a nested class within the block defined by a method or even within the body of

a for loop, as this next program shows:

// Define an inner class within a for loop.

class Outer {

int outer_x = 100;

Page 44 of 102
Object Oriented Programming using JAVA 24CSK42

void test() {

for(int i=0; i<10; i++) {

class Inner {

void display() {

[Link]("display: outer_x = " + outer_x);

Inner inner = new Inner();

[Link]();

class InnerClassDemo {

public static void main(String args[]) {

Outer outer = new Outer();

[Link]();

Output:

display: outer_x = 100

display: outer_x = 100

display: outer_x = 100

Page 45 of 102
Object Oriented Programming using JAVA 24CSK42

display: outer_x = 100

display: outer_x = 100

display: outer_x = 100

display: outer_x = 100

display: outer_x = 100

display: outer_x = 100

display: outer_x = 100

While nested classes are not applicable to all situations, they are particularly helpful when
handling events.

Features of Inner Classes

• Encapsulation: Inner classes can access private members of the outer class,
providing better encapsulation.

• Code Organization: Logically groups classes that belong together, making code more
readable.

• Access to Outer Class: Inner class instances have a reference to the outer class
instance.

• Namespace Management: Helps avoid naming conflicts by nesting related classes.

Types of Inner Classes

Java supports four types of inner classes:

1. Member Inner Class

2. Method-Local Inner Class

3. Static Nested Class

4. Anonymous Inner Class

Page 46 of 102
Object Oriented Programming using JAVA 24CSK42

Member Inner Class

A member inner class is a non-static class defined at the member level of another class. It has
access to all members of the outer class, including private members.

• Must be instantiated with an outer class instance.

• Syntax: [Link] inner = [Link] Inner();

class Outer {

private int outerVar = 100;

// Member inner class

class Inner {

void display() {

[Link]("Outer variable: " + outerVar);

class Main {

public static void main(String[] args) {

// Creating inner class instance

Page 47 of 102
Object Oriented Programming using JAVA 24CSK42

[Link] inner = new Outer().new Inner();

[Link]();

Output:

Inside outerMethod

Inside innerMethod

Method Local Inner Class: A method-local inner class is defined inside a method of the
outer class. It can only be instantiated within the method where it is defined.

Cannot access non-final local variables before Java 8. From Java 8 onwards, can access
effectively final local variables. Cannot be declared as private, protected, static, or transient.
Can be declared as abstract or final, but not both.

class Outer {

void outerMethod() {

int x = 98; // Effectively final

[Link]("Inside outerMethod");

class Inner {

void innerMethod() {

[Link]("x = " + x);

Inner inner = new Inner();

[Link]();

Page 48 of 102
Object Oriented Programming using JAVA 24CSK42

class Main {

public static void main(String[] args) {

Outer outer = new Outer();

[Link]();

Output:

Inside outerMethod

x = 98

Static Nested Classes

A static nested class is a static class defined inside another class. It does not have access to
instance members of the outer class but can access static members.

class Outer {

private static int staticVar = 50;

// Static nested class

static class Inner {

void display() {

[Link]("Static variable: " + staticVar);

}
Page 49 of 102
Object Oriented Programming using JAVA 24CSK42

class Main {

public static void main(String[] args) {

[Link] inner = new [Link](); // No need for outer class instance

[Link]();

Output: Static variable: 50

2.6 ABSTRACT CLASSES

In Java, an abstract class is a class that cannot be instantiated and is designed to be extended
by other classes. It is used to achieve partial abstraction, where some methods are
implemented while others are left for subclasses to define. An abstract class is declared using
the abstract keyword. It may contain:

• Abstract methods (methods without a body)


• Concrete methods (methods with implementation)
• Constructors
• Instance variables
• Static and final methods

Syntax:

abstract class ClassName {

abstract void methodName(); // Abstract method

void concreteMethod() { // Concrete method

[Link]("Method implementation");

Page 50 of 102
Object Oriented Programming using JAVA 24CSK42

Example: Abstract Class with Constructor and Methods.

import [Link].*;

abstract class Subject {

Subject() {

[Link]("Learning Subject");

abstract void syllabus();

void Learn(){

[Link]("Preparing Right Now!");

class IT extends Subject {

void syllabus(){

[Link]("C , Java , C++");

class GFG {

public static void main(String[] args) {

Subject x=new IT();

[Link]();

[Link]();

Page 51 of 102
Object Oriented Programming using JAVA 24CSK42

Output: avinash

21

222.2

Example: Abstract Class with Partial Abstraction

abstract class Shape {

String color;

Shape(String color) { // Constructor

[Link] = color;

abstract double area(); // Abstract method

void getColor() { // Concrete method

[Link]("Color: " + color);

class Circle extends Shape {

int radius;

Circle(String color, int radius) {

super(color);

[Link] = radius;

double area() {

Page 52 of 102
Object Oriented Programming using JAVA 24CSK42

return 3.14 * radius * radius;

public class GFG{

public static void main(String[] args) {

Shape s = new Circle("Red", 5);

[Link]();

[Link]("Area: " + [Link]());

Example 3: The following version of the program declares area( ) as abstract inside Figure.
This, of course, means that all classes derived from Figure must override area( )

// Using abstract methods and classes.

abstract class Figure {

double dim1;

double dim2;

Figure(double a, double b) {

dim1 = a;

dim2 = b;

// area is now an abstract method

abstract double area();

}
Page 53 of 102
Object Oriented Programming using JAVA 24CSK42

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a, b);

// override area for rectangle

double area() {

[Link]("Inside Area for Rectangle.");

return dim1 * dim2;

class Triangle extends Figure {

Triangle(double a, double b) {

super(a, b);

// override area for right triangle

double area() {

[Link]("Inside Area for Triangle.");

return dim1 * dim2 / 2;

class AbstractAreas {

public static void main(String args[]) {

Page 54 of 102
Object Oriented Programming using JAVA 24CSK42

// Figure f = new Figure(10, 10); // illegal now

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

Figure figref; // this is OK, no object is created

figref = r;

[Link]("Area is " + [Link]());

figref = t;

[Link]("Area is " + [Link]());

As the comment inside main( ) indicates, it is no longer possible to declare objects of type
Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To
prove this to yourself, try creating a subclass that does not override area( ). You will receive
a compile-time error.

Although it is not possible to create an object of type Figure, you can create a reference
variable of type Figure. The variable figref is declared as a reference to Figure, which
means that it can be used to refer to an object of any class derived from Figure. As
explained, it is through superclass reference variables that overridden methods are
resolved at run time.

2.7 FINAL MEMBERS & CLASSES:

The final keyword is a non-access modifier used to restrict modification. It applies to variable
for not changing its value, methods cannot be overridden and classes cannot be extended. It
helps create constants, control inheritance and enforce fixed behavior.

The following are different contexts where the final is used:

1. Variable

Page 55 of 102
Object Oriented Programming using JAVA 24CSK42

2. Method

3. Class

Using final to Prevent Overriding

While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared as final cannot be
overridden. The following fragment illustrates final:

class A {

final void meth() {

[Link]("This is a final method.");

class B extends A {

void meth() { // ERROR! Can't override.

[Link]("Illegal!");

Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a


compile-time error will result.

The binding which can be resolved at compile time by the compiler is known as static or
early binding. Binding of all the static, private and final methods is done at compile-time.

In the late binding or dynamic binding, the compiler doesn't decide the method to be
called. Overriding is a perfect example of dynamic binding. In overriding both parent and
child classes have the same method.

Page 56 of 102
Object Oriented Programming using JAVA 24CSK42

Example for Early Binding:

public class NewClass {

public static class superclass {

static void print() {

[Link](&quot;print in superclass.&quot;);

public static class subclass extends superclass {

static void print() {

[Link](&quot;print in subclass.&quot;);

public static void main(String[] args)

{ superclass A = new superclass();

superclass B = new subclass();

[Link]();

[Link]();

Output:

print in superclass.

print in superclass.

Page 57 of 102
Object Oriented Programming using JAVA 24CSK42

Example for Late Binding:

public class NewClass {

public static class superclass {

void print() {

[Link](&quot;print in superclass.&quot;); }

public static class subclass extends superclass {

@Override

void print() {

[Link](&quot;print in subclass.&quot;);

public static void main(String[] args)

{ superclass A = new superclass();

superclass B = new subclass();

[Link]();

[Link]();

Output:

print in superclass.

print in subclass.

Page 58 of 102
Object Oriented Programming using JAVA 24CSK42

Advantages of final Keyword

• Supports immutability by preventing reassignment

• Helps compiler and JVM optimize code in some scenarios

• Makes behavior predictable since values or methods stay unchanged

• Prevents accidental or unauthorized modification of critical logic

• Preserves API contracts by avoiding unwanted overriding

Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.

Here is an example of a final class:

final class A {

//...

// The following class is illegal.

class B extends A { // ERROR! Can't subclass A

//...

As the comments imply, it is illegal for B to inherit A since A is declared as final.

Page 59 of 102
Object Oriented Programming using JAVA 24CSK42

2.8 THE OBJECT CLASS


Object class (in [Link]) is the root of the Java class hierarchy. Every class in Java either
directly or indirectly extends Object. It provides essential methods like toString(), equals(),
hashCode(), clone() and several others that support object comparison, hashing, debugging,
cloning and synchronization.

Why Object Class?

• Acts as the root of all Java classes


• Defines essential methods shared by all objects
• Provides default behavior for printing, comparing and cloning objects
• Supports thread communication (wait(), notify(), notifyAll())

Object Class Methods

1. toString() Method: toString() provides a String representation of an object and is used to


convert an object to a String.

class Student{

String name = "Vishnu";

int age = 21;

@Override

public String toString(){

Page 60 of 102
Object Oriented Programming using JAVA 24CSK42

return "Student{name='" + name + "', age=" + age + "}";

public static void main(String[] args) {

Student s = new Student();

// Calls overridden toString()

[Link]([Link]());

Output

Student{name='Vishnu', age=21}

Explanation: Overridden toString() prints a custom readable string for the object

2. hashCode() Method: hashCode() method returns the hash value of an object (not its
memory address). Used heavily in hash-based collections like HashMap, HashSet, etc.

class Employee{

int id = 101;

@Override

public int hashCode(){

return id * 31; // Simple custom hash

public static void main(String[] args) {

Employee e = new Employee();

[Link]([Link]());

Page 61 of 102
Object Oriented Programming using JAVA 24CSK42

Output

3131

Explanation: hashCode() returns an integer value used in hashing-based collections like


HashMap. If two objects are equal, they must produce the same hash code..

3. equals(Object obj) Method

equals() method compares the given object with the current object. It is recommended to
override this method to define custom equality conditions.

class Book{

String title;

Book(String title) {

[Link] = title;

@Override

public boolean equals(Object obj){

Book b = (Book) obj;

return [Link]([Link]);

public static void main(String[] args) {

Book b1 = new Book("Java");

Book b2 = new Book("Java");

[Link]([Link](b2)); // true

Output

true

Page 62 of 102
Object Oriented Programming using JAVA 24CSK42

Explanation: equals() compares objects based on content rather than reference. Must be
overridden when custom comparison logic is needed.

4. getClass() method: getClass() method returns the class object of "this" object and is used
to get the actual runtime class of the object.

public class Hello{

public static void main(String[] args)

Object o = new String("HelloWorld");

Class c = [Link]();

[Link]("Class of Object o is: " + [Link]());

Output

Class of Object o is: [Link]

Explanation: The getClass() method is used to print the runtime class of the "o" object.

5. finalize() method: finalize() method is invoked by the Garbage Collector just before an
object is destroyed. It runs when the object has no remaining references. You can override
finalize() to release system resources and perform cleanup, but its use is discouraged in
modern Java.

public class Geeks {

public static void main(String[] args) {

Geeks t = new Geeks();

[Link]([Link]());

t = null;

// calling garbage collector

Page 63 of 102
Object Oriented Programming using JAVA 24CSK42

[Link]();

[Link]("end");

@Override protected void finalize()

[Link]("finalize method called");

Output

1510467688

end

finalize method called

Explanation: The finalize() method is called just before the object is garbage collected.

6. clone() method: clone() method creates and returns a new object that is a copy of the
current object.

class Student implements Cloneable{

int id = 1;

String name = "Vishnu";

@Override

public Object clone() throws CloneNotSupportedException{

return [Link](); // shallow copy

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

Student s1 = new Student();

Student s2 = (Student) [Link]();

Page 64 of 102
Object Oriented Programming using JAVA 24CSK42

[Link]([Link]); // Vishnu

[Link]([Link]); // Vishnu

Output

Vishnu

Vishnu

Explanation: clone() creates a copy of the current object (shallow copy by default). Class must
implement Cloneable or else it throws CloneNotSupportedException.

7. Concurrency Methods: wait(), notify() and notifyAll(): These methods are related to
thread Communication in Java. They are used to make threads wait or notify others in
concurrent programming.

import [Link].*;

public class Book implements Cloneable {

private String t; // title

private String a; // author

private int y; // year

public Book(String t, String a, int y)

this.t = t;

this.a = a;

this.y = y;

// Override the toString method

@Override public String toString()

Page 65 of 102
Object Oriented Programming using JAVA 24CSK42

return t + " by " + a + " (" + y + ")";

// Override the toString method

@Override public String toString()

return t + " by " + a + " (" + y + ")";

// Override the equals method

@Override public boolean equals(Object o)

if (o == null || !(o instanceof Book)) {

return false;

Book other = (Book)o;

return [Link]([Link]()) && [Link]([Link]()) && this.y ==


[Link]();

// Override the hashCode method

@Override public int hashCode()

int res = 17;

res = 31 * res + [Link]();

res = 31 * res + [Link]();

res = 31 * res + y;

return res;

Page 66 of 102
Object Oriented Programming using JAVA 24CSK42

// Override the clone method

@Override public Book clone()

try {

return (Book)[Link]();

catch (CloneNotSupportedException e) {

throw new AssertionError();

// Override the finalize method

@Override protected void finalize() throws Throwable

[Link]("Finalizing " + this);

public String getTitle() { return t; }

public String getAuthor() { return a; }

public int getYear() { return y; }

public static void main(String[] args)

// Create a Book object and print its details

Book b1 = new Book(

"The Hitchhiker's Guide to the Galaxy",

"Douglas Adams", 1979);

Page 67 of 102
Object Oriented Programming using JAVA 24CSK42

[Link](b1);

// Create a clone of the Book object and print its details

Book b2 = [Link]();

[Link](b2);

// Check if the two objects are equal

[Link]("b1 equals b2: " + [Link](b2));

// Get the hash code of the two objects

[Link]("b1 hash code: "+ [Link]());

[Link]("b2 hash code: "+ [Link]());

// Set book1 to null to trigger garbage collection and finalize method

b1 = null;

[Link]();

Output

The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)

The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)

b1 equals b2: true

b1 hash code: 1840214527

b2 hash code: 1840214527

Explanation: The above example demonstrates the use of toString(), equals(), hashCode()
and clone() methods in the Book class.

Page 68 of 102
Object Oriented Programming using JAVA 24CSK42

2.9 INTERFACES IN JAVA


An Interface in Java is an abstract type that defines a set of methods a class must implement.

• An interface acts as a contract that specifies what a class should do, but not how it
should do it. It is used to achieve abstraction and multiple inheritance in Java. We
define interfaces for capabilities (e.g., Comparable, Serializable, Drawable).
• A class that implements an interface must implement all the methods of the
interface. Only variables are public static final by default.

Before Java 8, interfaces could only have abstract methods (no bodies). Since Java 8, they can
also include default and static methods (with implementation) and since Java 9, private
methods are allowed.

This example demonstrates how an interface in Java defines constants and abstract methods,
which are implemented by a class.

Example Program:

import [Link].*;

// Interface Declared

interface testInterface {

// public, static and final

final int a = 10;

// public and abstract

void display();

Page 69 of 102
Object Oriented Programming using JAVA 24CSK42

// Class implementing interface

class TestClass implements testInterface {

// Implementing the capabilities of Interface

public void display(){

[Link]("Geek");

class Geeks{

public static void main(String[] args){

TestClass t = new TestClass();

[Link]();

[Link](t.a);

Output

Geek

10

Note:

Private methods can only be called inside default or static methods.

Static methods are accessed using the interface name, not via objects.

To implement an interface, use the implements keyword.

Relationship Between Class and Interface

A class can extend another class and similarly, an interface can extend another interface.
However, only a class can implement an interface and the reverse (an interface implementing
a class) is not allowed

Page 70 of 102
Object Oriented Programming using JAVA 24CSK42

Figure: Relationship between Classes and Interfaces

When to Use Class and Interface?

Use a Class when:

Use a class when you need to represent a real-world entity with attributes (fields) and
behaviors (methods). Use a class when you need to create objects that hold state and perform
actions. Classes are used for defining templates for objects with specific functionality and
properties.

Use an Interface when:

Use an interface when you need to define a contract for behavior that multiple classes can
implement. Interface is ideal for achieving abstraction and multiple inheritance.

Let’s consider the example of Vehicles like bicycles, cars and bikes share common
functionalities, which can be defined in an interface, allowing each class (e.g., Bicycle, Car,
Bike) to implement them in its own way. This approach ensures code reusability, scalability
and consistency across different vehicle types.

import [Link].*;

interface Vehicle {

// Abstract methods defined

void changeGear(int a);

Page 71 of 102
Object Oriented Programming using JAVA 24CSK42

void speedUp(int a);

void applyBrakes(int a);

// Class implementing vehicle interface

class Bicycle implements Vehicle{

int speed;

int gear;

// Change gear

@Override

public void changeGear(int newGear){

gear = newGear;

// Increase speed

@Override

public void speedUp(int increment){

speed = speed + increment;

// Decrease speed

@Override

public void applyBrakes(int decrement){

speed = speed - decrement;

public void printStates() {

[Link]("speed: " + speed + " gear: " + gear); }

Page 72 of 102
Object Oriented Programming using JAVA 24CSK42

class Main

public static void main (String[] args)

// Instance of Bicycle(Object)

Bicycle bicycle = new Bicycle();

[Link](2);

[Link](3);

[Link](1);

[Link]("Bicycle present state : ");

[Link]();

// Instance of Bike (Object)

Bike bike = new Bike();

[Link](1);

[Link](4);

[Link](3);

[Link]("Bike present state : ");

[Link]();

Output

Bicycle present state : speed: 2 gear: 2

Bike present state : speed: 1 gear: 1

Multiple Inheritance in Java Using Interface: Java does not support multiple
inheritance with classes to avoid ambiguity, but it supports multiple inheritance using interfaces.

Page 73 of 102
Object Oriented Programming using JAVA 24CSK42

Figure: Multiple Inheritance in Java

import [Link].*;

// Add interface

interface Add{

int add(int a,int b);

// Sub interface

interface Sub{

int sub(int a,int b);

// Calculator class implementing Add and Sub

class Cal implements Add , Sub

// Method to add two numbers

public int add(int a,int b){

return a+b;

Page 74 of 102
Object Oriented Programming using JAVA 24CSK42

// Method to sub two numbers

public int sub(int a,int b){

return a-b;

class GFG{

// Main Method

public static void main (String[] args){

// instance of Cal class

Cal x = new Cal();

[Link]("Addition : " + [Link](2,1));

[Link]("Substraction : " + [Link](2,1));

Output

Addition : 3

Substraction : 1

New Features Added in Interfaces in JDK 8

There are certain features added to Interfaces in JDK 8 update mentioned below:

1. Default Methods

Interfaces can define methods with default implementations.

Useful for adding new methods to interfaces without breaking existing implementations.

interface TestInterface

{ final int a = 10;

Page 75 of 102
Object Oriented Programming using JAVA 24CSK42

default void display() {

[Link]("hello");

// A class that implements the interface.

class TestClass implements TestInterface

// Driver Code

public static void main (String[] args) {

TestClass t = new TestClass();

[Link]();

Output

hello

2. Static Methods

Interfaces can now include static methods. These methods are called directly using the interface
name and are not inherited by implementing classes.

Another feature that was added in JDK 8 is that we can now define static methods in interfaces
that can be called independently without an object. These methods are not inherited.

3. Functional Interface

Functional interfaces can be used with lambda expressions or method [Link] @Functional
Interface annotation can be used to indicate that an interface is a functional interface, although it’s
optional.

@FunctionalInterface

public interface Calculator {

Page 76 of 102
Object Oriented Programming using JAVA 24CSK42

int compute(int x, int y); // single abstract method

New Features Added in Interfaces in JDK 9

From Java 9 onwards, interfaces can contain the following also:

1. Private Methods

Interfaces can now include private [Link] methods are defined within the interface but it
cannot be accessed by the implementing [Link] methods cannot be overridden by
implementing classes as they are not inherited.

interface Vehicle {

// Private method for internal use

private void startEngine() {

[Link]("Engine started.");

// Default method that uses the private method

default void drive() {

// Calls the private method

startEngine();

[Link]("Vehicle is now driving.");

class Car implements Vehicle {

// Car class implements Vehicle interface and inherits the default method 'drive'

public class Main {

public static void main(String[] args) {

Car car = new Car();

Page 77 of 102
Object Oriented Programming using JAVA 24CSK42

// This will call the default method, which in turn calls the private method

[Link]();

Output

Engine started.

Vehicle is now driving.

Extending Interfaces

One interface can inherit another by the use of keyword extends. When a class implements an
interface that inherits another interface, it must provide an implementation for all methods required
by the interface inheritance chain.

interface A {

void method1();

void method2();

// B now includes method1 and method2

interface B extends A {

void method3();

// the class must implement all method of A and B.

class GFG implements B

public void method1() {

[Link]("Method 1");

Page 78 of 102
Object Oriented Programming using JAVA 24CSK42

public void method2()

{ [Link]("Method 2");

public void method3()

{ [Link]("Method 3");

public static void main(String[] args)

{ // Instance of GFG class created

GFG x = new GFG();

// All Methods Called

x.method1();

x.method2();

x.method3();

Output

Method 1

Method 2

Method 3

Page 79 of 102
Object Oriented Programming using JAVA 24CSK42

Difference Between Class and Interface

Although Class and Interface seem the same there are certain differences between Classes and
Interface

2.10 PACKAGE FUNDAMENTALS


A package in Java is a mechanism to group related classes, interfaces, and sub-packages into
a single unit. Packages help organize large applications, avoid naming conflicts, provide
access protection, and make code modular and maintainable. A package in Java is a
namespace that organizes a set of related classes and interfaces. It is known as a folder in a
file system in which the related files (classes, interfaces, etc.) are stored together.

Page 80 of 102
Object Oriented Programming using JAVA 24CSK42

Java packages help in logically grouping classes and interfaces, making code more modular,
readable, and easier to maintain.

• Avoiding name conflicts (two classes with the same name can exist in different
packages)
• Providing access control using public, protected, and default access
• Reusability: packaged code can be imported and used anywhere
• Encouraging modular programming

Importance of Using Packages in Java:

• Code Organization and Maintainability: Packages group related classes, making your
code more organized and easier to maintain. Large codebases are simpler to
navigate and modify.
• Prevention of Naming Conflicts: By using packages, you can avoid conflicts between
classes that have the same name but serve different purposes by isolating them in
different namespaces.
• Enhanced Modularity and Reusability: Packages promote modular programming.
You can design components in packages that can be reused across different projects
without interference.
• Better Access Control and Security: Packages provide access modifiers (e.g., public,
private) to control the visibility of classes, methods, and variables, enhancing
security and encapsulation.
• Simplified Maintenance and Updates: With packages, you can easily update or
modify specific parts of your program without affecting other unrelated parts,
leading to more efficient and less error-prone maintenance.

Types of Java Packages:

Page 81 of 102
Object Oriented Programming using JAVA 24CSK42

Built-in Packages: Built-in Packages comprise a large number of classes that are part of the
Java API. The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.

The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles website:
[Link]

The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contain all the classes that
belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

Syntax:

import [Link]; // Import a single class

import [Link].*; // Import the whole package

Import a Class

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

Example:

import [Link];

In the example above, [Link] is a package, while Scanner is a class of the [Link] package.

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation.

In our example, we will use the nextLine() method, which is used to read a complete line:

Example: Using the Scanner class to get user input:

import [Link];

Page 82 of 102
Object Oriented Programming using JAVA 24CSK42

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

String userName = [Link]();

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

Import a Package

There are many packages to choose from. In the previous example, we used the Scanner class
from the [Link] package. This package also contains date and time facilities, random-
number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the [Link] package:

Example: import [Link].*;

Some of the commonly used built-in packages are:

• [Link]: Contains language support classes(e.g, classes that define primitive data
types, math operations). This package is automatically imported.
• [Link]: Contains classes for supporting input/output operations.
• [Link]: Contains utility classes that implement data structures such as Linked Lists
and Dictionaries, as well as support for date and time operations.
• [Link]: Contains classes for creating Applets.
• [Link]: Contains classes for implementing the components for graphical user
interfaces.

Page 83 of 102
Object Oriented Programming using JAVA 24CSK42

The Java API is grouped into several core packages to support various programming needs, such
as utility functions, input/output handling, networking, and GUI design.

Example: Using [Link] (Built-in Package)

import [Link]; // built-in package

public class GFG{

public static void main(String[] args) {

// using Random class

Random rand = new Random();

// generates a number between 0–99

int number = [Link](100);

[Link]("Random number: " + number);

Example : [Link] and [Link]

import [Link];

Page 84 of 102
Object Oriented Programming using JAVA 24CSK42

import [Link];

public class UtilPackageDemo {

public static void main(String[] args) {

// Using Date class

Date currentDate = new Date();

[Link]("Current Date and Time: " +currentDate);

// Using Calendar class

Calendar cal = [Link]();

[Link]("Year: " + [Link]([Link]));

[Link]("Month: " + ([Link]([Link]) +1)); // 0-based

[Link]("Day: " +[Link](Calendar.DAY_OF_MONTH));

}}

Example : [Link] & Class:

public class LangPackageDemo {

public static void main(String [] args) {

// Using Object class methods

String name = "Java";

[Link]("Hash Code: " + [Link]());

[Link] ("ToString: " + [Link]());

// Using Class class

Class<?> cls = [Link]();

[Link]("Class Name: " + [Link]());

}}

Example : [Link] InputStream and OutputStream:

import [Link];

Page 85 of 102
Object Oriented Programming using JAVA 24CSK42

import [Link];

import [Link];

public class IOPackageDemo {

public static void main(String[] args) {

try {

// Writing to file

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

String data = "Welcome to Java IO!";

[Link]([Link]());

[Link]();

// Reading from file

FileInputStream fis = new FileInputStream("[Link]");

int i;

[Link]("File Content: ");

while ((i = [Link]()) != -1) {

[Link]((char) i);

[Link](); }

catch (IOException e) {

[Link]();

Page 86 of 102
Object Oriented Programming using JAVA 24CSK42

User-defined Packages:
A user-defined package is a package created by the programmer to group related classes and
interfaces. These packages are designed to group related classes and interfaces specific to an
application or project. User-defined packages help developers avoid class name conflicts, organize
their code, and increase the modularity and reusability of the codebase.

Creating a User-Defined Package

To create a user-defined package, you simply use the package keyword at the beginning of
your Java file.

First We Should Choose A Name For The Package We Are Going To Create And Include. The
package command In The first line in the java program source code. Further inclusion of classes,
interfaces, annotation types, etc that is required in the package can be made in the package. For
example, the below single statement creates a package name called “FirstPackage”.

Syntax: To declare the name of the package to be created. The package statement simply defines
in which package the classes defined belong.

package FirstPackage ;

Implementation: To Create a Class Inside A Package

● First Declare The Package Name As The First Statement Of Our Program.

● Then We Can Include A Class As A Part Of The Package.

Example 1: Creating a Class Inside a Package

// Name of package to be created

package FirstPackage;

// Class in which the above created package belong to

class Welcome {

// main driver method

public static void main(String[] args)

Page 87 of 102
Object Oriented Programming using JAVA 24CSK42

// Print statement for the successful

// compilation and execution of the program

[Link](

"This Is The First Program Geeks For Geeks..");

So Inorder to generate the above-desired output first do use the commands as specified use the
following specified commands

Procedure to Generate Output:

1. Compile the [Link] file:

Command: javac [Link]

2. This command creates a [Link] file. To place the class file in the appropriate package
directory, use:

Command: javac -d . [Link]

3. This command will create a new folder called FirstPackage. To run the class, use:

Command: java [Link]

Output: The Above Will Give The Final Output Of The Example Program.

Example 2: Another Package Example

// Name of package to be created

package data;

// Class to which the above package belongs

public class Demo {

// Member functions of the class- 'Demo'

// Method 1 - To show()

Page 88 of 102
Object Oriented Programming using JAVA 24CSK42

public void show()

// Print message

[Link]("Hi Everyone");

// Method 2 - To show()

public void view()

// Print message

[Link]("Hello");

Again, in order to generate the above-desired output first do use the commands as specified use
the following specified commands

Procedure:

1. Compile the [Link] file:

Command: javac [Link]

2. This command will generate a [Link] file:

Command: javac -d . [Link]

3. This command will create a new folder called data containing the [Link] file.

Note: In data [Link] & [Link] File should be present

Example 3: Accessing Data from Another Program

// Name of the package

import data.*;

// Class to which the package belongs

Page 89 of 102
Object Oriented Programming using JAVA 24CSK42

class ncj {

// main driver method

public static void main(String arg[])

// Creating an object of Demo class

Demo d = new Demo();

// Calling the functions show() and view()

// using the object of Demo class

[Link]();

[Link]();

Procedure to Generate the Output:

1. Compile the [Link] file:

Command: javac [Link]

2. The above command compiles [Link] and requires the [Link] file to be present in the
data package.

Command: java ncj

// To Run This File

Output: Generated on the terminal after the above command Is executed

Hi Everyone

Hello

Page 90 of 102
Object Oriented Programming using JAVA 24CSK42

Access protection in java packages

In java, the access modifiers define the accessibility of the class and its members. For
example, private members are accessible within the same class members only. Java has four
access modifiers, and they are default, private, protected, and public.

In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility
of class members across the different packages.

In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.

Access of class and Interfaces in Java:

Page 91 of 102
Object Oriented Programming using JAVA 24CSK42

Default Access (Package-Private)

When no access modifier is used, it is accessible only within the same package.

package pack1;

class A {

int x = 10; // default access

✔ Accessible inside pack1

Not accessible outside pack1

Public Access

Accessible from anywhere, inside or outside the package.

package pack1;

public class A {

public int x = 10;

✔ Same package

✔ Different package

✔ Subclasses

✔ Non-subclasses

Protected Access (Important for Packages)


protected members are:

● Accessible within the same package

● Accessible in subclasses outside the package

package pack1;

public class A {

Page 92 of 102
Object Oriented Programming using JAVA 24CSK42

protected int x = 10;

package pack2;

import pack1.A;

class B extends A {

void show() {

[Link](x); // allowed

Cannot be accessed by non-subclass in another package.

Private Access
Accessible only within the same class.

class A {

private int x = 10;

Package-Level Protection (Key Concept)


➡ Default and protected access provide package-level protection

● Prevents unauthorized access from outside packages


● Helps in encapsulation
● Useful when building large applications

2.11 REFLECTIONS IN JAVA


Reflection is a feature in the Java programming Reflection is a feature in the Java programming
language. It allows an executing Java program to examine or "introspect" upon itself, and
manipulate internal properties of the program. For example, it's possible for a Java class to obtain
the names of all its members and display them.

Page 93 of 102
Object Oriented Programming using JAVA 24CSK42

The ability to examine and manipulate a Java class from within itself may not sound like very
much, but in other programming languages this feature simply doesn't exist. For example, there is
no way in a Pascal, C, or C++ program to obtain information about the functions defined within
that program.

One tangible use of reflection is in JavaBeans, where software components can be manipulated
visually via a builder tool. The tool uses reflection to obtain the properties of Java components
(classes) as they are dynamically loaded.

A Simple Example: To see how reflection works, consider this simple example:

import [Link].*;

public class DumpMethods {

public static void main(String args[])

try {

Class c = [Link](args[0]);

Method m[] = [Link]();

for (int i = 0; i < [Link]; i++)

[Link](m[i].toString());

catch (Throwable e) {

[Link](e);

For an invocation of:

java DumpMethods [Link]

the output is:

public [Link] [Link](

Page 94 of 102
Object Oriented Programming using JAVA 24CSK42

[Link])

public synchronized

[Link] [Link]()

public synchronized

[Link] [Link]()

public boolean [Link]()

public synchronized

int [Link]([Link])

That is, the method names of class [Link] are listed, along with their fully qualified
parameter and return types.

This program loads the specified class using [Link], and then calls
getDeclaredMethods to retrieve the list of methods defined in the class.
[Link] is a class representing a single class method.

Setting Up to Use Reflection

The reflection classes, such as Method, are found in [Link]. There are three steps
that must be followed to use these classes. The first step is to obtain a [Link] object
for the class that you want to manipulate. [Link] is used to represent classes and
interfaces in a running Java program.

One way of obtaining a Class object is to say:

Class c = [Link]("[Link]"); to get the Class object for String. Another


approach is to use: Class c = [Link]; or Class c = [Link]; to obtain Class information
on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper
(such as Integer) for the fundamental type.

The second step is to call a method such as getDeclaredMethods, to get a list of all the
methods declared by the [Link] this information is in hand, then the third step is to use
the reflection API to manipulate the information. For example, the sequence:

Class c = [Link]("[Link]");
Page 95 of 102
Object Oriented Programming using JAVA 24CSK42

Method m[] = [Link](); [Link](m[0].toString());

will display a textual representation of the first method declared in String.

In the examples below, the three steps are combined to present self contained illustrations
of how to tackle specific applications using reflection.

Simulating the instanceof Operator

Once Class information is in hand, often the next step is to ask basic questions about the Class
object. For example, the [Link] method can be used to simulate the instanceof
operator:

class A {}

public class instance1 {

public static void main(String args[])

try {

Class cls = [Link]("A");

boolean b1

= [Link](new Integer(37));

[Link](b1);

boolean b2 = [Link](new A());

[Link](b2);

catch (Throwable e) {

[Link](e);

Page 96 of 102
Object Oriented Programming using JAVA 24CSK42

In this example, a Class object for A is created, and then class instance objects are checked to
see whether they are instances of A. Integer(37) is not, but new A() is.

Finding Out About Methods of a Class

One of the most valuable and basic uses of reflection is to find out what methods are defined
within a class. To do this the following code can be used:

import [Link].*;

public class method1 {

private int f1(

Object p, int x) throws NullPointerException

if (p == null)

throw new NullPointerException();

return x;

public static void main(String args[])

try {

Class cls = [Link]("method1");

Method methlist[]

= [Link]();

for (int i = 0; i < [Link]; i++) {

Page 97 of 102
Object Oriented Programming using JAVA 24CSK42

Method m = methlist[i];

[Link]("name = " + [Link]());

[Link]("decl class = " +[Link]());

Class pvec[] = [Link]();

for (int j = 0; j < [Link]; j++)

[Link]("param #" + j + " " + pvec[j]);

Class evec[] = [Link]();

for (int j = 0; j < [Link]; j++)

[Link]("exc #" + j + " " + evec[j]);

[Link]("return type = " +[Link]());

[Link]("-----");

catch (Throwable e) {

[Link](e);

The program first gets the Class description for method1, and then calls getDeclaredMethods
to retrieve a list of Method objects, one for each method defined in the class. These include
public, protected, package, and private methods. If you use getMethods in the program
instead of getDeclaredMethods, you can also obtain information for inherited methods.

Page 98 of 102
Object Oriented Programming using JAVA 24CSK42

Once a list of the Method objects has been obtained, it's simply a matter of displaying the
information on parameter types, exception types, and the return type for each method. Each
of these types, whether they are fundamental or class types, is in turn represented by a Class
descriptor. The output of the program is:

name = f1

decl class = class method1

param #0 class [Link]

param #1 int

exc #0 class [Link]

return type = int

-----

name = main

decl class = class method1

param #0 class [[Link];

return type = void

Page 99 of 102
Object Oriented Programming using JAVA 24CSK42

Module Question Paper

1. What is inheritance in Java? Explain with an example.


2. What are the advantages of inheritance in object-oriented programming?
3. Explain the different types of inheritance supported in Java.
4. Why does Java not support multiple inheritance using classes?
5. What is the purpose of the super keyword?
6. Write a Java program where class Animal is inherited by class Dog and
demonstrate method inheritance.
7. Create a class Vehicle with properties speed and color. Derive a class Car and
display both properties.
8. Demonstrate multilevel inheritance using three classes: Person → Employee
→ Manager
9. What is method overriding in Java? What are the rules for method
overriding?
10. What is the difference between method overriding and method overloading?
11. What happens if the overridden method is declared final? Can static methods
be overridden? Explain.
12. Write a Java program demonstrating method overriding using Shape → Circle
classes.
13. Create a class Bank with method getInterestRate() and override it in
subclasses SBI, ICICI, and HDFC.
14. What are annotations in Java?
15. What is the purpose of @Override annotation? Explain @Deprecated
annotation with an example.
16. What is @SuppressWarnings used for? What are the types of annotations in
Java?
17. Write a Java program demonstrating the use of @Override.
18. Explain how custom annotations are created in Java.
19. What is a static variable in Java?

Page 100 of 102


Object Oriented Programming using JAVA 24CSK42

20. What is a static method? Can static methods access instance variables? Why
or why not?
21. What is a static block in Java? What is the difference between static and non-
static members?
22. Write a Java program demonstrating the use of a static variable to count
objects created.
23. Create a class with a static method that prints a message without creating an
object.
24. What is an inner class in Java? Explain the types of inner classes.
25. What is the difference between a static nested class and a non-static inner
class?
26. What is a local inner class? What is an anonymous inner class?
27. Write a Java program demonstrating a member inner class.
28. Write a Java program using an anonymous inner class to implement an
interface.
29. What is an abstract class in Java? What is an abstract method?
30. Can an abstract class have constructors? Explain. Can abstract classes contain
non-abstract methods?
31. What is the difference between abstract class and interface?
32. Write a Java program using abstract class Shape with abstract method area().
33. Create an abstract class Employee and implement it in subclasses Manager
and Clerk.
34. What is a final variable in Java? What is a final method?
35. What is a final class? Why is the String class declared final?
36. What happens if a class is declared final?
37. Write a program demonstrating a final variable.
38. Create a final class and attempt to inherit it. What happens?
39. What is the Object class in Java?
40. Why is the Object class considered the root class of Java?
41. Explain the toString() method.

Page 101 of 102


Object Oriented Programming using JAVA 24CSK42

42. What is the purpose of the equals() method? What is the hashCode()
method?
43. Write a program overriding toString() method.
44. Write a Java program demonstrating equals() method.
45. What is an interface in Java? What are the features of interfaces?
46. What is the difference between an interface and an abstract class? Can a class
implement multiple interfaces? Explain. What are default methods in
interfaces?
47. Write a Java program implementing an interface Printable.
48. Create an interface Shape and implement it in classes Circle and Rectangle.
49. What is a package in Java? What are the advantages of packages? What is the
difference between built-in packages and user-defined packages?
50. How do you create a package in Java? What is the purpose of the import
statement?
51. Write a Java program creating a user-defined package.
52. Write a program importing a specific class from a package.
53. What is reflection in Java? What is the purpose of the Class class?
54. How can reflection be used to inspect methods of a class? What are the
advantages of reflection? What are the limitations of reflection?
55. Write a Java program that prints all methods of a class using reflection.
56. Write a program to dynamically create an object using reflection.

Page 102 of 102


Object Oriented Programming Using Java 24CSK42

MODULE 3
String Manipulation and File Handling
String Constructors, Length Operations, Character
Extraction, Comparison, Searching, Modifying,
String Buffer, StringBuilder, Basic file I/O: File
Input Stream, File Output Stream, File Reader, File
Writer

3.1 Introduction to String


• String is set of characters enclosed within double quotes. String is class as well as
data type. String is non primitive data type. The default values for the string or
any class type is null
• String is pre-defined public final class present in the [Link] package.
• String class cannot be inherited because String is a final class. String objects are
immutable in nature
• Mutable version on string class are StringBuffer and StringBuilder. The String,
StringBuffer, and StringBuilder classes are defined in [Link]. Thus, they are
available to all programs automatically

String objects are created in two ways:


1. Without using new keyword(literals):
String s=”Raam”;
2. With new keyword:
String s=new String(“Raam”);
String objects will get stored inside memory location called as “String Pool”. String
pool is categorized into 2 parts. 1. Constant pool and 2. Non constant pool.
• String objects are created using new operator will get stored inside non
constant pool.
• String objects are created using literals will get stored inside constant pool.

Example:

New Horizon College of Engineering, Bengaluru 1|Page


Object Oriented Programming Using Java 24CSK42

class StringDemo {
public static void main(String[] args) {
// Without using new keyword(literals)
String s1 = "Hello";
String s2 = new String("World");
// Without using new keyword(literals)
[Link](s1); // Hello
[Link](s2); // World
}
}

3.2 String Constructors


• The String class supports several constructors.
a. To create an empty String, call the default constructor.
Example:
String s = new String ();

b. To create a String initialized by an array of characters, use the constructor


String(char chars[ ])
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
Example:
class StringConstructorDemo {
public static void main(String[] args) {
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
[Link](s); //abc
}
}

c. You can specify a subrange of a character array as an initializer using the


following constructor:
String(char chars[ ], int startIndex, int numChars)

New Horizon College of Engineering, Bengaluru 2|Page


Object Oriented Programming Using Java 24CSK42

Example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3); //cde

d. You can construct a String object that contains the same character
sequence as another String object using this constructor:
String(String strObj) -where strObj is a String object.
Example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
[Link](s1); //Java
[Link](s2); //Java
}
}

e. The String class provides constructors that initialize a string when given a
byte array. Two forms are shown here:
String(byte chrs[ ])
String(byte chrs[ ], int startIndex, int numChars)
In the above syntax , chrs specifies the array of bytes. The
second form allows you to specify a subrange. In each of these
constructors, the byte-to-character conversion is done by using the
default character encoding of the platform.

Example:
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);

New Horizon College of Engineering, Bengaluru 3|Page


Object Oriented Programming Using Java 24CSK42

[Link](s1); //A BC D E F
String s2 = new String(ascii, 2, 3); // C D E
[Link](s2);
}
}
NOTE: The contents of the array are copied whenever you create a
String object from an array. If you modify the contents of the array
after you have created the string, the String will be unchanged.

f. You can construct a String from a StringBuffer by using the constructor


shown here:
String(StringBuffer strBufObj)

Example:
public class StringBufferToStringExample {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer strBufObj = new StringBuffer("Hello, Java!");
// Create a String using the String(StringBuffer) constructor
String str = new String(strBufObj);
// Display both values
[Link]("StringBuffer value: " + strBufObj);
[Link]("String value: " + str);
}
}
Output:
StringBuffer value: Hello, Java!
String value: Hello, Java!

g. You can construct a String from a StringBuilder by using this constructor


shown here :
String(StringBuilder strBuildObj)

New Horizon College of Engineering, Bengaluru 4|Page


Object Oriented Programming Using Java 24CSK42

3.3 Length Operations


• The length of a string is the number of characters that it contains. To obtain this
value, call the length( ) method, shown here:
int length( )
• The following fragment prints "3", since there are three characters in the string s:

Example 1:
public class LengthDemo1 {
public static void main(String[] args) {
String text = "Hello, Java!";
int len = [Link]();
[Link]("The length of the string is: " + len);
}
}
Output: The length of the string is: 12

Example 1:
public class LengthDemo1 {
public static void main(String[] args) {
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
[Link]([Link]());
}
}
Output: 3

3.4 Character Extraction


• The String class provides a number of ways in which characters can be extracted
from a String object.
a) charAt() : To extract a single character from a String, you can refer
directly to an individual character via the charAt( ) method. It has this
general form:

New Horizon College of Engineering, Bengaluru 5|Page


Object Oriented Programming Using Java 24CSK42

char charAt(int where)


where is the index of the character that you want to obtain. The
value of where must be nonnegative and specify a location within the
string. charAt( ) returns the character at the specified location.

Example :
public class CharAtDemo{
public staic void main(String[] args){
char ch;
ch = "abc".charAt(1); //assigns the value b to ch.
[Link](ch);
}
}

b) getChars( ) : If you need to extract more than one character at a time,


you can use the getChars( ) method. It has this general form:

void getChars(int sourceStart, int sourceEnd, char


target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the
substring, and sourceEnd specifies an index that is one past the end of
the desired substring. The substring contains the characters from
sourceStart through sourceEnd–1. The array that will receive the
characters is specified by target. The index within target at which the
substring will be copied is passed in targetStart.

Example:
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
[Link](start, end, buf, 0);

New Horizon College of Engineering, Bengaluru 6|Page


Object Oriented Programming Using Java 24CSK42

[Link](buf);
}
} //Output: demo

c) getBytes( ) : There is an alternative to getChars( ) that stores the


characters in an array of bytes. This method is called getBytes( ), and it
uses the default character-to-byte conversions provided by the
platform. Here is its simplest form:
byte[ ] getBytes( )

getBytes() converts a String into a byte array. getBytes( ) is most


useful when you are exporting a String value into an environment that does
not support 16-bit Unicode characters. For example, most Internet protocols
and text file formats use 8-bit ASCII for all text interchange.

Example1:
public class GetBytesExample {
public static void main(String[] args) {
String str = "Hello";
byte[] byteArray = [Link]();
for (byte b : byteArray) {
[Link](b+” “);
}
}
} // Output: 72 101 108 108 111

Example2:
import [Link];
public class GetBytesExample2 {
public static void main(String[] args) {
String str = "Hello";
byte[] byteArray = [Link](StandardCharsets.UTF_8);
for (byte b : byteArray) {
[Link](b);

New Horizon College of Engineering, Bengaluru 7|Page


Object Oriented Programming Using Java 24CSK42

}
}
}

d) toCharArray( ): If you want to convert all the characters in a String


object into a character array, the easiest way is to call toCharArray( ). It
returns an array of characters for the entire string. It has this general
form:
char[ ] toCharArray( )

toCharArray() converts a String into char[]. Each character of the


string becomes one element in the array. Commonly used for
character processing and manipulation.

Example :
public class ToCharArrayExample {
public static void main(String[] args) {
String str = "Hello";
char[] charArray = [Link]();
for (char c : charArray) {
[Link](c +” “);
}
} //Output: H e l l o

3.5 String Comparison


• The String class includes a number of methods that compare strings or substrings
within strings.
a) equals( ) and equalsIgnoreCase( ) : To compare two strings for
equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking
String object. It returns true if the strings contain the same characters in
the same order, and false otherwise. The comparison is case-sensitive.

New Horizon College of Engineering, Bengaluru 8|Page


Object Oriented Programming Using Java 24CSK42

• To perform a comparison that ignores case differences, call


equalsIgnoreCase( ). When it compares two strings, it considers A-Z to
be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking
String object. It, too, returns true if the strings contain the same characters
in the same order, and false otherwise.

Example 1:
class EqualsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
[Link](s1 + " equals " + s2 + " -> " + [Link](s2));
[Link](s1 + " equals " + s3 + " -> " + [Link](s3));
[Link](s1 + " equals " + s4 + " -> " + [Link](s4));
[Link](s1 + " equalsIgnoreCase " + s4 + " -> " +
[Link](s4));
}
}
Example 2:
import [Link];
public class RealWorldEqualsExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String storedUsername = "AdminUser";
String storedPassword = "Java123";
[Link]("Enter username: ");
String inputUsername = [Link]();
[Link]("Enter password: ");
String inputPassword = [Link]();

New Horizon College of Engineering, Bengaluru 9|Page


Object Oriented Programming Using Java 24CSK42

// Case-sensitive comparison (equals)


if ([Link](inputUsername) &&
[Link](inputPassword)) {
[Link]("Login Successful!");
} else {
[Link]("Invalid Username or Password.");
}
// Case-insensitive comparison (equalsIgnoreCase)
[Link]("Enter your role (admin/user): ");
String role = [Link]();
if ([Link]("admin")) {
[Link]("Welcome, Administrator!");
} else {
[Link]("Welcome, User!");
}
[Link]();
}
}
Output:
Enter username: AdminUser
Enter password: Java123
Login Successful!
Enter your role (admin/user): ADMIN
Welcome, Administrator!

b) regionMatches( ) : The regionMatches( ) method compares a specific


region inside a string with another specific region in another string.
There is an overloaded form that allows you to ignore case in such
comparisons. Here are the general forms for these two methods:
i) boolean regionMatches(int startIndex, String str2, int
str2StartIndex, int numChars)
ii) boolean regionMatches(boolean ignoreCase, int startIndex,
String str2, int str2StartIndex, int numChars)

New Horizon College of Engineering, Bengaluru 10 | P a g e


Object Oriented Programming Using Java 24CSK42

c) startsWith( ) and endsWith( ) : The startsWith( ) method determines


whether a given String begins with a specified string. Conversely,
endsWith( ) determines whether the String in question ends with a
specified string. They have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the string matches, true
is returned. Otherwise, false is returned.

Example1:
"Foobar".endsWith("bar") //true
"Foobar".startsWith("Foo") //true

A second form of startsWith( ), shown here, lets you specify a starting


point:
boolean startsWith(String str, int startIndex)
Here, startIndex specifies the index into the invoking string at which
point the search will begin.

Example2:
"Foobar".startsWith("bar", 3) //true

Example3:
public class StartsEndsExample {
public static void main(String[] args) {
String str = "[Link]";
// Using startsWith()
[Link]("Starts with 'Hello': " +
[Link]("Hello"));
// Using endsWith()
[Link]("Ends with '.java': " + [Link](".java"));
}
}

New Horizon College of Engineering, Bengaluru 11 | P a g e


Object Oriented Programming Using Java 24CSK42

Output:
Starts with 'Hello': true
Ends with '.java': true

d) equals( ) Versus == : The equals( ) method and the == operator


perform two different operations. The equals( ) method compares
the characters inside a String object. The == operator compares two
object references to see whether they refer to the same instance.
Example1:
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
[Link](s1 + " equals " + s2 + " -> " +
[Link](s2)); [Link](s1 + " == " + s2 + " -> " +
(s1 == s2));
}
}
Output:
Hello equals Hello -> true
Hello == Hello -> false

Example 2:
import [Link];
public class CredentialVerification {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Predefined credentials
String correctUsername = "admin";
String correctPassword = "java123";
// User input
[Link]("Enter username: ");
String username = [Link]();

New Horizon College of Engineering, Bengaluru 12 | P a g e


Object Oriented Programming Using Java 24CSK42

[Link]("Enter password: ");


String password = [Link]();
// Verification using equals()
if ([Link](correctUsername) &&
[Link](correctPassword)) {
[Link]("Login successful!");
} else {
[Link]("Invalid username or
password.");
}
[Link]();
}
}
Output:
Enter username: admin
Enter password: java123
Login successful!

e) compareTo( ) : The compareTo() method is used to compare two


strings lexicographically (dictionary order). It is specified by the
Comparable interface, which String implements. It has this general
form:
int compareTo(String str)

• Returns 0 → if both strings are equal


• Returns negative number → if first string is smaller
• Returns positive number → if first string is greater
• Comparison is based on Unicode (ASCII) values
• It is case-sensitive

Example:
class SortString {
static String arr[] = {

New Horizon College of Engineering, Bengaluru 13 | P a g e


Object Oriented Programming Using Java 24CSK42

"Now", "is", "the", "time", "for", "all", "good", "men",


"to", "come", "to", "the", "aid", "of", "their",
"country"
};
public static void main(String args[]) {
for(int j = 0; j < [Link]; j++) {
for(int i = j + 1; i < [Link]; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
[Link](arr[j]);
}
}
}
If you want to ignore case differences when comparing two strings, use
compareToIgnoreCase( ), as shown here:
int compareToIgnoreCase(String str)
This method returns the same results as compareTo( ), except that case
differences are ignored. You might want to try substituting it into the
previous program.

3.6 Searching Strings


a) indexOf( ) and lastIndexOf( )
The String class provides two methods that allow you to search a string for
a specified character or substring:
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.
These two methods are overloaded in several different ways. In all cases,
the methods return the index at which the character or substring was found, or –
1 on failure.

New Horizon College of Engineering, Bengaluru 14 | P a g e


Object Oriented Programming Using Java 24CSK42

i) To search for the first occurrence of a character, use


int indexOf(int ch) // ch is the character being sought

ii) To search for the last occurrence of a character, use


int lastIndexOf(int ch) // ch is the character being sought

iii) To search for the first or last occurrence of a substring, use


int indexOf(String str)
int lastIndexOf(String str) // str specifies the substring

iv) You can specify a starting point for the search using these forms
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

Example:
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
[Link](s);
[Link]("indexOf(t) = " + [Link]('t'));
[Link]("lastIndexOf(t) = " + [Link]('t'));
[Link]("indexOf(the) = " + [Link]("the"));
[Link]("lastIndexOf(the) = " + [Link]("the"));
[Link]("indexOf(t, 10) = " + [Link]('t', 10));
[Link]("lastIndexOf(t, 60) = " + [Link]('t',
60));
[Link]("indexOf(the, 10) = " + [Link]("the", 10));
[Link]("lastIndexOf(the, 60) = " + [Link]("the",
60));
}

New Horizon College of Engineering, Bengaluru 15 | P a g e


Object Oriented Programming Using Java 24CSK42

}
Output:
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

3.7 Modifying a String


String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or StringBuilder, or use a String method that
constructs a new copy of the string.
a) substring( ) : You can extract a substring using substring( ). It has two forms.
The first is
String substring(int startIndex)
startIndex specifies the index at which the substring will begin. This
form returns a copy of the substring that begins at startIndex and runs to
the end of the invoking string.

The second form of substring( ) allows you to specify both the beginning and
ending index of the substring:
String substring(int startIndex, int endIndex)
startIndex specifies the beginning index, and endIndex specifies the
stopping point. The string returned contains all the characters from the
beginning index, up to, but not including, the ending index.

Example:
class StringReplace {
public static void main(String args[]) {

New Horizon College of Engineering, Bengaluru 16 | P a g e


Object Oriented Programming Using Java 24CSK42

String org = "This is a test. This is, too."; S


tring search = "is";
String sub = "was";
String result = "";
int i;
do {
// replace all matching substrings
[Link](org);
i = [Link](search);
if(i != -1) {
result = [Link](0, i);
result = result + sub;
result = result + [Link](i + [Link]()); org = result;
}
} while(i != -1);
}
}
Output:
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

b) concat( ) : You can concatenate two strings using concat( ), shown here: String
concat(String str) This method creates a new object that contains the invoking
string with the contents of str appended to the end. concat( ) performs the same
function as +.
Example:
public class ConcatDemo{
public static void main(String[] args){
String s1 = "one";
String s2 = [Link]("two");

New Horizon College of Engineering, Bengaluru 17 | P a g e


Object Oriented Programming Using Java 24CSK42

[Link](s2) // onetwo
String s1 = "one";
String s2 = s1 + "two";
[Link](s2) // onetwo
}
}

c) replace( ) : The replace( ) method has two forms. The first replaces all
occurrences of one character in the invoking string with another character. It has
the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character
specified by replacement.

Example:
public class ReplaceExample {
public static void main(String[] args) {
String str = "I like Python";
// Replace "Python" with "Java"
String newStr = [Link]("Python", "Java");
[Link]("Original String: " + str);
[Link]("Modified String: " + newStr);
String s = "Hello".replace('l', 'w');
[Link](s); //puts the string "Hewwo" into s.
}
}
The second form of replace( ) replaces one character sequence with
another. It has this general form:
String replace(CharSequence original, CharSequence
replacement)

d) trim( ) : The trim( ) method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed. It has this general form:
String trim( )

New Horizon College of Engineering, Bengaluru 18 | P a g e


Object Oriented Programming Using Java 24CSK42

Example1:
String s = " Hello World ".trim(); // " Hello World
Example2:
import [Link].*;
class UseTrim {
public static void main(String args[]) throws IOException {
// create a BufferedReader using [Link]
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
String str;
[Link]("Enter 'stop' to quit.");
[Link]("Enter State: ");
do {
str = [Link]();
str = [Link](); // remove whitespace
if([Link]("Illinois"))
[Link]("Capital is Springfield.");
else if([Link]("Missouri"))
[Link]("Capital is Jefferson City.");
else if([Link]("California"))
[Link]("Capital is Sacramento.");
else if([Link]("Washington"))
[Link]("Capital is Olympia.");
} while(![Link]("stop"));
}
}

Output:
Enter 'stop' to quit.

Enter State:
Missouri
Capital is Jefferson City.

New Horizon College of Engineering, Bengaluru 19 | P a g e


Object Oriented Programming Using Java 24CSK42

3.8 StringBuffer
• StringBuffer supports a modifiable string. As you know, String represents
fixed-length, immutable character sequences. In contrast, StringBuffer
represents growable and writable character sequences.
• StringBuffer may have characters and substrings inserted in the middle or
appended to the end.
• StringBuffer will automatically grow to make room for such additions and often
has more characters preallocated than are actually needed, to allow room for
growth.

StringBuffer Constructors
• StringBuffer defines these four constructors:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)

⚫ The default constructor (the one with no parameters) reserves room for 16 characters
without reallocation.

⚫ The second version accepts an integer argument that explicitly sets the size of the
buffer.

⚫ The third version accepts a String argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer allocates room for 16 additional characters when no specific buffer
length is requested, because reallocation is a costly process in terms of time. Also,
frequent reallocations can fragment memory. By allocating room for a few extra
characters, StringBuffer reduces the number of reallocations that take place.

⚫ The fourth constructor creates an object that contains the character sequence
contained in chars and reserves room for 16 more characters.

Example:

public class StringBufferConstructorsDemo {


public static void main(String[] args) {

New Horizon College of Engineering, Bengaluru 20 | P a g e


Object Oriented Programming Using Java 24CSK42

// 1. StringBuffer()
StringBuffer sb1 = new StringBuffer();
[Link]("Default Constructor");
[Link]("sb1: " + sb1);

// 2. StringBuffer(int size)
StringBuffer sb2 = new StringBuffer(30);
[Link]("Capacity Constructor");
[Link]("sb2: " + sb2);
[Link]("sb2 capacity: " + [Link]());

// 3. StringBuffer(String str)
StringBuffer sb3 = new StringBuffer("Hello Java");
[Link]("sb3: " + sb3);

// 4. StringBuffer(CharSequence chars)
CharSequence cs = "Learning StringBuffer";
StringBuffer sb4 = new StringBuffer(cs);
[Link]("sb4: " + sb4);
}
}
Output:
sb1: Default Constructor
sb2: Capacity Constructor
sb2 capacity: 30
sb3: Hello Java
sb4: Learning StringBuffer

a) length( ) and capacity( ): The current length of a StringBuffer can be found via
the length( ) method, while the total allocated capacity can be found through the
capacity( ) method. They have the following general forms:
int length( )

New Horizon College of Engineering, Bengaluru 21 | P a g e


Object Oriented Programming Using Java 24CSK42

int capacity( )
Here is an example:
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " + [Link]());

}
}
Output:
buffer = Hello
length = 5
capacity = 21

b) ensureCapacity( ) : If you want to preallocate room for a certain number of


characters after a StringBuffer has been constructed, you can use
ensureCapacity( ) to set the size of the buffer. This is useful if you know in
advance that you will be appending a large number of small strings to a
StringBuffer. ensureCapacity( ) has this general form:
void ensureCapacity(int minCapacity)
Here, minCapacity specifies the minimum size of the buffer.

c) setLength( ): To set the length of the string within a StringBuffer object, use
setLength( ). Its general form is shown here:
void setLength(int len)
Here, len specifies the length of the string. This value must be
nonnegative.
Example:
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());

New Horizon College of Engineering, Bengaluru 22 | P a g e


Object Oriented Programming Using Java 24CSK42

[Link]("capacity = " + [Link]());


Since sb is initialized with the string "Hello" when it is created, its length is
5. Its capacity is 21 because room for 16 additional characters is
automatically added.

d) charAt( ) and setCharAt( ) : The value of a single character can be obtained


from a StringBuffer via the charAt( ) method. You can set the value of a character
within a StringBuffer using setCharAt( ). Their general forms are shown here:

char charAt(int where)


void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the character being obtained. For
setCharAt( ), where specifies the index of the character being set, and ch
specifies the new value of that character. For both methods, where must be
nonnegative and must not specify a location beyond the end of the string.

Example:
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer before = " + sb);
[Link]("charAt(1) before = " + [Link](1));
[Link](1, 'i');
[Link](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
}
}
Output:
buffer before = Hello charAt(1)
before = e
buffer after = Hi
charAt(1) after = i

New Horizon College of Engineering, Bengaluru 23 | P a g e


Object Oriented Programming Using Java 24CSK42

e) getChars( ) : To copy a substring of a StringBuffer into an array, use the


getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
sourceStart specifies the index of the beginning of the substring, and
sourceEnd specifies an index that is one past the end of the desired substring.
This means that the substring contains the characters from sourceStart through
sourceEnd–1. The array that will receive the characters is specified by target.
The index within target at which the substring will be copied is passed in
targetStart. Care must be taken to assure that the target array is large enough to
hold the number of characters in the specified substring.

f) append( ) : The append( ) method concatenates the string representation of any


other type of data to the end of the invoking StringBuffer object. It has several
overloaded versions. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

The string representation of each parameter is obtained, often by calling


[Link]( ). The result is appended to the current StringBuffer object. The
buffer itself is returned by each version of append( ).
Example:
class appendDemo {
public static void main(String args[]) {
String s; int a = 42;
StringBuffer sb = new StringBuffer(40);
s = [Link]("a = ").append(a).append("!").toString();
[Link](s);
}
}
Output : a = 42!

New Horizon College of Engineering, Bengaluru 24 | P a g e


Object Oriented Programming Using Java 24CSK42

g) insert( ) : The insert( ) method inserts one string into another. It is overloaded
to accept values of all the primitive types, plus Strings, Objects, and
CharSequences. Like append( ), it obtains the string representation of the value
it is called with. This string is then inserted into the invoking StringBuffer object.
These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

Here, index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.
Example:
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
[Link](2, "like ");
[Link](sb);
}
}
Output: I like Java!

h) reverse( ) : You can reverse the characters within a StringBuffer object using
reverse( ), shown here:
StringBuffer reverse( )

This method returns the reverse of the object on which it was called.
Example:
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
[Link](s);
[Link]();
[Link](“ “ +s);
}

New Horizon College of Engineering, Bengaluru 25 | P a g e


Object Oriented Programming Using Java 24CSK42

} //output : abcdef fedcba

i) delete( ) and deleteCharAt( ): You can delete characters within a StringBuffer


by using the methods delete( ) and deleteCharAt( ). These methods are shown
here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
• The delete( ) method deletes a sequence of characters from the
invoking object. Here, startIndex specifies the index of the first
character to remove, and endIndex specifies an index one past the
last character to remove. Thus, the substring deleted runs from
startIndex to endIndex–1. The resulting StringBuffer object is
returned.
• The deleteCharAt( ) method deletes the character at the index
specified by loc. It returns the resulting StringBuffer object.

Example:
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](4, 7);
[Link]("After delete: " + sb);
[Link](0);
[Link]("After deleteCharAt: " + sb);
}
}
Output:
After delete: This a test.
After deleteCharAt: his a test.

j) replace( ): You can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). Its signature is shown here:

StringBuffer replace(int startIndex, int endIndex, String str)

New Horizon College of Engineering, Bengaluru 26 | P a g e


Object Oriented Programming Using Java 24CSK42

The substring being replaced is specified by the indexes startIndex and


endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The
replacement string is passed in str. The resulting StringBuffer object is returned.
Example:
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](5, 7, "was");
[Link]("After replace: " + sb);
}
}
Output:
After replace: This was a test.
k) substring( ): You can obtain a portion of a StringBuffer by calling substring( ).
It has the following two forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)

The first form returns the substring that starts at startIndex and runs to the
end of the invoking StringBuffer object. The second form returns the substring
that starts at startIndex and runs through endIndex–1.
Example:
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
// From index 6 to end
String part1 = [Link](6);
[Link](part1); // Output: World
// From index 0 to 5 (exclusive)
String part2 = [Link](0, 5);
[Link](part2); // Output: Hello
}
}

New Horizon College of Engineering, Bengaluru 27 | P a g e


Object Oriented Programming Using Java 24CSK42

3.9 StringBuilder
• StringBuilder is similar to StringBuffer except for one important difference: it is
not synchronized, which means that it is not thread-safe.
• The advantage of StringBuilder is faster performance. However, in cases in which
a mutable string will be accessed by multiple threads, and no external
synchronization is employed, you must use StringBuffer rather than StringBuilder.

Example Program:
public class StringBuilderExample {
public static void main(String[] args) {
// Create a StringBuilder object
StringBuilder sb = new StringBuilder("Hello");

// Append text
[Link](" World");
// Insert text
[Link](5, ",");
// Display result
[Link]("Final String: " + sb);
}
}
Output:
Final String: Hello, World

Difference between String, StringBuffer and StringBuilder

String StringBuffer StringBuilder


1. String 1. StringBuffer 1. StringBuilder
introduced from introduced from JDK introduced from JDK
JDK 1.0 1.0 1.5

New Horizon College of Engineering, Bengaluru 28 | P a g e


Object Oriented Programming Using Java 24CSK42

2. Strings are 2. StringBuffer are 3. StringBuilder are


immutable in mutable in nature mutable in nature
nature
3. Strings are [Link] are [Link] are
Thread safe Thread safe not Thread safe
4. String class has 4. StringBuffer class 4. StringBuilder class
overridden 3 has overridden 1 has overridden 1
methods from method from object method from object
object class. class. [Link]() class. [Link]()
[Link](),
[Link](),
[Link]()
5. String objects 5. StringBuffer objects 5. StringBuilder
can be created can be created only objects can be created
with or without using new keyword only using new
new keyword keyword
6. + operator can 6. + operator cannot be 6. + operator cannot be
be used for used for concatenation used for concatenation
concatenation in in StringBuffer class. in StringBuilder class.
String class
7. Memory efficient 7. Memory efficient is 7. Memory efficient is
is High Less Efficient Efficient

3.10 Basic file I/O

• File I/O in Java means File Input and Output the process of reading data from
files and writing data to files on a storage device (like a hard drive). Java provides
several classes in the [Link] and [Link] packages to handle file operations.

New Horizon College of Engineering, Bengaluru 29 | P a g e


Object Oriented Programming Using Java 24CSK42

• Here Input means Reading data from a file into a program and Output means
writing data from a program into a file.
• Files can contain Text data (e.g., .txt), Binary data (e.g., images, PDFs).
• Basic File I/O utilizes stream-based I/O for bytes
(FileInputStream/FileOutputStream) and character-based I/O for text
(FileReader/FileWriter). Key operations involve opening streams,
reading/writing data, and closing streams within blocks to ensure proper resource
management and exception handling.

a) Byte Streams(Binary Data) :Used for binary data (images, sounds, raw
bytes).
FileInputStream: Reads from a file one byte at a time.
Example:
FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream: Writes bytes to a file.
Example:
FileOutputStream fos = new FileOutputStream("[Link]");
Key Concept: Read/write operations can throw IOException, requiring try-
catch.

b) Character Streams (FileReader & FileWriter): Used for text data, handling
16-bit Unicode characters.
FileReader: Reads characters from a text file.
Constructor: FileReader fr = new FileReader("[Link]");
Methods: read() returns the next character or -1.
FileWriter: Writes characters to a text file.
Constructor: FileWriter fw = new FileWriter("[Link]", true);
Methods: write(String str)

File Class: Represents a file or directory path.


File file = new File("[Link]");
Example:
import [Link];

New Horizon College of Engineering, Bengaluru 30 | P a g e


Object Oriented Programming Using Java 24CSK42

public class Example {


public static void main(String[] args) {
File file = new File("[Link]");
[Link]([Link]());
}
}

3.10.1 FileInputStream
• FileInputStream is a class in Java used to read data (bytes) from a file.
It is mainly used for reading binary data such as images, audio files, or any file
where data is handled as raw bytes.
• It belongs to the [Link] package.
Creating a FileInputStream object:
FileInputStream fis = new FileInputStream("filename");
Or using a File object:
File file = new File("filename");
FileInputStream fis = new FileInputStream(file);
• Important methods present in FileInputStream are:

Method Description

read() Reads one byte from the file

read(byte[] b) Reads bytes into an array

available() Returns number of bytes available

close() Closes the stream


Example 1:
import [Link];
import [Link];

public class FileInputExample {


public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("[Link]");

New Horizon College of Engineering, Bengaluru 31 | P a g e


Object Oriented Programming Using Java 24CSK42

int i;
while ((i = [Link]()) != -1) {
[Link]((char)i);
}
[Link]();
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
Example 2:
import [Link];
import [Link];
public class FileInputExample2 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("[Link]");
byte[] data = new byte[[Link]()];
[Link](data);
[Link](new String(data));
[Link]();
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}

3.10.2 FileOutputStream
• FileOutputStream is a class in Java used to write data (in the form of bytes) to
a file. It is mainly used for writing binary data such as images, audio files, or any
raw byte data, but it can also be used to write text. It belongs to the
[Link] package.

New Horizon College of Engineering, Bengaluru 32 | P a g e


Object Oriented Programming Using Java 24CSK42

Creating a FileOutputStream object


Writing to a file (overwrites existing content):
FileOutputStream fos = new FileOutputStream("filename");
Writing using a File object:
File file = new File("filename");
FileOutputStream fos = new FileOutputStream(file);
Writing in append mode (adds to existing content):
FileOutputStream fos = new FileOutputStream("filename",
true);
• Important Methods present in FileOutputStream are as follows

Method Description

write(int b) Writes a single byte

write(byte[] b) Writes an array of bytes

write(byte[] b, int off, int len) Writes a portion of an array

flush() Forces data to be written

close() Closes the stream

Example 1: Writing Text to a File


import [Link];
import [Link];
public class FileOutputExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("[Link]");
String text = "Hello, FileOutputStream!";
[Link]([Link]()); //getBytes() converts a string into bytes.
[Link]();
[Link]("Data written successfully.");
} catch (IOException e) {
[Link]("Error: " + [Link]());
}

New Horizon College of Engineering, Bengaluru 33 | P a g e


Object Oriented Programming Using Java 24CSK42

}
}
Example 2: Writing Data Byte by Byte
import [Link];
import [Link];

public class Example2 {


public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("[Link]");
for (int i = 65; i <= 70; i++) {
[Link](i);
}
[Link]();
} catch (IOException e) {
[Link](e);
}
}
}
Example 3: Append Mode
import [Link];
import [Link];
public class AppendExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("[Link]", true);
String data = "\nAppended text.";
[Link]([Link]());
[Link]();
} catch (IOException e) {
[Link](e);
}
}

New Horizon College of Engineering, Bengaluru 34 | P a g e


Object Oriented Programming Using Java 24CSK42

3.10.3 FileReader
• FileReader is a class used to read character data from files. It is part of the [Link]
package and is mainly used for reading text files. FileReader is a character stream
class that reads data as a sequence of characters. It is typically used when:
• The file contains character data (not binary like images or videos)
o You want to read text files (.txt, .csv, etc.)
o The file contains character data (not binary like images or videos)
Constructors of FileReader
i) Using file name (String)
FileReader fr = new FileReader("[Link]");

ii) Using File object


File file = new File("[Link]");
FileReader fr = new FileReader(file);

iii) Using FileDescriptor


FileDescriptor fd = new FileDescriptor();
FileReader fr = new FileReader(fd);
These constructors throw FileNotFoundException, so you must handle it.

• Important methods present in FileReader : Since FileReader extends Reader class


so it inherits methods from Reader class.
i) read() : Reads a single character.
int data = [Link]();
Returns character as ASCII/Unicode integer
Returns -1 when end of file is reached
Example:
public class FileReaderDemo{
public static void main(String[] args){
FileReader fr = new FileReader("[Link]");
int i;

New Horizon College of Engineering, Bengaluru 35 | P a g e


Object Oriented Programming Using Java 24CSK42

while ((i = [Link]()) != -1) {


[Link]((char) i);
}
[Link]();
} }

ii) read(char[] array) : Reads characters into an array.


char[] arr = new char[100];
[Link](arr);
Example:
public class FileReaderDemo{
public static void main(String[] args){
FileReader fr = new FileReader("[Link]");
char[] arr = new char[50];
int charsRead = [Link](arr);
[Link](new String(arr, 0, charsRead));
[Link]();
}
}

iii) close(): Closes the file and releases system resources. It is always good
practice to close the file after reading. Ex: [Link]()

Complete example:
import [Link];
import [Link];
public class FileReaderExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link]((char) i);
}

New Horizon College of Engineering, Bengaluru 36 | P a g e


Object Oriented Programming Using Java 24CSK42

[Link]();
} catch (IOException e) {
[Link]();
}
}
}

3.10.4 FileWriter
• FileWriter is a class in Java used to write character data (text) to files.
It belongs to the [Link] package and is part of Java’s character stream classes.
• FileWriter is used to write text data to a file character by character. It is mainly
used for:
• Writing .txt, .csv, .log files
• Saving text output
• Creating and updating text files
• FileWriter extends OutputStreamWriter, which converts characters into bytes
using a character encoding.
• Constructors of FileWriter :
i) Write using filename (overwrite mode)
FileWriter fw = new FileWriter("[Link]");
Creates file if not exists and Overwrites file if already exists

ii) Append mode


FileWriter fw = new FileWriter("[Link]", true);
true = append mode and false (default) = overwrite
iii) Using File object
File file = new File("[Link]");
FileWriter fw = new FileWriter(file);
Constructors throw IOException, so must handle or declare it.

• Important methods of FileWriter class are


i) write(int c) : Writes a single character.
[Link]('A');

New Horizon College of Engineering, Bengaluru 37 | P a g e


Object Oriented Programming Using Java 24CSK42

ii) write(char[] c) : Writes an array of characters.


char[] arr = {'H','e','l','l','o'};
[Link](arr);
iii) write(String str) : Writes a string.
[Link]("Hello World");
iv) write(String str, int off, int len) : Writes part of a string.
[Link]("Hello World", 0, 5); // writes Hello

v) flush() : Forces buffered data to be written immediately.

Example:
import [Link];
import [Link];
public class FileWriterExample {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java\n");
[Link]("FileWriter Example");
[Link]();
[Link]("File written successfully");
} catch (IOException e) {
[Link]();
}
}
}
Questions:
1. Define a String constructor in Java.
2. List different ways to create a String object.
3. Identify the method used to find the length of a String.
4. Name two methods used for character extraction from a String.
5. Recall the classes used for basic file I/O in Java for reading and writing text files.
6. Explain how the length() method works in Java Strings.
7. Describe the difference between StringBuffer and StringBuilder.

New Horizon College of Engineering, Bengaluru 38 | P a g e


Object Oriented Programming Using Java 24CSK42

8. Summarize how character extraction methods such as charAt() and getChars()


operate.
9. Differentiate between FileInputStream and FileReader.
10. Explain the purpose of comparison methods like equals() and compareTo() in
Strings.
11. Use a String constructor to create a String from a character array.
12. Demonstrate how to extract a substring from a given String.
13. Implement a Java program that compares two Strings using equalsIgnoreCase().
14. Show how to search for a word in a sentence using indexOf().
15. Apply FileWriter to write text data into a file.
16. Compare the performance characteristics of String, StringBuffer, and
StringBuilder.
17. Distinguish between mutable and immutable string classes in Java.
18. Examine how the replace() and replaceAll() methods differ in String modification.
19. Analyze the steps involved in reading binary data using FileInputStream.
20. Investigate what happens internally when multiple modifications are performed
on a String object.
21. Assess when it is more appropriate to use StringBuilder instead of StringBuffer.
22. Justify the use of Buffered streams along with file streams in file I/O operations.
23. Critique the efficiency of using String concatenation inside loops.
24. Evaluate the advantages and limitations of character streams (FileReader,
FileWriter) versus byte streams (FileInputStream, FileOutputStream).
25. Recommend the best approach for comparing large numbers of Strings in a
performance-critical application.
26. Design a Java program that reads a text file and counts the number of characters,
words, and lines.
27. Construct a method that reverses a String using StringBuilder.
28. Develop a program that searches for a substring in a file and replaces it with
another word.
29. Formulate a class that demonstrates all major String comparison methods with
examples.
30. Create a Java application that copies the contents of one file to another using file
streams.

New Horizon College of Engineering, Bengaluru 39 | P a g e


Object Oriented Programming using Java 24CSK42

MODULE 4
Exception Handling and Multi-Threading
Exception handling: Fundamentals, Types, Using try,
catch, throw,throws, finally, multiple catch, User
Defined Exceptions, Thread Concept, Java Thread
Model, The main method, Creating Threads, Daemon
Threads, Thread Pool, Thread Priorities,
Synchronization, join.

4.1. Exception Handling: Fundamentals


The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.

In this section, we will learn about Java exceptions, its type and the difference between checked and
unchecked exceptions.

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition. In Java, an exception is an event that


disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception handling.

Hierarchy of Java Exception classes

The [Link] class is the root class of Java Exception hierarchy which is inherited
by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Object Oriented Programming using Java 24CSK42

Fig. 4.1. Hierarchy of Java Exception Classes

4.2. Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error
Object Oriented Programming using Java 24CSK42

Fig. 4.2. Exception Types


Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit 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 which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

4.3 Java Exception Handling Keywords


There are 5 keywords which are used in handling exceptions in Java.

Keyword Description
Object Oriented Programming using Java 24CSK42
try The trykeyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we
can't use try block alone.
catch The catch block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The finallyblock is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The throwkeyword is used to throw an exception.

throws The throwskeyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e){
[Link](e);
}
//rest code of the program
[Link]("rest of the code...");}
}
Output:
Exception in thread main [Link]:/ by zero
rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-


catch block.

4.3.1. Java try-catch 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.
Object Oriented Programming using Java 24CSK42
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}

Syntax of try-finally block

try{
//code that may throw an exception
}
finally{
// code that is always executed irrespective of exception
}

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block with a single
try block.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1
public class TryCatchExample1 {
public static void main(String[] args){
int data=50/0; //may throw exception
[Link]("rest of the code");
}
}

Output:
Object Oriented Programming using Java 24CSK42
Exception in thread "main" [Link]: / by zero

As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed). There can be 100 lines of code after exception. So all the code after
exception will not be executed.

Solution by exception handling

Let's see the solution of the above problem by a java try-catch block.

Example 2
public class TryCatchExample2 {
public static void main(String[] args){
try{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e){
[Link](e);
}
[Link]("rest of the code");
}
}

Output:
[Link]: / by zero
rest of the code

Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
Syntax:

...
try{
statement 1;
statement 2;
try{
statement 1;
statement 2;
}
catch(Exception e){
Object Oriented Programming using Java 24CSK42
}
}
catch(Exception e)
{
}
...

Java nested try example


class Excep6{
public static void main(String args[]){
try {
try {
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){
[Link](e);}
[Link]("other statement);
}
catch(Exception e){[Link]("handeled");}
[Link]("normal flow..”);
}
}

4.3.2. Java 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.

Points to remember

• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
• ArithmeticExceptionmust come before catch for Exception.

Example 1

Let's see a simple example of java multi-catch block.


public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
Object Oriented Programming using Java 24CSK42
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBounds Exception
occurs”);
}
catch(Exception e){
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code

4.3.3. Java 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.

Fig 4.3. Finally block use


Object Oriented Programming using Java 24CSK42

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).

Why use java finally

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

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;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");}
}

Output:
5
finally block is always executed
rest of the code...

4.3.4. Java throw keyword

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

We can throw either checked or unchecked exception in java by throw keyword. The throw keyword
is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

The following statement throws an IOException.

throw new IOException("sorry device error);

In this example, we have created the validate method that takes integer value as a parameter. If the age
is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
Object Oriented Programming using Java 24CSK42
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}

Output:

Exception in thread main [Link]:not valid

4.3.5. Java throws keyword

The Java throws keyword is used to declare that a method throws an exception. It gives an
information to the programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up
before the code being used.

Syntax of java throws


return_type method_name() throws ExceptionClassName{
//method code
}

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack). It provides information to the
caller of the method about the exception.

Java throws example


import [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){
Object Oriented Programming using Java 24CSK42
[Link]("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}

Output:
exception handled
normal flow...

4.4. User Defined Exceptions


We have seen predefined exceptions provided by the Java platform. These predefined exceptions are
used to handle errors occurring in the program.
But sometimes the programmer wants to create his own customized exception as per requirements of
the application which is called user-defined exception or custom exception.

Custom exceptions in Java are those exceptions which are created by a programmer to meet their
specific requirements of the application.
For example: 1. A banking application, a customer whose age is lower than 18 years, the program
throws a custom exception indicating “needs to open joint account”. 2. Voting age in India: If a
person’s age entered is less than 18 years, the program throws “invalid age” as a custom exception.
How to create your own User-defined Exception in Java?
There are following steps that are followed in creating user-defined exception or custom exception in
Java. They are as follows:
Step 1: User-defined exceptions can be created simply by extending Exception class. This is done as:
class OwnException extends Exception
Step 2: If you do not want to store any exception details, define a default constructor in your own
exception class. This can be done as follows:
OwnException()
{
}
Step 3: If you want to store exception details, define a parameterized constructor with string as a
parameter, call super class (Exception) constructor from this, and store variable “str”. This can be done
as follows:
OwnException(String str)
{
Object Oriented Programming using Java 24CSK42
super(str); // Call super class exception constructor and store
variable "str" in it.
}
Step 4: In the last step, we need to create an object of user-defined exception class and throw it using
throw clause.
OwnException obj = new OwnException("Exception details");
throw obj;
or,
throw new OwnException("Exception details");

Example :
package customExceptionProgram;
public class OwnException extends Exception
{
// Declare default constructor.

OwnException()
{ }
}
public class MyClass {
public static void main(String[] args)
{
try
{
// Create an object of user defined exception and throw it using
throw clause.
OwnException obj = new OwnException();
throw obj;
}
catch (OwnException ex)
{
System. [Link]("Caught a user defined exception");
}
}

}
Example Programs:
File Handling with FileNotFoundException:
Object Oriented Programming using Java 24CSK42
import [Link].*;

public class CheckedExample1 {

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


FileReader fr = new FileReader("[Link]");

} catch (FileNotFoundException e) { [Link]("File not


found: " + e);
}

}
Thread sleep with InterruptedException:
public class CheckedExample2 {

public static void main(String[] args) {

try {
[Link]("Sleeping...");
[Link](2000);
} catch (InterruptedException e)
{ [Link]("Sleep interrupted: " + e);
}
}

Using throws with File I/O:


import [Link].*;

public class CheckedExample3 {

public static void readFile() throws IOException {

BufferedReader reader = new BufferedReader(new


FileReader("[Link]"));
[Link]([Link]());
}
public static void main(String[] args) {
try {
readFile();

} catch (IOException e) {
Object Oriented Programming using Java 24CSK42
[Link]("I/O Exception: " + e);
}

Unchecked Exception Example: String Index Out of Bounds

public class UncheckedExample5 {

public static void main(String[] args) {

try {
String name = "Java";

char ch = [Link](10); // invalid index [Link](ch);


} catch (StringIndexOutOfBoundsException e) {
[Link]("String index error: " +
[Link]());

• StringIndexOutOfBoundsExceptionis an unchecked exception.

• It occurs at runtime when accessing an invalid character index in a string.

• These types of exceptions are not checked at compile time.

• Handling them ensures the program doesn’t crash unexpectedly due to logic errors.

Null Pointer Exception:

public class UncheckedExample3 {

public static void main(String[] args) {

try {
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Null reference: " + e);
Object Oriented Programming using Java 24CSK42
}

Number Format Exception:

public class UncheckedExample4 {

public static void main(String[] args) {

try {
int num = [Link]("abc");

} catch (NumberFormatException e) {

[Link]("Invalid number format: " + e);


}

}
User Defined Exceptions:

class MyException extends Exception {

public MyException(String message) {

super(message);
}

}
public class UserDefined1 {

public static void main(String[] args) {

try {
throw new MyException("This is a custom exception");
} catch (MyException e) {
[Link]("Caught: " + e);
}

Difference between throw and throws in Java


Object Oriented Programming using Java 24CSK42
A list of differences between throw and throws are given below:

throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare that
throw an exception. a method throws an exception.

Checked exception cannot be propagated using Checked exception can be propagated with
throw only. throws.

Throw is followed by an instance. throws is followed by class.

You cannot throw multiple exceptions. You can declare a method to throw multiple
exceptions e.g.
public void method() throws IOException,
SQLException.

Difference between final, finally and finalize


A list of differences between final, finally and finalize are given below:

final finally finalize


finalis used to apply restrictions finallyis used to finalizeis used
on class, method and variable. place important code, to perform clean up
Final class can't be inherited, final that needs to be executed processing just
method can't be overridden and whether exception is before object is
final variable value can't be handled or not. garbage collected
changed.
final is a keyword used to qualify variable, finally is used to define a finalize is a method
method or class block of code

Java final example


class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error}
}

Java finally example


class FinallyExample{
public static void main(String[] args){
try{
int x=300;
Object Oriented Programming using Java 24CSK42
}
catch(Exception e){[Link](e);}
finally{[Link]("finally block is executed");}
}
}

Java finalize example


class FinalizeExample{
public void finalize(){
[Link]("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
[Link]();
}
}

Sample program File reading - try-catch -finally

public class FileProcessor {

public void processFile(String filePath) { FileReader reader = null;


try {

reader = new FileReader(filePath); BufferedReader bufferedReader =


new BufferedReader(reader);

String line;

while ((line = [Link]()) != null) {


[Link](line);
}

} catch (FileNotFoundException e) {

[Link]("File not found: " + [Link]());


} catch (IOException e) { [Link]("Error reading file: "
+
Object Oriented Programming using Java 24CSK42
[Link]());

} finally {

if (reader != null) { try {


[Link]();

} catch (IOException e) { [Link]("Error closing reader:


" +
[Link]());

} } } } }

Java finally example

class FinallyExample{

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


int x=300;

}catch(Exception e){[Link](e);}

finally {

[Link]("finally block is executed");}


}

}
public class FinallyDemo1 {

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


int a = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Caught: " + e);


} finally {

[Link]("Finally block always executes");

} } }
public class FinallyDemo2 {

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


int a = 20 / 2; [Link]("Result: " + a);
} catch (Exception e) { [Link]("Exception caught");
} finally {
Object Oriented Programming using Java 24CSK42
[Link]("Always runs: finally block");

} } }
public class FinallyDemo3 {

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


[Link](0);

} finally {

[Link]("This won't be printed");

Java finalize example

class FinalizeExample{

public void finalize(){[Link]("finalize called");

public static void main(String[] args)

{ FinalizeExample f1=new FinalizeExample();

FinalizeExample f2=new FinalizeExample();

f1=null;
f2=null;

[Link]();

}}

public class FinalizeDemo1 { public void finalize() {


[Link]("Finalize method called");

}
public static void main(String[] args) {
FinalizeDemo1 obj = new FinalizeDemo1();
obj = null;
[Link]();

}
Object Oriented Programming using Java 24CSK42
}

Multiple Objects:

public class FinalizeDemo2 {


public void finalize() {
[Link]("Object finalized");

}
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
FinalizeDemo2 obj = new FinalizeDemo2();
obj = null;
}
[Link]();
}
}
Finalize in Inheritance:

class A {
public void finalize() { [Link]("Finalize of class A");
}
}

public class FinalizeDemo3 extends A { public void finalize() {


[Link]("Finalize of class B");
}
public static void main(String[] args) { FinalizeDemo3 obj = new
FinalizeDemo3();

obj = null;
[Link]();
}
}

Nested Try-Catch-Finally

public class NestedTry {

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


try {
Object Oriented Programming using Java 24CSK42
int a = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Inner catch: " + e);

} finally {

[Link]("Inner finally block");

} catch (Exception e) { [Link]("Outer catch");


} } }

4.5. Thread Concept

A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread and each thread defines a separate path of execution. Thus, multithreading
is a specialized form of multitasking. There are two distinct types of multitasking: process-based and
thread-based. It is important to understand the difference between the two. For most readers, process-
based multitasking is the more familiar form. A process is, in essence, a program that is executing.
Thus, process-based multitasking is the feature that allows your computer to run two or more programs
concurrently. For example, process-based multitasking enables you to run the Java compiler at the
same time that you are using a text editor. In process-based multitasking, a program is the smallest unit
of code that can be dispatched by the scheduler. In a thread-based multitasking environment, the thread
is the smallest unit of dispatchable code. This means that a single program can perform two or more
tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as
long as these two actions are being performed by two separate threads. Thus, process-based
multitasking deals with the “big picture,” and thread-based multitasking handles the details.
Object Oriented Programming using Java 24CSK42

Fig. 4.4. Process :a program loaded and running in the computer memory
along with resources required for execution
Source: [Link]

A process is a program running in computer system. More precisely, a process is a program loaded
into computer memory along with all the resources it needs for running the program. A process, when
created in the computer memory, will have a process id, status and exclusive memory space, open file
descriptions, open network connection and so on. As there are multiple processes running
simultaneously, operating system will have a mechanism to schedule processes for execution.

A thread is a concurrent sequence of execution inside a process. A process can contain multiple parallel
execution sequences (control) which are called threads. A thread resides inside a process and it is much
light weight compared to process. A thread is the smallest entity that can be scheduled for execution.
Threads uses the process memory and the process memory space is shared between multiple threads.

By default a process will have a single main thread when scheduled for execution. In Java, this thread
start executing the code starting from the main() function sequentially. However, there are
circumstances when an application needs multiple parallel sequences of executions. These parallel
sequences execute in separate threads. Following are the practical scenarios when one will consider
multiple threads in an application.
Object Oriented Programming using Java 24CSK42

Fig. 4.5. Comparison of process with single and Multiple threads

1. Parallel computing to leverage the additional computing resources available in the system and run
the application faster. For example, if the hardware have multiple processors, each thread will run
in a separate processor in parallel.
2. An application might want to execute certain slow operation like logging in a separate background
thread so that the main thread is to blocked due to slow disk and network operation.
Until the program explicitly creates a new thread and schedules it for execution, the entire process
will continue with a single execution thread.

4.6. Java Thread Model

Java Virtual Machine allows an application to have multiple threads of execution concurrently. Every
thread has a priority and a thread can be marked as daemon thread or non-daemon () thread. A daemon
thread is a thread with lowers priority and the JVM does not wait for the execution of daemon thread
to finish before exiting. If all non-daemon threads have finished execution, JVM terminates even if
daemon threads are still running. A daemon thread is used for performing background tasks like
garbage collection.
The Java run-time system depends on threads for many things, and all the class libraries are designed
with multithreading in mind. In fact, Java uses threads to enable the entire environment to be
asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles. As the process
has several states, similarly a thread exists in several states. A thread can be in the following states:
Object Oriented Programming using Java 24CSK42
4.6.1. Life cycle of a Thread (Thread States)
A thread can be in one of the five states. According to Sun Microsystem, there is only 4 states in thread
life cycle in java : new, runnable, non-runnable and terminated. There is no running state.

Fig.4.6. Comparison of process with single and Multiple threads

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

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
Object Oriented Programming using Java 24CSK42
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)

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

5) Terminated

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

When JVM starts, it starts with a single non-daemon thread, which calls the main() method of the
starting class. Multiple new threads can be started from this main thread. By default, each new thread
starting from a current running thread will take the same priority and daemon status as the creating
thread. The JVM keeps running until 1) exit() method of class Runtime has been called or 2) all
non-daemon threads have died either by graceful completion of execution or by an unhandled
Exception or Error.

Java provides a class [Link], which simplifies the process of creating a new thread,
starting the execution of the thread and managing threads like setting thread priorities, interrupting a
thread execution etc.

4.6.2. Thread Priorities


Each thread has its own priority in Java. Thread priority is an absolute integer value. Thread priority
decides only when a thread switches from one running thread to next, called context switching. Priority
does increase the running time of the thread or gives faster execution.

A thread can -voluntarily relinquish control: This is done by explicitly yielding, sleeping, or
blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread
that is ready to run is given the CPU.

A thread can be preempted by a higher-priority thread: In this case, a lower- priority thread that
does not yield the processor is simply preempted—no matter what it is doing—by a higher-priority
thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive
multitasking.
Object Oriented Programming using Java 24CSK42
4.6.3. Synchronization

Java supports an asynchronous multithreading, any number of thread can run simultaneously without
disturbing other to access individual resources at different instant of time or shareable resources. But
some time it may be possible that shareable resources are used by at least two threads or more than
two threads, one has to write at the same time, or one has to write and other thread is in the middle of
reading it. For such type of situations and circumstances Java implements synchronization model called
monitor. The monitor is considered as a box, in which only one thread can reside. As a thread enter in
monitor, all other threads have to wait until that thread exits from the monitor. In such a way, a monitor
protects the shareable resources used by it being manipulated by other waiting threads at the same
instant of time. Java provides a simple methodology to implement synchronization.

4.6.4. Messaging

A program is a collection of more than one thread. Threads can communicate with each other. Java
supports messaging between the threads with lost-cost. It provides methods to all objects for inter-
thread communication. As a thread exits from synchronization state, it notifies all the waiting threads.

4.7. Java main() method


The main() is the starting point for JVM to start execution of a Java program. Without the main()
method, JVM will not execute the program. The syntax of the main() method is:

public: It is an access specifier. We should use a public keyword before the main() method so
that JVM can identify the execution point of the program. If we use private, protected, and default
before the main() method, it will not be visible to JVM.

static:You can make a method static by using the keyword static. We should call the main()
method without creating an object. Static methods are the method which invokes without creating the
objects, so we do not need any object to call the main() method.
Object Oriented Programming using Java 24CSK42

void :In Java, every method has the return type. Void keyword acknowledges the compiler that
main() method does not return any value.

main(): It is a default signature which is predefined in the JVM. It is called by JVM to execute a
program line by line and end the execution after completion of this method. We can also overload the
main() method.

String args[]:The main() method also accepts some data from the user. It accepts a group of
strings, which is called a string array. It is used to hold the command line arguments in the form of
string values.
main( String args[] )
Here, args[] is the array name, and it is of String type. It means that it can store a group of string.
Remember, this array can also store a group of numbers but in the form of string only. Values passed
to the main() method is called arguments. These arguments are stored into args[] array, so the
name args[] is generally used for it.

What happens if the main() method is written without String args[]?

The program will compile, but not run, because JVM will not recognize the main() method.
Remember JVM always looks for the main() method with a string type array as a parameter.

4.8. Creating Threads in Java

How to create thread

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

1. Thread()
2. Thread(String name)
Object Oriented Programming using Java 24CSK42
3. Thread(Runnable r)
4. Thread(Runnable r, String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread. JVM calls the run() method
on the thread.

3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

4. public void join(): waits for a thread to die.


5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.

6. public int getPriority(): returns the priority of the thread.


7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.

10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.

15. public void suspend(): is used to suspend the thread(deprecated).


16. public void resume(): is used to resume the suspended thread(deprecated).
17. public void stop(): is used to stop the thread(deprecated).

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Object Oriented Programming using Java 24CSK42
• A new thread starts (with new call stack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by extending Thread class

public class Counter extends Thread {


private int start = 0;
private int end = Integer.MAX_VALUE;
private String name;
public Counter(String name, int start, int end){
[Link] = name;
[Link] = start;
[Link] = end;}

public void run(){


for( int i =start; i < end; i++) {
[Link](name + “: ” + i );}
}

public static void main(String args[]){


Counter c1 = new Counter(“Positive Counter”, 0, 1000);
Counter c2 = new Counter(“Negative Counter”, -1000, 0);
[Link](“Starting Positive Counter”);
[Link]();
[Link](“Starting Negative Counter”);

[Link]();
[Link](“Continuing tasks in main thread”);
}
}

Java Thread Example by implementing Runnable interface

public class Counter implements Runnable{


private int start = 0;
private int end = Integer.MAX_VALUE;
private String name;
Object Oriented Programming using Java 24CSK42
public Counter(String name, int start, int end){
[Link] = name;
[Link] = start;
[Link] = end;}

public void run(){


for( int i =start; i < end; i++) {
[Link](name + ” ” + i );}}

public static void main(String args[]){


Counter c1 = new Counter(“Positive Counter”, 0, 1000);
Counter c2 = new Counter(“Negative Counter”, -1000, 0);
[Link](“Starting Positive Counter”);
Thread c1Runner = new Thread(c1);
[Link]();
[Link](“Starting Negative Counter”);
Thread c2Runner = new Thread(c2);
[Link]();
[Link](“Continuing tasks in main thread”);}

4.9. Daemon Threads


A daemon thread is a low-priority background thread in Java that supports user threads and does not
prevent the JVM from exiting. It is ideal for background tasks like monitoring, logging, and cleanup.
• Runs in the background to support user (non-daemon) threads.
• JVM exits automatically when all user threads finish.
• Created using the Thread class and marked as daemon with setDaemon(true).
• setDaemon(true) must be called before starting the thread, or it throws
IllegalThreadStateException.
• Common examples: Garbage Collector (GC) and Finalizer Thread.

class MyDaemonThread extends Thread {

public void run() {

[Link](getName() + " is running as a daemon thread.");

public class GFG {


Object Oriented Programming using Java 24CSK42
public static void main(String[] args) throws InterruptedException {

MyDaemonThread t1 = new MyDaemonThread();

[Link](true); // mark as daemon

[Link]("Daemon-1");

[Link]();

[Link](100);

[Link]("Main thread ends.");

}
Output
Daemon-1 is running as a daemon thread.
Main thread ends.

Syntax

Thread t=new Thread;


[Link](true);// Mark thread as daemon
[Link]();

Methods Used

• void setDaemon(boolean on): Marks a thread as daemon or user thread. Must be called
before start().
• boolean isDaemon(): Checks whether a thread is daemon.

Creating a Daemon Thread

public class DaemonExample extends Thread {


public void run() {
if ([Link]().isDaemon()) {
[Link]("Daemon thread running...");
} else {
[Link]("User thread running...");
}
}
Object Oriented Programming using Java 24CSK42

public static void main(String[] args) {


DaemonExample t1 = new DaemonExample();
DaemonExample t2 = new DaemonExample();

[Link](true); // must be set before start()

[Link]();
[Link]();
}
}
Output
Daemon thread running...

User thread running...

Difference Between User Thread and Daemon Thread

Basis User Thread Daemon Thread

Purpose Executes main application tasks Performs background services

Lifecycle Keeps JVM alive until finished Terminates when all user threads finish

Priority Usually higher Usually lower

JVM Exit JVM waits for completion JVM exits even if running

Examples Main thread, worker threads Garbage collector, background monitors

4.10. Thread Pool


A Thread Pool is a collection of pre-created, reusable threads that are kept ready to perform tasks.
Instead of creating a new thread every time you need to run something (which is costly in terms of
memory and CPU), a thread pool maintains a fixed number of threads. When a task is submitted:

• If a thread is free, it immediately picks up the task and runs it.


• If all threads are busy, the task waits in a queue until a thread becomes available.
Object Oriented Programming using Java 24CSK42
• After finishing a task, the thread does not die. It goes back to the pool and waits for the next task.
Benefits of Thread Pool
• Better Performance: Threads are reused instead of being created and destroyed repeatedly.
• Faster Response Time: Tasks don’t need to wait for a new thread to be created.
• Reusability: Threads remain alive after finishing tasks and are reused for future tasks.
• Resource Management: Limits the number of concurrent threads, preventing
OutOfMemoryError or CPU overload.

Thread Pool Initialization

When we initialize a thread pool:

•A fixed number of worker threads are created (e.g., 3).


• These threads are kept idle, waiting for tasks.
•A task queue is set up to hold submitted tasks until a worker is free.
Thread Pool Working
Step 1: Idle State
• Tasks are submitted and placed in the Task Queue.
• Worker threads exist but are idle until work arrives.

Fig. 4.7. Thread Pool Initialization with size = 3 threads. Task Queue = 5

Step 2: Task Assignment

• Each idle thread picks a task from the queue.


• Example: Thread 1 -> Task 1, Thread 2 -> Task 2, Thread 3 -> Task 3
• Remaining tasks (Task 4, Task 5) wait in the queue.
Object Oriented Programming using Java 24CSK42

Fig. 4.8. Thread Pool executing first three tasks

Step 3: Thread Reuse

• Once a thread completes its current task, it becomes idle again.


• It immediately takes the next waiting task from the queue.
• Example: Thread 1 -> Task 4, Thread 2 -> Task 5, Thread 3 -> Idle (no tasks left)

Fig. [Link] Pool executing task 4 and 5

Thread Pool methods


Method Purpose

submit(Runnable task) Adds a task into the queue for execution by worker threads.

shutdown() Gracefully stops the thread pool → no new tasks accepted,


workers stop after finishing current tasks.

shutdownNow() (optional) Immediately interrupts workers and clears pending tasks.

getQueueSize() (optional) Returns how many tasks are waiting in the queue.
Object Oriented Programming using Java 24CSK42
Method Purpose

getActiveCount() (optional) Returns number of threads currently executing tasks.

4.11. Java Thread Priority in Multithreading

In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of
thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can
either be given by JVM while creating the thread or it can be given by programmer explicitly.

Accepted value of priority for a thread is in range of 1 to 10. There are 3 static variables defined in
Thread class for priority.

1. public static int MIN_PRIORITY: This is minimum priority that a thread can have.
Value for this is 1.

2. public static int NORM_PRIORITY: This is default priority of a thread if do not


explicitly define it. Value for this is 5.

3. public static int MAX_PRIORITY: This is maximum priority of a thread. Value for
this is 10.

Get and Set Thread Priority:

1. public final int getPriority(): [Link]()


method returns priority of given thread.

2. public final void setPriority(int newPriority):


[Link]() method changes the priority of thread to the value
newPriority. This method throws IllegalArgumentException if value of parameter
newPriority goes beyond minimum(1) and maximum(10) limit.

Examples of getPriority() and setPriority()

// Java program to demonstrate getPriority() and setPriority()


package labpgms;
class A1 extends Thread{
public void run(){
for(int i=0; i<5; i++)
[Link]("Inside run method in class A");
}
Object Oriented Programming using Java 24CSK42
}

class B1 extends Thread {


public void run(){
for(int i=0; i<5; i++)
[Link]("Inside run method in class B");
}
}

public class ThreadPriority extends Thread {


public void run(){
for(int i=0; i<5; i++)
[Link]("Inside run method ThreadPriority");
}

public static void main(String[] args) {


ThreadPriority t1 = new ThreadPriority();
A1 t2=new A1();
B1 t3=new B1();
[Link]("t1 thread priority : “ + [Link]());
[Link]("t2 thread priority : " + [Link]());
[Link]("t3 thread priority : " + [Link]());
[Link]();
[Link]();
[Link]();
[Link](10);
[Link](5);
[Link](1);

//[Link](21); will throw IllegalArgumentException


[Link]("t1 thread priority : " + [Link]());
[Link]("t2 thread priority : " + [Link]());
[Link]("t3 thread priority : " + [Link]());

// Main thread
[Link]([Link]().getName());
[Link]("Main thread priority : “ +
[Link]().getPriority());

// Main thread priority is set to 10


Object Oriented Programming using Java 24CSK42
[Link]().setPriority(10);
[Link]("Main thread priority : “ +
[Link]().getPriority());

OUTPUT
t1 thread priority : 5 t2 thread priority : 5 t3 thread
priority : 5
Inside run method ThreadPriority
Inside run method ThreadPriority
Inside run method ThreadPriority
Inside run method ThreadPriority
Inside run method ThreadPriority
Inside run method in class A
Inside run method in class A
Inside run method in class A
t1 thread priority : 5 t2 thread priority : 10 t3 thread priority :
5
main
Main thread priority : 5 Main thread priority : 10
Inside run method in class B
Inside run method in class B
Inside run method in class B
Inside run method in class B
Inside run method in class B

Note:

• Thread with highest priority will get execution chance prior to other threads.

Suppose there are 3 threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first
based on maximum priority 6 after that t1 will execute and then t3.

• Default priority for main thread is always 5, it can be changed later. Default priority for all
other threads depends on the priority of parent thread.

Example:
// Java program to demonstrate that a child thread
// gets same priority as parent
import [Link].*;
Object Oriented Programming using Java 24CSK42
class ThreadDemo extends Thread {
public void run(){
[Link]("Inside run method");
}
public static void main(String[]args){
// main thread priority is 6 now
[Link]().setPriority(6);
[Link]("Main thread priority : " +
[Link]().getPriority());

ThreadDemo t1 = new ThreadDemo();


// t1 thread is child of main thread
// so t1 thread will also have priority 6.
[Link]("t1 thread priority : “ + [Link]());}
}

Output:
Main thread priority : 6
t1 thread priority : 6

• If two threads have same priority then we can’t expect which thread will execute first. It depends
on thread scheduler’s algorithm (Round Robin, First Come First Serve, etc.)

• If we are using thread priority for thread scheduling then we should always keep in mind that
underlying platform should provide support for scheduling based on thread priority.

4.12. Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared
resource. Java Synchronization is better option where we want to allow only one thread to access the
shared resource. When multiple threads try to access a common resource such as a shared variable at
the same time, where at least two of them involves a write operation, a race condition can happen and
the resulting resource can take an inconsistent of corrupted value. The following example illustrates
this.
Object Oriented Programming using Java 24CSK42

class Counter {
private int c = 0;

public void increment() {


c++;
}

public void decrement() {


c--;
}

public int value() {


return c;
}
}

Suppose the thread t1 invokes increment() method and another thread t2 invokes
decrement() method on the same object at the same time. An increment/decrement operation like
the above is not an atomic operation. It’s performed in three different atomic operations

1. Retrieve the value of instance variable c

2. Increment/Decrement the retrieved value by 1

3. Store the incremented value back in variable c

It can happen that the above three operations of two threads can interleave each other causing the
following inconsistent result. Suppose the initial value of c is 0

1. Thread t1 retrieves the value of instance variable c

2. Thread t2 retrieves the value of instance variable c

3. Thread t1 increments the retrieved value : result is 1

4. Thread t2 decrements the retrieved value : result is -1

5. Thread t1 stores result in c: c = 1

6. Thread t2 stores result in c: c = -1

Thread t1 result is overwritten by t2 and hence the final value of c is -1 where as it should be 0 ( one
increment and one decrement so the value should not be changed).
Object Oriented Programming using Java 24CSK42
The code block like above where we should allow only one single thread to execute at at time is called
a critical section. Java provides a keyword synchronized which is used to restrict the access to a shared
resource from multiple threads. Java makes sure that only one thread can enter the code defined inside
synchronized section at a time. Java uses lock on intrinsic object to control the access to synchronized
code. Only one thread can hold the lock for an object at a time. Before a thread enters a synchronized
code, it tries to acquire the lock on the specified object. If the thread acquires the lock, it enters the
critical section code and all other thread that needs to enter the critical section will go into a blocking
wait state. Once the thread holding the lock completes the execution of the synchronized section, it
releases the lock so that any other waiting thread can acquire the lock and continue execution.
Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization

2. Thread Synchronization

Here, we will discuss only thread synchronization.


Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. Mutual Exclusive

a) Synchronized method.

b) Synchronized block.

c) Static synchronization.

2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
Object Oriented Programming using Java 24CSK42
done by three ways in java:

1. by synchronized method

2. by synchronized block

3. by static synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every object has an
lock associated with it. By convention, a thread that needs consistent access to an object’s fields has to
acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package [Link] contains several lock
implementations.
Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

class Table {
void printTable(int n){ //method not synchronized
for(int i=1; i <= 5; i++){
[Link](n * i);
try {
[Link](400);
}
catch(Exception e){
[Link](e);}
}
}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}

public void run(){


[Link](5);}
}
Object Oriented Programming using Java 24CSK42
class MyThread2 extends Thread{
Table t;
MyThread2(Table t) {
this.t=t;
}
public void run(){
[Link](100);
}
}

class TestSynchronization1{
public static void main(String args[]) {
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

Output:
5
100
10
200
15
300
20
400
25
500

1. Synchronized statement block


A synchronized statement block is defined by enclosing the code block in inside
synchronized(lockObject) where lockObject is the object on which lock needs to be
acquired by the thread entering the critical section.
Object Oriented Programming using Java 24CSK42
class Counter {
private int c = 0;

public void increment() {


synchronized(this){
c++;
}
}

public void decrement() {


synchronized(this){
c--;
}
}

public int value() {


return c;
}
}

2. Java synchronized method


If you declare any method as synchronized, it is known as synchronized method. Synchronized method
is used to lock an object for any shared resource.

public synchronized void increment() {


c++;
}

If the entire method needs to be synchronized, as in the above case, we can add the keyword
synchronized to the method declaration to declare the method as synchronized. In this case, the entire
method forms the critical section and the lock is acquired on the current object, this. If a static method
is declared as synchronized, lock is obtained on the class object.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

//example of java synchronized method

class Table{
synchronized void printTable(int n){
//synchronized method
for(inti=1; i<=5; i++){
[Link](n * i);
try{
Object Oriented Programming using Java 24CSK42
[Link](400);
}
catch(Exception e){
[Link](e);}
}
}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}
Object Oriented Programming using Java 24CSK42

Output:
5
10
15
20
25
100
200
300
400
500

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds) throws InterruptedException

public static void sleep(long miliseconds, int nanos)throws


InterruptedException

Example of sleep method in java


class TestSleepMethod1 extends Thread {
public void run() {
for(inti=1;i<5;i++) {
try {
[Link](500);}
catch(InterruptedException e) {
[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1 = new TestSleepMethod1();
Object Oriented Programming using Java 24CSK42
TestSleepMethod1 t2 = new TestSleepMethod1();

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

Output:
1

4.13. The join() method

[Link] class provides the join() method which allows one thread to wait until another thread
completes its execution. If t is a Thread object whose thread is currently executing, then [Link]() will
make sure that t is terminated before the next instruction is executed by the program.

If there are multiple threads calling the join() methods that means overloading on join allows the
programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for
timing, so you should not assume that join will wait exactly as long as you specify.

Syntax:

public void join() throws InterruptedException

public void join(long milliseconds) throws InterruptedException

public class joinexample extends Thread{


public void run(){
for(inti=1; i < 20; i++){
[Link]([Link]().getName());
Object Oriented Programming using Java 24CSK42
[Link](i);
}
}
public static void main(String args[]){
joinexample t1 = new joinexample();
joinexample t2 = new joinexample();
joinexample t3 = new joinexample();
[Link]();
try{
[Link](); //or [Link](1500);
}
catch(Exception e){
[Link](e);
}
[Link]();
try{
[Link](); //or [Link](1500);
}
catch(Exception e){
[Link](e);
}
[Link]();
try{
[Link](); //or [Link](1500);
}
catch(Exception e){
[Link](e);}
}
}

Output

Thread-0
1
Thread-0
2
Thread-0
3
Thread-0
4
Thread-0
5
Object Oriented Programming using Java 24CSK42
Thread-1
1
Thread-1
2
Thread-1
3
Thread-1
4
Thread-1
5
Thread-2
1
Thread-2
2
Thread-2
3
Thread-2
4
Thread-2
5

The above output clearly shows that first t1 is executed then t2 and then t3.

Join method for waiting for completion of multiple threads before proceeding ( Joining multiple
parallel threads)

public static void main(String args){


Counter c1 = new Counter(“Positive Counter”, 0, 1000);
Counter c2 = new Counter(“Negative Counter”, -1000, 0);
[Link](“Starting Positive Counter”);
Thread c1Runner = new Thread(c1);
[Link]();
[Link](“Starting Negative Counter”);
Thread c2Runner = new Thread(c2);
[Link]();
[Link](“Both counters started”);
// do something else
[Link]();
[Link](“Positive counter completed execution”);
[Link]();
[Link](“Negative counter completed execution”);
}
Thread interrupt

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's
up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common
Object Oriented Programming using Java 24CSK42
for the thread to terminate.

A thread can interrupt execution of another thread, say c1Runner, by calling the interrupt()
method of the thread object - [Link](). The interrupt status of the interrupted will
be set. Also if the thread is blocked by an invocation of join(), wait() or sleep() method,
the thread receive an InterruptedExecption.
Java provides following methods on Thread class to support interrupt
1. public void interrupt()

If the three is blocked, in an invocation of wait(), join() or sleep()), threads


i n t e r r u p t s t a t u s i s c l e a r e d a n d t h e t h r e a d r e c e i v e s a n d InterruptedException.
Otherwise, threads interrupt status flag is set.
2. public boolean isInterrupted()
Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by
this method. A thread interruption ignored because a thread was not alive at the time of the interrupt
will be reflected by this method returning false.

Returns:

True if this thread has been interrupted; false otherwise.


3. public static boolean interrupted()

Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by
this method. In other words, if this method were to be called twice in succession, the second call would
return false (unless the current thread were interrupted again, after the first call had cleared its
interrupted status and before the second call had examined it).
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected
by this method returning false.

Returns: true if the current thread has been interrupted; falseotherwise.

Sample program for interrupt


public class InterruptFlagCheckExample implements Runnable {
public void run() {
while (![Link]().isInterrupted()) {
[Link]("Thread is running.");
try {
[Link](1000); // Simulate some work
} catch (InterruptedException e) {
// Re-interrupt the thread to preserve the
Object Oriented Programming using Java 24CSK42
interrupted status
[Link]().interrupt();
[Link]("Thread was interrupted during
sleep.");
}
}
[Link]("Thread has stopped running.");
}

public static void main(String[] args) throws


InterruptedException {
Thread thread = new Thread(new InterruptFlagCheckExample());
[Link]();

[Link](3000); // Main thread sleeps for 3 seconds


[Link](); // Interrupt the running thread
}
}
Thread Name and ID
A thread has a name and id attribute which is used to uniquely identify the thread. The following
methods are available to get and set name attribute and to get the ID of the thread
public String getName()
public void setName(String name)
public long getId()

class TestJoinMethod3 extends Thread {


public void run{
[Link](“running...");
}

public static void main(String args[]{


TestJoinMethod3 t1 = new TestJoinMethod3();
TestJoinMethod3 t2 = new TestJoinMethod3();
[Link]("Name of t1:” + [Link]());
[Link]("Name of t2:” + [Link]());
[Link]("id of t1:” + [Link]());
[Link]();
[Link]();
[Link](“SonooJaiswal");
Object Oriented Programming using Java 24CSK42
[Link]("After changing name of t1:” + [Link]());
}
}

Output:
N
a
m
e

4.14. Inter thread Communication:

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its


critical section and another thread is allowed to enter (or lock) in the same critical section to be
[Link] is implemented by following methods of Object class:

• wait()
• notify()
• notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

public final void wait() throws waits until object is notified


InterruptedException

2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation. Syntax:

public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax: public final void
notifyAll().
Object Oriented Programming using Java 24CSK42

package labpgms;
class ThreadB extends Thread {
int total;
public void run() {
for (int i = 0; I < 10; i++){
total += i;
}
}
}

public class ThreadA{


public static void main(String[] args){
ThreadB b = new ThreadB();
[Link]();
[Link]("Total is: " + [Link]);

}
}

OUTPUT:
Total is: 0

In the above program, we want to print the total values calculate by ThreadB, But due to parallel
execution of threads, before ThreadB executes, main thread completes its execution printing the
value of total to be 0.

The following program, synchronises the main and ThreadB, giving the updated value of total as
result.

Example program for inter Thread Communication (Synchronised block):

package labpgms;
class ThreadB extends Thread{
int total;
public void run(){
synchronized(this){
for(int i=0; i<5 ; i++){
total += i;
notify();
}
}
Object Oriented Programming using Java 24CSK42
}

public class InterCommunicationExample {


public static void main(String[] args){ ThreadBb =
newThreadB();
[Link]();
synchronized(b){ try{
[Link]("Waiting for b to complete..."); [Link]();
//wait() tells the calling thread to give up
the monitor
//and go to sleep until some other thread enters the same
monitor
//and calls notify( ).

}
catch(InterruptedException e){ [Link]();
}
[Link]("Total is: " + [Link]);
}
}
}

OUTPUT:
Waiting for b to
complete...
Total is: 10

Producer-Consumer Program using Threads:

Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer
won’t try to remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer
removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same
way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts
data into the buffer, it wakes up the sleeping consumer. An inadequate solution could result in a
deadlock where both processes are waiting to be awakened.
Object Oriented Programming using Java 24CSK42

package labpgms;
class Q {
int n;
boolean valueSet = false; synchronized int get(){
if(!valueSet) try {

wait();
} catch(InterruptedException{
[Link]("InterruptedException caught");
}
[Link]("Got: " + n); valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet) try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught”);
}
this.n = n; valueSet = true; if(n<=5){
[Link]("Put: " + n); notify();
}}
}
class Producer extends Thread { Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 1;
while(true) {
[Link](i++);
}
}
}
class Consumer extends Thread {
Q q;
Consumer(Q q) {
this.q = q;
Object Oriented Programming using Java 24CSK42
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
[Link]();
}
}
}
class producerconsumer {
public static void main(String args[]) {
[Link]("Press Control-C to stop.”);
Q q = newQ();
Producer p1=newProducer(q);
Consumer c1=newConsumer(q);
}
}

OUTPUT:

Press Control-C to stop.

Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Object Oriented Programming using Java 24CSK42

Sample Questions

1. What is an Exception? What happens if an exception is not handled?


2. Describe the hierarchy of classes in java used for managing Exception
3. Explain the difference between checked and un-checked Exception
4. What is the difference between Exception and Error?
5. What is the use of finally block?
6. Explain how multiple exceptions can be handled in a java code.
7. Explain the need for nested try statements in java exception handling
8. What is the difference between final, finalize and finally keywords in java
9. Explain the difference between throw and throws keywords in java
10. Explain with an example program how to create custom exception in java
11. What happens to the thread when an unhandled exception occurs at runtime
12. Discuss the need for exception handling in programming
13. Write a program that illustrates resource leak when finally block is not used
What is a thread?. Explain the life cycle of a thread

Explain the two different approaches for creating threads in java with sample
program?

What is thread synchronization in multi-threaded programming? Why is it required?

Explain the concept of lock in java and describe how it is used for thread
syncrhonization?

What is join() method? Explain the need for it with example

Explain how thread priorities are set and used in java?

Explain the difference between synchronized block and synchronized method.

Explain the use of wait(), notify() and notify() all methods in java
Object Oriented Programming using Java 24CSK42

What is inter-thread communication? Why is it required? How inter-thread


communication is achieved in java ?

Provide the complete signature of main() method in java. Explain the significance
of main() method in java.

Explain why overloading of main() method is required with an example.

Discuss what is garbage collection in java.

Identify different cases where an object becomes eligible for garbage collection
Object Oriented Programming using Java 24CSK42
MODULE 5
Collection Framework

Collections Overview, Collection Interfaces, Set,


List, Map, Queue, Collection Classes, Generics,
Type Wrappers, accessing a collection using an
Iterator, Sorting collections, equals ().

5.1 Introduction
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects. Java Collections can achieve all the operations that
you perform on a data such as searching, sorting, insertion, manipulation, and
deletion.
Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
A Collection represents a single unit that contains multiple objects, i.e., a group.
What is a framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.

What is Collection Framework?

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes for representing group of


objects.
2. Algorithms like sorting, searching, copying, shuffling and more. These
algorithms as given as static methods of [Link].
The [Link] package contains all the classes and interfaces for the Collection
framework.

Page 1 of 48
Object Oriented Programming using Java 24CSK42
Core Collections Framework:
There are two main interfaces for all the collection types in Java:

• Collection<E>
• Map<K, V>
All collection interfaces and implementations are in [Link] package.

Iterable Interface

The Iterable interface is the root interface for all the collection classes.
The Collection interface extends the Iterable interface and therefore all the
subclasses of Collection interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

Page 2 of 48
Object Oriented Programming using Java 24CSK42

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.


Using the Iterator interface

The iterator method of the Iterator interface returns the iterator that iterates over the
elements in the list.

import [Link].*;

public class IteratorExample1 {

public static void main(String[] args) {

// create list

ArrayList<String> colorsList =

new ArrayList<String>();

// add colors to colorsList

[Link]("Violet");

[Link]("Indigo");

[Link]("Blue");

[Link]("Green");

[Link]("Yellow");

[Link]("Orange");

[Link]("Red");

[Link]("ColorList using iterator:");

//define iterator for colorsList

Iterator<String> i = [Link] ();

Page 3 of 48
Object Oriented Programming using Java 24CSK42
//iterate through colorsList using iterator and print each item

while([Link]( ))

[Link]([Link]() + " ");

Collection Interface

The Collection interface is the interface which is implemented by all the classes
in the collection framework. It declares the methods that every collection will have.
In other words, we can say that the Collection interface builds the foundation on
which the collection framework depends.

Methods of Collection interface:

Page 4 of 48
Object Oriented Programming using Java 24CSK42

5.2 List Interface

List interface is the child interface of Collection interface. A List is an ordered set of
objects, with indexed access to elements, like an Array. However, unlike Array, size
of the List can grow dynamically as more elements are inserted into it. A List can
contain duplicate objects. Also a List can store only Objects where are an array can
store both primitive and objects data types.

Implementations ( Classes ) of List interface:


List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

List interface provides following additional methods to perform operations specific to


lists.

• get(int index): Returns the element at the specified index in the list.
• set(int index, E element): Replaces the element at the specified index with the
given element.
• indexOf(Object o): Returns the index of the first occurrence of the specified
Page 5 of 48
Object Oriented Programming using Java 24CSK42
element in the list, or -1 if not found.
• lastIndexOf(Object o): Returns the index of the last occurrence of the specified
element in the list, or -1 if not found.
• addAll(Collection<? extends E> c): Appends all elements from the specified
collection to the end of the list.
• addAll(int index, Collection<? extends E> c): Inserts all elements from the
specified collection into the list at the specified position.
• remove(int index): Removes the element at the specified index from the list.
• subList(int fromIndex, int toIndex): Returns a view of the portion of the list
between the specified fromIndex (inclusive) and toIndex (exclusive).

Classes implementing List interface

ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed. The limitation with array is that it has a fixed length so if it is
full you cannot add any more elements to it, likewise if there are number of elements
gets removed from it the memory consumption would be the same as it doesn’t
shrink. On the other ArrayList can dynamically grow and shrink after addition and
removal of elements (See the images below). Apart from these benefits ArrayList
class enables us to use predefined methods of it which makes our task easy. Consider
the following example.

package labpgms;
// Program to demonstrate ArrayList
import [Link].*;
public class ArrayListExample {
public static void main(String args[]) {
// create an array list the following are constructors
ArrayList<String> al=new ArrayList<String>();
Page 6 of 48
Object Oriented Programming using Java 24CSK42
ArrayList a=new ArrayList(5);
[Link]("Initial size of al: " + [Link]());
// add elements to the array list
[Link]("abc");
[Link]("cde");
[Link]("fgh");
[Link]("ijk");
[Link]("lmn");
[Link]("pqr");
[Link](1, "steve");
[Link]("Size of al after additions: " +
[Link]());
[Link]("element at 1 index is"+ [Link](1));
//display using iterator
[Link]("using iterator");
Iterator iter = [Link]();
while ([Link]()) {
[Link]([Link]());}

// Remove elements from the array list


[Link]("abc");

[Link](2);

[Link]("Size of al after deletions: " + [Link]());


[Link]("Contents of al: " + al);
[Link](al);//sorting array list elements
[Link]("Contents of al: " + al);

}}

Output:

Initial size of al: 0

Size of al after additions: 7 element at 1 index issteve

using iterator

abc

steve

cde

Page 7 of 48
Object Oriented Programming using Java 24CSK42
fgh

ijk
lmn

pqr

Size of al after deletions: 5

Contents of al: [steve, cde, ijk, lmn, pqr]

Contents of al: [cde, ijk, lmn, pqr, steve]

** ArrayList allows duplicate values. For example in the above program a statement like

[Link](1, ”stevejob”);

adds “stevejobs” at index 1 and earlier value “steve” moves to second position.

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is [Link] List are linear data structures where the elements are not
stored in contiguous locations and every element is a separate object with a data part
and address part. The elements are linked using pointers and addresses. Each element
is known as a node. Due to the dynamicity and ease of insertions and deletions, they
are preferred over the arrays. It also has few disadvantages like the nodes cannot be
accessed directly instead we need to start from the head and follow through the link
to reach to a node we wish to access. To store the elements in a linked list we use a
doubly linked list which provides a linear data structure and also used to inherit an
abstract class and implement list and deque interfaces.
In Java, LinkedList class implements the list interface. The LinkedList class also
consists of various constructors and methods like other java collections.

Constructors for Java LinkedList:

LinkedList(): Used to create an empty linked list.

LinkedList(Collection C): Used to create a ordered list which contains all the
elements of a specified collection, as returned by the collection’s iterator.
Consider the following example.
package labpgms_Second;

Page 8 of 48
Object Oriented Programming using Java 24CSK42
import [Link];

import [Link];

import [Link];

public class LinkedListExample {


public static void main(String[] args) {
// Creating object of class linked list
LinkedList<String> object = new LinkedList<String>();

// Adding elements to the linked list


[Link]("A");

[Link]("B");
[Link]("C");
[Link]("D");
[Link](2, "E");
[Link]("F");
[Link]("G");
[Link]("Linked list : " + object);
// Removing elements from the linked list
[Link]("B");
[Link](3);
[Link]();
[Link]();

[Link]("Linked list after deletion: " +


object);
// Finding elements in the linked list
boolean status = [Link]("E");
if(status)
[Link]("List contains the element 'E' ");
else
[Link]("List doesn't contain the element
'E'");
// Number of elements in the linked list

Page 9 of 48
Object Oriented Programming using Java 24CSK42
int size = [Link]();
[Link]("Size of linked list = " + size);

// Get and set elements from linked list


Object element = [Link](2);

[Link]("Element returned by get() : " +


element);

[Link](2, "Y");
[Link]("Linked list after change : " +
object);
}
}

Output:
Linked list :[D, A, E, B, C, F,G]
Linked list after deletion: [A, E, F]

List contains the element 'E'

Size of linked list = 3 Element


returned by get() : F

Linked list after change : [A, E, Y]

Vector

The Vector class implements a growable array of objects. Vectors basically fall in
legacy classes but now it is fully compatible with collections. Vector implements a
dynamic array that means it can grow or shrink as required. Like an array, it contains
components that can be accessed using an integer index. They are very similar to
ArrayList but Vector is synchronised and have some legacy method which collection
framework does not [Link] extends AbstractList and implements List interfaces.

Constructor:

Vector(): Creates a default vector of initial capacity is 10.


Page 10 of 48
Object Oriented Programming using Java 24CSK42
Vector(int size): Creates a vector whose initial capacity is specified by size.

Vector(int size, int incr): Creates a vector whose initial capacity is specified by size
and increment is specified by incr. It specifies the number of elements to allocate
each time that a vector is resized upward.

Vector(Collection c): Creates a vector that contains the elements of collection c.

Consider the following example.


package labpgms_Second;
import [Link].*;
public class vectorExample {
public static void main(String[] args) {
Vector v = new Vector();

ArrayList a = new ArrayList();


[Link](10);

[Link](20);
[Link](30);
[Link](10.4);
[Link](34);
[Link]("ff");

[Link](2,”kkk"); //adding with index


[Link](a); //adds ArrayList elements to the vector
list

[Link](v);
Vector vCone = new Vector();
vClone = (Vector) [Link]();//clones a vector object
[Link](vClone);

vClone("10"); //removes element


[Link](“HASH CODE IS “ + [Link]());
[Link]();

[Link](v);}}

Page 11 of 48
Object Oriented Programming using Java 24CSK42

Output:

[10.4, 34, kkk, ff, 10, 20, 30]


[10, 20, 30, 10.4, 34, kkk, ff, 10, 20, 30]
[10, 20, 30, 10.4, 34, kkk, ff, 10, 20, 30]
HASH CODE IS 1842549099
[]

Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines
its properties.

Page 12 of 48
Object Oriented Programming using Java 24CSK42
Consider the following Example.

package labpgms_Second;
import [Link];
import [Link];

public class StackExample {


public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();

for(int i = 0; i < 5; i++) {


[Link](i);

}
[Link]("the elements of stack are:");
Iterator<Integer> itr= [Link]();
while([Link]()){

[Link]([Link]()); }
[Link]("element removed is” +

[Link]()); //removes and returns the top most element


of stack

[Link]("top most element of stack


is:"+[Link]());//returns the top element of stack
[Link]([Link]());//return true if stack is
empty otherwise false

[Link]([Link](0)); // returns the


position of element

//from top of stack starting with 1 if element is present


otherwise -1

}
}

Output:

the elements of stack are:

Page 13 of 48
Object Oriented Programming using Java 24CSK42
0
1
2
3
4
element removed is4
top most element of stack is:3
false

Queue Interface

The Queue interface is available in [Link] package and extends the Collection
interface. The queue collection is used to hold the elements about to be processed and
provides various operations like the insertion, removal etc. It is an ordered list of
objects with its use limited to insert elements at the end of the list and deleting
elements from the start of list i.e. it follows the FIFO or the First-In-First-Out
principle. Being an interface the queue needs a concrete class for the declaration and
the most common classes are the PriorityQueue and LinkedList in [Link] is to be
noted that both the implementations are not thread safe.

Characteristics of Queue are:

● The Queue is used to insert elements at the end of the queue and removes from
the beginning of the queue. It follows FIFO concept.
● The Java Queue supports all methods of Collection interface including
insertion, deletion etc.
● LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently
used implementations.
● If any null operation is performed on BlockingQueues, NullPointerException is
thrown.
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO,
first element is removed first and last element is removed at last.

Queue Interface declaration

Page 14 of 48
Object Oriented Programming using Java 24CSK42

1. public interface Queue<E> extends Collection<E>


Methods of Java Queue Interface

Method Description
boolean It is used to insert the specified element into this queue and
add(object) return true upon success.

boolean It is used to insert the specified element into this queue.


offer(object)

Object It is used to retrieves and removes the head of this queue.


remove()
Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.

Object It is used to retrieves, but does not remove, the head of this
element() queue.

Object It is used to retrieves, but does not remove, the head of this
peek() queue, or returns null if this queue is empty.

package labpgms_Second;
import [Link].*;
public class QueueExample {
public static void main(String[] args) {
Queue<Integer> q=new PriorityQueue<Integer>();
[Link](10);

[Link](20);
[Link](30);
[Link]("the elements of queue are:");
Iterator<Integer> itr= [Link]();
while([Link]()){

Page 15 of 48
Object Oriented Programming using Java 24CSK42
[Link]([Link]()); }
[Link]("peek"+[Link]()); //head element in
queue,

//if queue is empty returns NULL


[Link](“element" + [Link]());//similar to
peek,NoSuchElementException if empty

//removes and returns the head of queue throws


NoSuchElementException

[Link]("removed element is"+[Link]());


//similar to remove return NULL if no elements
[Link]("poll is” + [Link]());
[Link]("size of the queue is"+[Link]()); //
size of the queue }}

Output
the elements of queue are:
10
20
30
peek10
element10

removed element is10


poll is20

size of the queue is1

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.

Consider the following example.

Page 16 of 48
Object Oriented Programming using Java 24CSK42
import [Link].*;
public class TestJavaCollection5 {
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Amit Sharma");
[Link]("Vijay Raj");
[Link]("JaiShankar");
[Link]("Raj");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]("iterating the queue elements:");
Iterator itr=[Link]();
while([Link]()) {
[Link]([Link]());
}
[Link]();
[Link]();

[Link]("after removing two elements:");


Iterator<String> itr2=[Link](); while([Link]()){

[Link]([Link]());

}
}
}

OUTPUT

head:Amit Sharma
head:Amit Sharma

iterating the queue elements: Amit


Sharma

Raj JaiShankar
Vijay Raj

after removing two elements: Raj

Page 17 of 48
Object Oriented Programming using Java 24CSK42
Vijay Raj

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables
us to perform the operations at both the ends.
Deque can be instantiated as:
1. Deque d = new ArrayDeque();
ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
import [Link].*;
public class TestJavaCollection6 {
public static void main(String[] args) {
//Creating Deque and adding elements Deque<String> deque = new
ArrayDeque<String>(); [Link]("Gautam");
[Link]("Karan");
[Link]("Ajay");
//Traversing elements
for (String str : deque) {
[Link](str);
}
}
}
Output:
Gautam
Karan
Ajay

Page 18 of 48
Object Oriented Programming using Java 24CSK42
5.3 Set in Java

● Set is an interface which extends Collection. It is an unordered collection of


objects in which duplicate values cannot be stored.
● Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted
representation).
● Set has various methods to add, remove clear, size, etc to enhance the usage of
this interface
Classes that directly implement Set interface are HashSet and LinkedHashSet. Java
provides another interface SortedSet, that extends Set interface, which is a set in
which elements are in stored sorted order. Class TreeSet is an implementation of
SortedSet.

In addition to operations defined in Collection interface, Set interface provides


following methods for performing union, intersection, set difference and subset.
boolean retainAll(Collection<?> c)
Retains only the elements in this set that are contained in specified collection.
boolean removeAll(Collection<?> c)
Remove all elements of the specified collection from this collection
boolean containsAll(Collection<?> c)
Returns true if this set contains all elements of the specified collection
boolean addAll(Collection<? extends E> c)
Add all distinct elements of the specified collection to this collection if they are not
already present.

Page 19 of 48
Object Oriented Programming using Java 24CSK42
Example program:

package labpgms_Second;
import [Link];
import [Link];
import [Link];

public class setexample {


public static void main(String[] args) {
Set<String> hash_Set = new HashSet<String>();

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


hash_Set.add("delhi");

hash_Set.add("andhra");
hash_Set.add("cochin");
hash_Set1.add("telangana");
hash_Set1.add("andhra");
hash_Set1.add("karnataka");
[Link]("hash_set is"+hash_Set);
[Link]("hash_Set1 is"+hash_Set1);
hash_Set.addAll(hash_Set1); //union of two sets
[Link]("union of both sets is"+hash_Set);
hash_Set.retainAll(hash_Set1);//intersection of two sets
[Link]("intersection is"+hash_Set);
// Set demonstration using TreeSet
//[Link]("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
[Link](tree_Set);

}
}

Output:
hash_set is[andhra, delhi, cochin]
hash_Set1 is[andhra, karnataka, telangana]
union of both sets is[andhra, karnataka, telangana, delhi, cochin]

intersection is[andhra, karnataka, telangana]

Page 20 of 48
Object Oriented Programming using Java 24CSK42
[andhra, karnataka, telangana]

Example-2:packagelabpgms_Second;
import [Link].*;
import [Link];
import [Link];
import [Link];
public class hashsetexample {
public static void main(String[] args)
{
HashSet<String> a1=new HashSet<String>();//set interface,unordered,no
duplicates allowed

[Link]("abc");
[Link]("defghij");
[Link]("abcd");
[Link]("hashset is"+a1);

[Link]([Link]("abcd"));//removes and
returns true if element is present otherwise false

[Link]("hashset is"+a1);
LinkedHashSet<String> a=new LinkedHashSet<String>();//
linked in the order of the elements added

[Link]("abc");
[Link]("defghij");
[Link]("abcd");
[Link]("ooo");
[Link]("linkedhashset is"+a);

TreeSet<String> t=new TreeSet<String>();//sorted set of


elements

[Link]("andra");
[Link]("zzz");
[Link]("ccc");
[Link]("tree_set is"+t);

Page 21 of 48
Object Oriented Programming using Java 24CSK42

}} fghij, abcd, ooo]

OUTPUT: tree_set is[andra, ccc, zzz]


hashset
is[defgh
ij, abc,
abcd]
true
hashset
is[defgh
ij, abc]
l
i
n
k
e
d
h
a
s
h
s
e
t

i
s
[
a
b
c
,

d
e

Page 22 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.
SAME EXAMPLE FOR Set Interface can be considered.

//declaration of HashSet object HashSet<String> h1 = new


hashSet<String>();

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It


extends the HashSet class and implements Set interface. Like HashSet, It also
contains unique elements. It maintains the insertion order and permits null elements.
Consider the following example.
import [Link].*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
[Link]("Ravi");

[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}}

Output:
Ravi
Vijay
Ajay
Page 23 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural ordering
of the elements.
The SortedSet can be instantiated as:
1. SortedSet<data-type> set = new TreeSet();

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Consider the following example:

import [Link].*;
public class TestJavaCollection9 {
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
[Link]("Ravi");

[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//traversing elements
Iterator<String> itr=[Link]();
while([Link]()){

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

Page 24 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Output:
Ajay
Ravi
Vijay

5.4 Java Map Interface


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

Java Map Hierarchy


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

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key
or value.

Page 25 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

A Map can’t be traversed, so your need to convert it into Set using keySet() or
entrySet() method.
Put and Get operations in HashMap
A key value pair is inserted into a Map using method put(Object key,
Object value). Figure below shows the steps of operations involved when a new
key-value pair is inserted into the Map. First, the hash of the key object is evaluated
using the hashCode() function. The hash value is used to find the index into the
internal array where values are stored. The object is inserted at location index. If
there is a collision, multiple key-value pairs are stored at the same index as a linked
list.

Internal sequence of operations during put() operation in a Map


Source: [Link]
part3-hashmap-internal-working-563bb13bf8d0

Page 26 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Internal sequence of operations during get) operation in a Map Source:


[Link]
programs-part3-hashmap-internal-working-563bb13bf8d0

The value associated with a particular key stored in the Map is obtained using the
get(Object key) function. When the get() method is invoked, the
hashCode() of the key object is called again to evaluate the array index. The value
at location pointed by index is retrieved and returned.

Useful methods of Map interface


Method Description

V put(Object key, Object value) It is used to insert an entry in the map.


void putAll(Map map) It is used to insert the specified map in
the map.

V putIfAbsent(K key, V value) It inserts the specified value with the


specified key in the map only if it is not
already specified.

V remove(Object key) It is used to delete an entry for the


specified key.

Page 27 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

boolean remove(Object key, It removes the specified values with the


Object value) associated specified keys from the map.

Set keySet() It returns the Set view containing all the


keys.

Set<[Link]<K, V>> It returns the Set view containing all the


entrySet() keys and values.

void clear() It is used to reset the map.

V compute (K key, BiFunction<? It is used to compute a mapping for the


super K, ? super V, ? extends V> specified key and its current mapped
remappingFunction ) value (or null if there is no current
mapping).

V computeIfAbsent (K key, It is used to compute its value using the


Function<? super K,? extends given mapping function, if the specified
V> mappingFunction) key is not already associated with a value
(or is mapped to null), and enters it into
this map unless null.

V computeIfPresent (K key, It is used to compute a new mapping


BiFunction<? super K,? super given the key and its current mapped
V,? extends V> value if the value for the specified key is
remappingFunction) present and non-null.

//demonstrate hashmap <key-value> pair


package labpgms;
import [Link].*;
public class hashmapexample {
public static void main(String[] args)
{ Scanner s=new Scanner([Link]);
HashMap<Integer,Integer> map = new

HashMap<Integer,Integer>();

Page 28 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

[Link](1,12);
[Link](2, 12); //hashcode()--hashing function---
buckets(positions)

[Link](3, 34);
[Link](4, 35);
[Link](map);

for(int i=1;i<5;i++)
{
[Link]("key:"+i+" "+"value is"+ "
"+[Link](i));

}
Hashtable<Integer,String> map11 = new
Hashtable<Integer,String>();
[Link](121,"abc");
[Link](136, "abc");
[Link](49, "def1");
[Link](215, "def2");
[Link](map11);

[Link]([Link]());
String n1,n2;

TreeMap<String, String> map1 = new TreeMap<String,


String>();

[Link]("1","sabc");
[Link]("102", "sdef");
[Link]("36", "sdef1");
[Link]("4", "sdef2");
//sending user values
/*for(int i=0;i<5;i++) CAN ALSO
ACCPET VALUES FROM USER AND SEND TO MAP

Page 29 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

n1=[Link]();
n2=[Link]();
[Link](n1,n2);

}*/
//displaying the values thru iterator

Iterator <String> key1 = [Link]().iterator();


while([Link]())
{
String key = [Link]();
[Link]("key: " + key + " value: " +

[Link](key));
}
}}

Sample programs using HashMap

1. Counting the frequency of each word in a string


import [Link];
import [Link];

public class WordCount {


public static void main(String[] args) {
String s = "A java program is written in a text file with extension java
and compiled to a java class file";
HashMap<String,Integer> wordCount = new
HashMap<String,Integer>();

String[] words = [Link](" ");


for(String word:words){

int count = [Link](word, 0);


[Link](word, count + 1);

Page 30 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

for( String word : [Link]()){


[Link](word + ":" + [Link](word));

}
}
}

5.5 Sorting collections


[Link]() method is present in [Link] class. It is used
to sort the elements present in the specified list of Collection in ascending order. It
works similar to [Link]() method but it is better then as it can sort the
elements of Array as well as linked list, queue and many more present in it.
// Java program to demonstrate working of [Link]()

import [Link].*;
public class CollectionSorting {
public static void main(String[] args) {
// Create a list of strings
ArrayList<String> al = new ArrayList<String>();
[Link]("Geeks For Geeks");

[Link]("Friends");
[Link]("Dear");
[Link]("Is");
[Link]("Superb");
/* [Link] method is sorting the
elements of ArrayList in ascending order. */
[Link](al);

// Let us print the sorted list


[Link]("List after the use of" +

" [Link]() :\n" + al);


}
}

Output:

Page 31 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

List after the use of [Link]() :

[Dear, Friends, Geeks For Geeks, Is, Superb]

Sorting an ArrayList in descending order:

// Java program to demonstrate working of [Link]()


// to descending order.
import [Link].*;

public class CollectionSorting {


public static void main(String[] args) {
// Create a list of strings
ArrayList<String> al = new ArrayList<String>();
[Link]("Geeks For Geeks");

[Link]("Friends");
[Link]("Dear");
[Link]("Is");
[Link]("Superb");

/* [Link] method is sorting the


elements of ArrayList in ascending order. */
[Link](al, [Link]());

// Let us print the sorted list


[Link]("List after the use of" +

" [Link]() :\n" + al);


}
}

OUTPUT:

Page 32 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

List after the use of [Link]() :

[Superb, Is, Geeks For Geeks, Friends, Dear]

Sorting an ArrayList according to user defined criteria.

We can use Comparator Interface for this purpose.


package labpgms_Second;
import [Link].*;
import [Link].*;
import [Link].*;

// A class to represent a student.


class Student {

int rollno;
String name, address;
int no;

// Constructor
public Student(int rollno, String name,
String address, int n) {
[Link] = rollno;
[Link] = name;
[Link] = address;
[Link]=n;

// Used to print student details in main()


public String toString(){

return [Link] + " " + [Link] +


" " + [Link] +" "+ [Link];
}

Page 33 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

}
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b) {
return [Link] - [Link];

}
}

// Driver class
class CollectionSortex {
public static void main (String[] args){
Student s1=new Student(111, "bbbb", "london",30);
Student s2=new Student(131, "aaaa", "nyc",6);
Student s3=new Student(121, "cccc", "jaipur",89);
ArrayList<Student> ar = new ArrayList<Student>();
[Link]("Unsorted");

[Link](s1);
[Link](s2);
[Link](s3);
[Link](ar);

for (int i=0; i<[Link](); i++)


[Link]([Link](i)); //[Link](ar);

[Link](ar, new Sortbyroll());


[Link]("\nSorted by no");
for (int i=0; i<[Link](); i++)

[Link]([Link](i));
}
}

Page 34 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

OUTPUT:

Unsorted
[111 bbbb london 30, 131 aaaa nyc 6, 121 cccc jaipur 89]

111 bbbb london 30


131 aaaa nyc 6
121 cccc jaipur 89
Sorted by no

131 aaaa nyc 6


111 bbbb london 30
121 cccc jaipur 89

5.6 equals() and hashCode() methods in Java

[Link] has two very important methods defined: public boolean


equals(Object obj)and public int hashCode().

In java equals()method is used to compare equality of two Objects.

• Shallow comparison: The default implementation of equals method is defined in


[Link] class which simply checks if two Object references (say x and y) refer to the
same Object. i.e. It checks if x == y. Since Object class has no data members that define its
state, it is also known as shallow comparison.
• Deep Comparison: Suppose a class provides its own implementation of equals() method in
order to compare the Objects of that class w.r.t state of the Objects. That means data members
(i.e. fields) of Objects are to be compared with one another. Such Comparison based on data
members is known as deep comparison. Examples, two instances of Rectangle class can be
considered as equal if their lengthand widthproperties are have the same value.

hashCode() method

● It returns the hash code value as an Integer. Hash code value is mostly used in hashing based
collections like HashMap, HashSet, HashTable etc. When an object is used as a key to an
entry in HashMap, the hashCode() method is invoked to get an integer value corresponding
to the object which used as hash key for the hash map. This method must be overridden in
every class which overrides equals() method.

The general contract of hashCode is:

● During the execution of the application, if hashCode() is invoked more than once on the same
Object then it must consistently return the same Integer value, provided no information used
in equals(Object) comparison on the Object is modified. It is not necessary that this Integer
value to be remained same from one execution of the application to another execution of the
same application.
Page 35 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

● If two Objects are equal, according to the equals(Object) method, then hashCode() method
must produce the same Integer on each of the two Objects.
● If two Objects are unequal, according to the equals(Object) method, It is not necessary the
integer value produced by hashCode() method on each of the two Objects will be distinct. It
can be same but producing the distinct Integer on each of the two Objects is better for
improving the performance of hashing based Collections like HashMap, HashTabe. Etc.

Note: Equal objects must produce the same hash code as long as they are equal,
however unequal objects need not produce distinct hash codes.
Example program overriding equals and HashMap method

import [Link];
public class BankAccount

private String accountNumber;


private String accountHolderName;
private double balance;

public BankAccount(String accountNumber, String


accountHolderName, double balance)

[Link] = accountNumber;
[Link] = accountHolderName;
[Link] = balance;

}
// Getters and setters
public static void main(String [] args)
{
BankAccount account1 = new BankAccount("Savings", "Test",
2022);
BankAccount account2 = new BankAccount("Savings", "Test",
2022);
[Link]([Link](account2)); // returns
false
}

Page 36 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Output:

false

In the above program, equals() methods returns false as the default implementation in
Object class is reference comparison (account1 == account2). The
comparison does not check the value of object attributes like account
accountNumber. In the below code we override the equals method to redefine
the comparison using key fields of the the Account object.

import [Link];
public class BankAccount

//Fields And Constructors


// Getters and setters
// Equals method implementation
@Override

public boolean equals(Object obj) {


if (this == obj) {

return true;
}
if (obj == null || getClass() != [Link]()) {
return false;

}
BankAccount otherAccount = (BankAccount) obj;
return [Link](accountNumber,

[Link])
&& [Link](accountHolderName,
[Link])

&& [Link](balance, [Link]) == 0;


}

Page 37 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

public static void main(String [] args) {


BankAccount account1 = new BankAccount("Savings", "Test",
2022);

2022);

true
} }

Output

true

However, since hashCode method is not overridden, the default implementation of


hashCode() method in object class used the object reference to generate the hash
code and returns different hash code for account1 and account2 object which
violates the contract with new implementation of equals methods.

The hashCode() method should also be overridden so that it returns the same hash code of account1
and account2 ( as [Link](account2) is true).

import [Link];
public class BankAccount {

//Fields And Constructors


// Getters and setters
@Override

public int hashCode() {


int result;

long temp;
result = [Link]();
result = 31 * result + [Link]();
temp = [Link](balance);

result = 31 * result + (int) (temp ^ (temp >>> 32));


return result;

Page 38 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

public static void main(String [] args) {


BankAccount account1 = new BankAccount("Savings", "Test",
2022);

BankAccount account2 = new BankAccount("Savings", "Test",


2022);

[Link]([Link](account2)); // true
[Link]([Link]());//-813975577

[Link]([Link]());//-813975577
}
}

Page 39 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Type Wrappers:

Wrapper Classes in Java

A Wrapper class is a class whose object wraps or contains a primitive data types.
When we create an object to a wrapper class, it contains a field and in this field, we
can store a primitive data types. In other words, we can wrap a primitive value into a
wrapper class object.

Need of Wrapper Classes

They convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method (because primitive types are passed by
value). The classes in [Link] package handles only objects and hence wrapper
classes help in this case also. Data structures in the Collection framework, such
as ArrayList and Vector, store only objects (reference types) and not primitive types.
An object is needed to support synchronization in multithreading.

Primitive Data types and their Corresponding Wrapper class:

Page 40 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

BankAccount account2 = new BankAccount("Savings", "Test",

[Link]([Link](account2)); // returns

Class hierarchy of wrapper classes

• All numeric wrapper classes extends [Link]


• Classes Boolean and Character directly extend Object class
• All wrapper classes implement interface [Link] and
[Link]
Autoboxing and Unboxing

• Autoboxing is the automatic conversion of a primitive data type to


corresponding wrapper class object.

class Autoboxing {
public static void main(String[] args) {
Boolean bool = true;

Character ch = 'c';
Byte b = 2;

Short s = 2;
Integer i = 1;
Long l = 4L;
Float f = 1.2f;
Double d = 1.2;
Page 41 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

}
}

• Unboxing is the reverse of autoboxing. It is automatic conversion of wrapper


class to primitive data type.

Methods for Creating an object of Wrapper class

1. Autoboxing
2. Constructor
3. Static method
class WrapperUsingConstructor {
public static void main(String[] args) {

// Constructors that accepts primitive Value


Boolean bool1 = new Boolean(true);
Character char1 = new Character('c');
Byte byte1 = new Byte((byte) 3);

Short short1 = new Short((short) 2);


Integer int1 = new Integer(1);

Long long1 = new Long(4L);


Float float1 = new Float(1.2f);

Double double1 = new Double(1.5);

// Constructors that accepts String Value


Boolean bool2 = new Boolean("true");

// Character char2 = new Character("c"); -> Won't compile


Byte byte2 = new Byte("3");

Short short2 = new Short("2");


Integer int2 = new Integer("1");
Long long2 = new Long("4");
Float float2 = new Float("1.2");

Double double2 = new Double("1.5");

Page 42 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

}
}

class WrapperUsingStaticMethod {
public static void main(String[] args) {
// Static methods that accepts primitive Value
Boolean bool1 = [Link](true);
Character char1 = [Link]('c');

Byte byte1 = [Link]((byte) 3);


Short short1 = [Link]((short) 2);
Integer int1 = [Link](1);

Long long1 = [Link](4L);


Float float1 = [Link](1.2f);

Double double1 = [Link](1.5);

// Static methods that accepts String Value


Boolean bool2 = [Link]("true");

// Character char2 = [Link]("c"); -Won’t compile


Byte byte2 = [Link]("3");

Short short2 = [Link]("2");


Integer int2 = [Link]("1");
Long long2 = [Link]("4");
Float float2 = [Link]("1.2");

Double double2 = [Link]("3.5");

}
}

Retrieving primitive value from wrapper object

class WrapperToPrimitive {
public static void main(String[] args) {
Boolean bool2 = [Link]("true");

Page 43 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Character char2 = [Link]('c');


Byte byte2 = [Link]("3");

Short short2 = [Link]("2");


Integer int2 = [Link]("1");
Long long2 = [Link]("4");
Float float2 = [Link]("1.2");

Double double2 = [Link]("3.5");

// Retrieve primitive value from the wrapper object


boolean bool = [Link]();

char ch = [Link]();
byte b = [Link]();
short s = [Link]();
int i = [Link]();

long l = [Link]();
float f = [Link]();

double d = [Link]();

}
}

Parsing String value to primitive

All the wrapper classes, except Character, defines static utility method to parse a String to
corresponding primitive data type.

class StringToPrimitive {
public static void main(String[] args) {
// Retrieve primitive value from string
boolean bool = [Link]("true");
byte b = [Link]("2");

short s = [Link]("3");
int i = [Link]("4");

Page 44 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

long l = [Link]("5");
float f = [Link]("6.6");

double d = [Link]("7.7");
}
}

Page 45 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Sample Questions

1. Give an overview of interfaces in java collection framework

2. What is the difference between [Link] and [Link] ?


3. What are the differences between List, Set and Map?

4. What are Wrapper classes in java ? Explain the need for Wrapper classes
5. Explain what is shallow comparison and deep comparison of java objects
with example

6. What is the use of equals() and hashCode() method in Object class?

7. Explain the contract to be followed while overriding equals and


hashCode method. Explain why is this contract necessary with
respect to HapshMap.

8. Explain how to sort objects based on custom criteria in java with an example

9. Discuss the different interfaces and algorithms provided in collection


framework

10. Explain the differences between Set and List interface.

11. What is the difference between [Link], [Link]


and [Link]?

12. Explain the methods provided by java collection framework for


sorting a collection of objects.

13. Explain the important methods in Map interface used to insert an item,
retrieve an item and check if an item is present in the Map.

14. What is the difference between, HashSet, HashMap and TreeMap?

15. What is linked HashSet in java


16. Explain different interfaces and classes for Stack data structure in java

17. Explain different interfaces and classes for Queue data structure in java

18. Write an interface Shape with method area() that returns the area of the
shape. Implement two classes Rectangle and Circle that implements

Page 46 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42

Shape class. Write a function that takes a List of Shape objects and sort
them based on area.

19. Write a java class Rectangle that has two attributes length and width.
Override equals() and hashCode method so that two rectangles with
same length and width are equal. Use a HashSet to de-dupe a List of
Rectangle objects.

Page 47 of 48
Object oriented programming using Java 24CSK42

Page 1 of 48

You might also like