24CSK42 OOPs Using Java All Module Notes
24CSK42 OOPs Using Java All Module Notes
COURSE MATERIAL
Academic year: 2025-2026
Semester: 4
Course Code & Name: 24CSK42– Object Oriented
Programming using Java
Course Coordinator: Dr Karthiyayini
[Link]. Swathi
Object Oriented Programming using Java 24CSK42
MODULE 1
Introduction to Java
Here are important landmarks from the history of the Java language:
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.
• 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) 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.
• 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.
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.
• 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.
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. 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
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
Types of Variables
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.
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.
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
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
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
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
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
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.
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
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.
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.
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.
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.
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.
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.
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.
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.
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest
range of Unicode system.
classGeeksforGeeks {
publicstaticvoidmain(String args[])
{
// declaring character
chara = 'G';
Object Oriented Programming using Java 24CSK42
shorts = 56;
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
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
or
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
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
Object Oriented Programming using Java 24CSK42
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 −
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to [Link]-1.
Example
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 {
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Object Oriented Programming using Java 24CSK42
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0
2) Assignment Operators
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 —
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
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.
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 or equal to right side.
<= returns true if left side is less than or equal to right side.
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
}
}
6) Bitwise Operators
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
result = ~num1;
[Link]("~num1: "+result);
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
num2: 200
num2: 100
1.8 Control Statement- Decision Making in Java (if, if-else, switch, break, continue,
jump)
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;
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");
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:
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:
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
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:
Break:
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;
i: 4
Loop complete.
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");
// 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
if (t)
return;
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.
int x = 1;
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:
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.
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
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
Example While running a class Demo, you can specify command line arguments as
Example:
To Learn java Command Line Arguments
class CommandLineExample {
public static void main(String[] args) {
Output:
Number of arguments: 3
Argument 0: Hello
Argument 1: 123
Argument 2: Java
Object Oriented Programming using Java 24CSK42
OOPs Concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Class
Object
Method
Message Passing
Object Oriented Programming using Java 24CSK42
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
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:
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.
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.
Syntax:
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.
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.
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
• 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:
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
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. }
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
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
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{
....
....
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.
[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 {
[Link](g + h);
[Link](g + h);
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:
class Main
{
Object Oriented Programming using Java 24CSK42
[Link]('G');
[Link]('S','J');
Output:
You have typed the letter: G
Program to Demonstrate Method Overloading Based on the Sequence of Data Type in the
Parameters
Example:
class DispOvrload
class Main
Object Oriented Programming using Java 24CSK42
[Link]('G',62);
[Link](46,'S');
Output:
The 'show method' is defined for the first time.
• 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
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.
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
}
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.
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
Output:
public class Employee{
int empId;
String empName;
Id:10245Name:Chaitanya
Id:92232Name:Negan
Object Oriented Programming using Java 24CSK42
class Example2
{
private intvvar;
//default constructor
public Example2()
{
[Link]=10;
}
//parameterized constructor
public Example2(int num)
{
[Link]= num;
}
Output:
varis:10
varis:100
Object Oriented Programming using Java 24CSK42
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. 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.
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.
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.
Output:
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);
Output:
1
1
1
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.
Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}
Output:
1
2
3
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.
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
//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;
}
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
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
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
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
Object Oriented Programming using Java 24CSK42
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.
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.
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:
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
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 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.
class Base_class_name
//Access_specifier member_function(parameter_list);
Page 1 of 102
Object Oriented Programming using JAVA 24CSK42
Inheritance:
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.
class A
{ int i, j;
void showij()
class B extends A
{ int k;
void showk()
Page 2 of 102
Object Oriented Programming using JAVA 24CSK42
void sum()
{ [Link]("i+j+k: " + (i+j+k));
class SimpleInheritance {
superOb.i = 10;
superOb.j = 20;
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
Page 3 of 102
Object Oriented Programming using JAVA 24CSK42
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.
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.
[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.
• 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.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
• 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
Car() {
Output:
This is a Vehicle
Page 6 of 102
Object Oriented Programming using JAVA 24CSK42
Program Code:
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
FourWheeler() {
Car() {
Page 7 of 102
Object Oriented Programming using JAVA 24CSK42
Output:
This is a Vehicle
4 Wheeler Vehicles
Program Code:
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
Car() {
Page 8 of 102
Object Oriented Programming using JAVA 24CSK42
Bus() {
Output:
This is a Vehicle
This is a Vehicle
• 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
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 j; // private to A
{ i = x; j = y;
class B extends A
{ int total;
void sum()
class Access
[Link](10, 12);
[Link]();
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.
class Box
Box(Box ob)
width = [Link];
height = [Link];
depth = [Link];
Page 11 of 102
Object Oriented Programming using JAVA 24CSK42
Box()
Box(double len)
double volume()
Page 12 of 102
Object Oriented Programming using JAVA 24CSK42
class DemoBoxWeight
double vol;
vol = [Link]();
vol = [Link]();
Output:
A reference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.
Class RefDemo
Page 13 of 102
Object Oriented Programming using JAVA 24CSK42
double vol;
vol = [Link]();
plainbox = weightbox;
/* The following statement is invalid because plainbox does not define a weight
member.*/
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
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";
{ String color="black";
void printColor()
class TestSuper
[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.
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...");
{ 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
[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
{ Dog()
{ super();
[Link]("dog is created");
class TestSuper
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
Page 18 of 102
Object Oriented Programming using JAVA 24CSK42
Box(Box ob)
Box()
Box(double len)
double volume()
// Add weight.
{ double weight;
BoxWeight(BoxWeight ob)
Page 19 of 102
Object Oriented Programming using JAVA 24CSK42
{ super(ob);
weight = [Link];
{ super(w, h, d);
weight = m;
BoxWeight()
{ super();
weight = -1;
{ super(len);
weight = m;
{ double cost;
Shipment(Shipment ob)
{ super(ob);
cost = [Link];
Page 20 of 102
Object Oriented Programming using JAVA 24CSK42
cost = c;
Shipment()
{ super(len, m);
cost = c;
class DemoShipment
double vol;
vol = [Link]();
[Link]();
Page 21 of 102
Object Oriented Programming using JAVA 24CSK42
vol = [Link]();
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()
class B extends A
{ B()
Page 22 of 102
Object Oriented Programming using JAVA 24CSK42
class C extends B
{ C()
class CallingCons
{ C c = new C();
Output :
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.
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()
class B extends A
{ int k
{ super(a, b); k = c;
void show()
class Override
Page 24 of 102
Object Oriented Programming using JAVA 24CSK42
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;
{ super(a, b); k = c;
void show()
Output: i and j: 1 2 k: 3
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()
class B extends A
{ int k;
{ super(a, b);
k = c;
// overload show()
{ [Link](msg + k);
class Override
Page 26 of 102
Object Oriented Programming using JAVA 24CSK42
This is k: 3 i and j: 1 2
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.
class ABC
{ //Overridden method
Page 27 of 102
Object Oriented Programming using JAVA 24CSK42
{ //Overriding method
{ /*When Parent class reference refers to the parent class object then in this case
overridden method (the method of parent class) is called. */
[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. */
[Link]();
Output:
Page 28 of 102
Object Oriented Programming using JAVA 24CSK42
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 .
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{
[Link]("Overridden method");
[Link]();
Page 29 of 102
Object Oriented Programming using JAVA 24CSK42
[Link]("Overriding method");
[Link]();
Output:
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.
• Annotations are not pure comments as they can change the way a program is treated
by the compiler. See below code for example.
Page 30 of 102
Object Oriented Programming using JAVA 24CSK42
Java includes several built-in annotations. Here are some of the most commonly used:
Annotation Description
@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.
class Animal {
void makeSound() {
Page 31 of 102
Object Oriented Programming using JAVA 24CSK42
[Link]("Animal sound");
@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:
@Deprecated
@SuppressWarnings Annotation
The @SuppressWarnings annotation tells the compiler to ignore specific warnings, like
"unchecked" or "deprecation":
import [Link];
@SuppressWarnings("unchecked")
[Link]("Volvo");
[Link](cars);
Output: [Volvo]
• 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.
4. Type Annotations: Introduced in Java 8 for annotating types (variables, generics, return
types). Useful for stronger type checking and frameworks.
import [Link];
import [Link];
@Target(ElementType.TYPE_USE)
@interface TypeAnnoDemo{
// Main class
[Link](string);
abc();
Page 34 of 102
Object Oriented Programming using JAVA 24CSK42
return 0;
Output
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Retention([Link])
@Repeatable([Link])
@interface Words
{
Page 35 of 102
Object Oriented Programming using JAVA 24CSK42
@Retention([Link])
@interface MyRepeatedAnnos
Words[] value();
try {
Class<?> c = [Link]();
Method m = [Link]("newMethod");
Annotation anno
Page 36 of 102
Object Oriented Programming using JAVA 24CSK42
= [Link]([Link]);
[Link](anno);
catch (NoSuchMethodException e) {
[Link](e);
Output:
@MyRepeatedAnnos({@Words(value=1,word="First"),@Words(value=2,
word="Second")})
From [Link]
1. @Documented
2. @Target
Specifies where the annotation can be applied (class, method, field, etc.).
3. @Inherited
Syntax
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.
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 Expirydate();
@TestAnnotation(Developer="Rahul", Expirydate="01-10-2020")
void fun1()
@TestAnnotation(Developer="Anil", Expirydate="01-10-2021")
void fun2()
[Link]("Hello");
Page 39 of 102
Object Oriented Programming using JAVA 24CSK42
Output: Hello
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
[Link]("Hello");
[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
[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
static{
Output
Page 41 of 102
Object Oriented Programming using JAVA 24CSK42
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 {
class InnerClass {
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.
class InnerClass {
void display() {
Page 42 of 102
Object Oriented Programming using JAVA 24CSK42
[Link]();
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.
class Outer {
void test() {
[Link]();
class Inner {
void display() {
Page 43 of 102
Object Oriented Programming using JAVA 24CSK42
class InnerClassDemo {
[Link]();
Output:
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
class Outer {
Page 44 of 102
Object Oriented Programming using JAVA 24CSK42
void test() {
class Inner {
void display() {
[Link]();
class InnerClassDemo {
[Link]();
Output:
Page 45 of 102
Object Oriented Programming using JAVA 24CSK42
While nested classes are not applicable to all situations, they are particularly helpful when
handling events.
• 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.
Page 46 of 102
Object Oriented Programming using JAVA 24CSK42
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.
class Outer {
class Inner {
void display() {
class Main {
Page 47 of 102
Object Oriented Programming using JAVA 24CSK42
[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() {
[Link]("Inside outerMethod");
class Inner {
void innerMethod() {
[Link]();
Page 48 of 102
Object Oriented Programming using JAVA 24CSK42
class Main {
[Link]();
Output:
Inside outerMethod
x = 98
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 {
void display() {
}
Page 49 of 102
Object Oriented Programming using JAVA 24CSK42
class Main {
[Link]();
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:
Syntax:
[Link]("Method implementation");
Page 50 of 102
Object Oriented Programming using JAVA 24CSK42
import [Link].*;
Subject() {
[Link]("Learning Subject");
void Learn(){
void syllabus(){
class GFG {
[Link]();
[Link]();
Page 51 of 102
Object Oriented Programming using JAVA 24CSK42
Output: avinash
21
222.2
String color;
[Link] = color;
int radius;
super(color);
[Link] = radius;
double area() {
Page 52 of 102
Object Oriented Programming using JAVA 24CSK42
[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( )
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
Page 53 of 102
Object Oriented Programming using JAVA 24CSK42
Rectangle(double a, double b) {
super(a, b);
double area() {
Triangle(double a, double b) {
super(a, b);
double area() {
class AbstractAreas {
Page 54 of 102
Object Oriented Programming using JAVA 24CSK42
figref = r;
figref = t;
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.
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.
1. Variable
Page 55 of 102
Object Oriented Programming using JAVA 24CSK42
2. Method
3. Class
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 {
class B extends A {
[Link]("Illegal!");
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
[Link]("print in superclass.");
[Link]("print in subclass.");
[Link]();
[Link]();
Output:
print in superclass.
print in superclass.
Page 57 of 102
Object Oriented Programming using JAVA 24CSK42
void print() {
[Link]("print in superclass."); }
@Override
void print() {
[Link]("print in subclass.");
[Link]();
[Link]();
Output:
print in superclass.
print in subclass.
Page 58 of 102
Object Oriented Programming using JAVA 24CSK42
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.
final class A {
//...
//...
Page 59 of 102
Object Oriented Programming using JAVA 24CSK42
class Student{
@Override
Page 60 of 102
Object Oriented Programming using JAVA 24CSK42
[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
[Link]([Link]());
Page 61 of 102
Object Oriented Programming using JAVA 24CSK42
Output
3131
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
return [Link]([Link]);
[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.
Class c = [Link]();
Output
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.
[Link]([Link]());
t = null;
Page 63 of 102
Object Oriented Programming using JAVA 24CSK42
[Link]();
[Link]("end");
Output
1510467688
end
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.
int id = 1;
@Override
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].*;
this.t = t;
this.a = a;
this.y = y;
Page 65 of 102
Object Oriented Programming using JAVA 24CSK42
return false;
res = 31 * res + y;
return res;
Page 66 of 102
Object Oriented Programming using JAVA 24CSK42
try {
return (Book)[Link]();
catch (CloneNotSupportedException e) {
Page 67 of 102
Object Oriented Programming using JAVA 24CSK42
[Link](b1);
Book b2 = [Link]();
[Link](b2);
b1 = null;
[Link]();
Output
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
• 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 {
void display();
Page 69 of 102
Object Oriented Programming using JAVA 24CSK42
[Link]("Geek");
class Geeks{
[Link]();
[Link](t.a);
Output
Geek
10
Note:
Static methods are accessed using the interface name, not via objects.
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
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 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 {
Page 71 of 102
Object Oriented Programming using JAVA 24CSK42
int speed;
int gear;
// Change gear
@Override
gear = newGear;
// Increase speed
@Override
// Decrease speed
@Override
Page 72 of 102
Object Oriented Programming using JAVA 24CSK42
class Main
// Instance of Bicycle(Object)
[Link](2);
[Link](3);
[Link](1);
[Link]();
[Link](1);
[Link](4);
[Link](3);
[Link]();
Output
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
import [Link].*;
// Add interface
interface Add{
// Sub interface
interface Sub{
return a+b;
Page 74 of 102
Object Oriented Programming using JAVA 24CSK42
return a-b;
class GFG{
// Main Method
Output
Addition : 3
Substraction : 1
There are certain features added to Interfaces in JDK 8 update mentioned below:
1. Default Methods
Useful for adding new methods to interfaces without breaking existing implementations.
interface TestInterface
Page 75 of 102
Object Oriented Programming using JAVA 24CSK42
[Link]("hello");
// Driver Code
[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
Page 76 of 102
Object Oriented Programming using JAVA 24CSK42
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 {
[Link]("Engine started.");
startEngine();
// Car class implements Vehicle interface and inherits the default method 'drive'
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.
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();
interface B extends A {
void method3();
[Link]("Method 1");
Page 78 of 102
Object Oriented Programming using JAVA 24CSK42
{ [Link]("Method 2");
{ [Link]("Method 3");
x.method1();
x.method2();
x.method3();
Output
Method 1
Method 2
Method 3
Page 79 of 102
Object Oriented Programming using JAVA 24CSK42
Although Class and Interface seem the same there are certain differences between Classes and
Interface
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
• 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.
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 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:
import [Link];
Page 82 of 102
Object Oriented Programming using JAVA 24CSK42
class Main {
[Link]("Enter 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:
• [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.
import [Link];
Page 84 of 102
Object Oriented Programming using JAVA 24CSK42
import [Link];
}}
}}
import [Link];
Page 85 of 102
Object Oriented Programming using JAVA 24CSK42
import [Link];
import [Link];
try {
// Writing to file
[Link]([Link]());
[Link]();
int i;
[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.
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 ;
● First Declare The Package Name As The First Statement Of Our Program.
package FirstPackage;
class Welcome {
Page 87 of 102
Object Oriented Programming using JAVA 24CSK42
[Link](
So Inorder to generate the above-desired output first do use the commands as specified use the
following specified commands
2. This command creates a [Link] file. To place the class file in the appropriate package
directory, use:
3. This command will create a new folder called FirstPackage. To run the class, use:
Output: The Above Will Give The Final Output Of The Example Program.
package data;
// Method 1 - To show()
Page 88 of 102
Object Oriented Programming using JAVA 24CSK42
// Print message
[Link]("Hi Everyone");
// Method 2 - To show()
// 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:
3. This command will create a new folder called data containing the [Link] file.
import data.*;
Page 89 of 102
Object Oriented Programming using JAVA 24CSK42
class ncj {
[Link]();
[Link]();
2. The above command compiles [Link] and requires the [Link] file to be present in the
data package.
Hi Everyone
Hello
Page 90 of 102
Object Oriented Programming using JAVA 24CSK42
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.
Page 91 of 102
Object Oriented Programming using JAVA 24CSK42
When no access modifier is used, it is accessible only within the same package.
package pack1;
class A {
Public Access
package pack1;
public class A {
✔ Same package
✔ Different package
✔ Subclasses
✔ Non-subclasses
package pack1;
public class A {
Page 92 of 102
Object Oriented Programming using JAVA 24CSK42
package pack2;
import pack1.A;
class B extends A {
void show() {
[Link](x); // allowed
Private Access
Accessible only within the same class.
class A {
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].*;
try {
Class c = [Link](args[0]);
[Link](m[i].toString());
catch (Throwable e) {
[Link](e);
Page 94 of 102
Object Oriented Programming using JAVA 24CSK42
[Link])
public synchronized
[Link] [Link]()
public synchronized
[Link] [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.
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.
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
In the examples below, the three steps are combined to present self contained illustrations
of how to tackle specific applications using reflection.
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 {}
try {
boolean b1
= [Link](new Integer(37));
[Link](b1);
[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.
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].*;
if (p == null)
return x;
try {
Method methlist[]
= [Link]();
Page 97 of 102
Object Oriented Programming using JAVA 24CSK42
Method m = methlist[i];
[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
param #1 int
-----
name = main
Page 99 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.
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.
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
Example:
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
}
}
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);
[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.
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!
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
Example :
public class CharAtDemo{
public staic void main(String[] args){
char ch;
ch = "abc".charAt(1); //assigns the value b to ch.
[Link](ch);
}
}
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);
[Link](buf);
}
} //Output: demo
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);
}
}
}
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
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]();
Example1:
"Foobar".endsWith("bar") //true
"Foobar".startsWith("Foo") //true
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"));
}
}
Output:
Starts with 'Hello': true
Ends with '.java': true
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]();
Example:
class SortString {
static String arr[] = {
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));
}
}
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
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[]) {
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");
[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( )
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();
}
}
Output:
Enter 'stop' to quit.
Enter State:
Missouri
Capital is Jefferson City.
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:
// 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( )
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
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]());
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
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);
}
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:
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
}
}
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
• 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.
• 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)
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
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.
Method Description
}
}
Example 2: Writing Data Byte by Byte
import [Link];
import [Link];
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]");
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);
}
[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
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.
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.
In this section, we will learn about Java exceptions, its type and the difference between checked and
unchecked exceptions.
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.
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
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
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
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.
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...
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
try{
//code that may throw an exception
}
finally{
// code that is always executed irrespective of exception
}
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.
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.
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
The try block within a try block is known as nested try block in java.
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)
{
}
...
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..”);
}
}
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
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.
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).
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...
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.
throw exception;
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:
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.
Now Checked Exception can be propagated (forwarded in call stack). It provides information to the
caller of the method about the exception.
Output:
exception handled
normal flow...
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].*;
}
Thread sleep with InterruptedException:
public class CheckedExample2 {
try {
[Link]("Sleeping...");
[Link](2000);
} catch (InterruptedException e)
{ [Link]("Sleep interrupted: " + e);
}
}
} catch (IOException e) {
Object Oriented Programming using Java 24CSK42
[Link]("I/O Exception: " + e);
}
try {
String name = "Java";
• Handling them ensures the program doesn’t crash unexpectedly due to logic errors.
try {
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Null reference: " + e);
Object Oriented Programming using Java 24CSK42
}
try {
int num = [Link]("abc");
} catch (NumberFormatException e) {
}
User Defined Exceptions:
super(message);
}
}
public class UserDefined1 {
try {
throw new MyException("This is a custom exception");
} catch (MyException e) {
[Link]("Caught: " + e);
}
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.
You cannot throw multiple exceptions. You can declare a method to throw multiple
exceptions e.g.
public void method() throws IOException,
SQLException.
String line;
} catch (FileNotFoundException e) {
} finally {
} } } } }
class FinallyExample{
}catch(Exception e){[Link](e);}
finally {
}
public class FinallyDemo1 {
} catch (ArithmeticException e) {
} } }
public class FinallyDemo2 {
} } }
public class FinallyDemo3 {
} finally {
class FinalizeExample{
f1=null;
f2=null;
[Link]();
}}
}
public static void main(String[] args) {
FinalizeDemo1 obj = new FinalizeDemo1();
obj = null;
[Link]();
}
Object Oriented Programming using Java 24CSK42
}
Multiple Objects:
}
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");
}
}
obj = null;
[Link]();
}
}
Nested Try-Catch-Finally
} catch (ArithmeticException e) {
} finally {
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
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.
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.
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
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.
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.
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.
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.
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.
1. Thread()
2. Thread(String name)
Object Oriented Programming using Java 24CSK42
3. Thread(Runnable r)
4. Thread(Runnable r, String name)
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
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.
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().
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.
[Link]();
[Link](“Continuing tasks in main thread”);
}
}
[Link]("Daemon-1");
[Link]();
[Link](100);
}
Output
Daemon-1 is running as a daemon thread.
Main thread ends.
Syntax
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.
[Link]();
[Link]();
}
}
Output
Daemon thread running...
Lifecycle Keeps JVM alive until finished Terminates when all user threads finish
JVM Exit JVM waits for completion JVM exits even if running
Fig. 4.7. Thread Pool Initialization with size = 3 threads. Task Queue = 5
submit(Runnable task) Adds a task into the queue for execution by worker threads.
getQueueSize() (optional) Returns how many tasks are waiting in the queue.
Object Oriented Programming using Java 24CSK42
Method Purpose
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.
3. public static int MAX_PRIORITY: This is maximum priority of a thread. Value for
this is 10.
// Main thread
[Link]([Link]().getName());
[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());
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.
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;
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
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
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
Types of Synchronization
1. Process Synchronization
2. 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.
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
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 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
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.
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);}
}
}
}
Output:
5
10
15
20
25
100
200
300
400
500
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
[Link]();
[Link]();
}
}
Output:
1
[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:
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)
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()
Returns:
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.
Output:
N
a
m
e
• 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.
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:
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;
}
}
}
}
}
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.
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
}
}
catch(InterruptedException e){ [Link]();
}
[Link]("Total is: " + [Link]);
}
}
}
OUTPUT:
Waiting for b to
complete...
Total is: 10
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:
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
Explain the two different approaches for creating threads in java with sample
program?
Explain the concept of lock in java and describe how it is used for thread
syncrhonization?
Explain the use of wait(), notify() and notify() all methods in java
Object Oriented Programming using Java 24CSK42
Provide the complete signature of main() method in java. Explain the significance
of main() method in java.
Identify different cases where an object becomes eligible for garbage collection
Object Oriented Programming using Java 24CSK42
MODULE 5
Collection Framework
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.
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.
Page 2 of 48
Object Oriented Programming using Java 24CSK42
1. Iterator<T> iterator()
The iterator method of the Iterator interface returns the iterator that iterates over the
elements in the list.
import [Link].*;
// create list
ArrayList<String> colorsList =
new ArrayList<String>();
[Link]("Violet");
[Link]("Indigo");
[Link]("Blue");
[Link]("Green");
[Link]("Yellow");
[Link]("Orange");
[Link]("Red");
Page 3 of 48
Object Oriented Programming using Java 24CSK42
//iterate through colorsList using iterator and print each item
while([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.
Page 4 of 48
Object Oriented Programming using Java 24CSK42
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.
• 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).
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]());}
[Link](2);
}}
Output:
using iterator
abc
steve
cde
Page 7 of 48
Object Oriented Programming using Java 24CSK42
fgh
ijk
lmn
pqr
** 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.
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];
[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]();
Page 9 of 48
Object Oriented Programming using Java 24CSK42
int size = [Link]();
[Link]("Size of linked list = " + size);
[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]
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(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.
[Link](20);
[Link](30);
[Link](10.4);
[Link](34);
[Link]("ff");
[Link](v);
Vector vCone = new Vector();
vClone = (Vector) [Link]();//clones a vector object
[Link](vClone);
[Link](v);}}
Page 11 of 48
Object Oriented Programming using Java 24CSK42
Output:
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];
}
[Link]("the elements of stack are:");
Iterator<Integer> itr= [Link]();
while([Link]()){
[Link]([Link]()); }
[Link]("element removed is” +
}
}
Output:
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.
● 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.
Page 14 of 48
Object Oriented Programming using Java 24CSK42
Method Description
boolean It is used to insert the specified element into this queue and
add(object) return true upon success.
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,
Output
the elements of queue are:
10
20
30
peek10
element10
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.
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]([Link]());
}
}
}
OUTPUT
head:Amit Sharma
head:Amit Sharma
Raj JaiShankar
Vijay 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
Page 19 of 48
Object Oriented Programming using Java 24CSK42
Example program:
package labpgms_Second;
import [Link];
import [Link];
import [Link];
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]
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);
[Link]("andra");
[Link]("zzz");
[Link]("ccc");
[Link]("tree_set is"+t);
Page 21 of 48
Object Oriented Programming using Java 24CSK42
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.
LinkedHashSet
[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
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.
Page 26 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
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.
Page 27 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
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;
[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
[Link](key));
}
}}
Page 30 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
}
}
}
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);
Output:
Page 31 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
[Link]("Friends");
[Link]("Dear");
[Link]("Is");
[Link]("Superb");
OUTPUT:
Page 32 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
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;
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);
[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]
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.
● 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
[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
return true;
}
if (obj == null || getClass() != [Link]()) {
return false;
}
BankAccount otherAccount = (BankAccount) obj;
return [Link](accountNumber,
[Link])
&& [Link](accountHolderName,
[Link])
Page 37 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
2022);
true
} }
Output
true
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 {
long temp;
result = [Link]();
result = 31 * result + [Link]();
temp = [Link](balance);
Page 38 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
[Link]([Link](account2)); // true
[Link]([Link]());//-813975577
[Link]([Link]());//-813975577
}
}
Page 39 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
Type Wrappers:
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.
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.
Page 40 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
[Link]([Link](account2)); // returns
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
}
}
1. Autoboxing
2. Constructor
3. Static method
class WrapperUsingConstructor {
public static void main(String[] args) {
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');
}
}
class WrapperToPrimitive {
public static void main(String[] args) {
Boolean bool2 = [Link]("true");
Page 43 of 48
OBJECT ORIENTED PROGRAMMING USING JAVA 24CSK42
char ch = [Link]();
byte b = [Link]();
short s = [Link]();
int i = [Link]();
long l = [Link]();
float f = [Link]();
double d = [Link]();
}
}
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
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
8. Explain how to sort objects based on custom criteria in java with an example
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.
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