0% found this document useful (0 votes)
12 views71 pages

Java Classes and Objects Explained

Unit III covers the concepts of classes, objects, and inheritance in Java. It explains the structure and properties of Java classes, the creation and manipulation of objects, and the principles of inheritance, emphasizing code reusability and method overriding. Additionally, it discusses method overloading and the differences between static and non-static nested classes.

Uploaded by

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

Java Classes and Objects Explained

Unit III covers the concepts of classes, objects, and inheritance in Java. It explains the structure and properties of Java classes, the creation and manipulation of objects, and the principles of inheritance, emphasizing code reusability and method overriding. Additionally, it discusses method overloading and the differences between static and non-static nested classes.

Uploaded by

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

Unit III CLASS, ARRAYS AND INHERITANCE

Classes, Objects and Methods

What are Java Classes?

A class is a blueprint from which individual objects are created (or, we can say a class is a data type of an object type).
In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.

For example, if you want to create a class for students. In that case, "Student" will be a class, and student records
(like student1, student2, etc) will be objects.

Properties of Java Classes

 A class does not take any byte of memory.

 A class is just like a real-world entity, but it is not a real-world entity. It's a blueprint where we specify the
functionalities.

 A class contains mainly two things: Methods and Data Members.

 A class can also be a nested class.

 Classes follow all of the rules of OOPs such as inheritance, encapsulation, abstraction, etc.

Types of Class Variables

A class can contain any of the following variable types.

 Local variables − Variables defined inside methods, constructors or blocks are called local variables. The
variable will be declared and initialized within the method and the variable will be destroyed when the method
has completed.

 Instance variables − Instance variables are variables within a class but outside any method. These variables are
initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor
or blocks of that particular class.

 Class variables − Class variables are variables declared within a class, outside any method, with the static
keyword.

CREATING (DECLARING) A JAVA CLASS

 To create (declare) a class, you need to use access modifiers followed by class keyword and class_name.

Syntax to create a Java class

 Use the below syntax to create (declare) class in Java:


Example of a Java Class

In this example, we are creating a class "Dog". Where, the class attributes are breed, age, and color. The class methods
are setBreed(), setAge(), setColor(), and printDetails().

class Dog {

// Declaring and initializing the attributes

String breed;

int age;

String color;

// methods to set breed, age, and color of the dog

public void setBreed(String breed) {

[Link] = breed;

public void setAge(int age) {

[Link] = age;

public void setColor(String color) {

[Link] = color;

public void printDetails() {

[Link]("Dog detials:");

[Link]([Link]);

[Link]([Link]);

[Link]([Link]);

What are Java Objects?


An object is a variable of the type class, it is a basic component of an object-oriented programming system. A class has
the methods and data members (attributes), these methods and data members are accessed through an object. Thus, an
object is an instance of a class.

If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a
state and a behavior.

If we consider a dog, then its state is - name, breed, and color, and the behavior is - barking, wagging the tail, and
running.

If you compare the software object with a real-world object, they have very similar characteristics. Software objects
also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods. So, in
software development, methods operate on the internal state of an object, and the object-to-object communication is
done via methods.

Creating (Declaring) a Java Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In
Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object type.

 Instantiation − The 'new' keyword is used to create the object.

 Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Syntax to Create a Java Object

Consider the below syntax to create an object of the class in Java:

Class_name object_name = new Class_name([parameters]);

Note: parameters are optional and can be used while you're using constructors in the class.

Example to Create a Java Object

In this example, we are creating an object named obj of Dog class and accessing its methods.

// Creating a Java class class Dog {

// Declaring and initializing the attributes

String breed; int age;

String color;
// methods to set breed, age, and color of the dog

public void setBreed(String breed) {

[Link] = breed;

public void setAge(int age) {

[Link] = age;

public void setColor(String color) {

[Link] = color;

// method to print all three values

public void printDetails() {

[Link]("Dog detials:");

[Link]([Link]);

[Link]([Link]);

[Link]([Link]);

public class Main {

public static void main(String[] args) {

// Creating an object of the class

Dog Dog obj = new Dog();

// setting the attributes [Link]("Golden Retriever");

[Link](2);

[Link]("Golden");

// Printing values [Link]();

}
}

Output

Dog detials:

Golden Retriever

Golden

Rules for using the Classes and Objects Concepts

Let's now look into the source file declaration rules (to use the Java classes & objects approach). These rules are
essential when declaring classes, import statements, and package statements in a source file.

 There can be only one public class per source file.

 A source file can have multiple non-public classes.

 The public class name should be the name of the source file as well which should be appended by .java at the
end. For example − the class name is public class Employee{} then the source file should be as [Link].

 If the class is defined inside a package, then the package statement should be the first statement in the source
file.

 If import statements are present, then they must be written between the package statement and the class
declaration. If there are no package statements, then the import statement should be the first line in the source
file.

 Import and package statements will imply to all the classes present in the source file. It is not possible to declare
different import and/or package statements to different classes in the source file.

Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be
explaining about all these in the access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and
Anonymous classes.

Examples on Java Classes and Objects

Example 1

The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly
defined constructor, which takes a parameter.

CLASS OVERVIEW

public class Employee {


 The class is named Employee.
 It can be used to create employee objects that store and display employee details.

INSTANCE VARIABLES (FIELDS)

String name;

int age;

String designation;

double salary;

These are instance variables — each Employee object will have its own copy of these:

 name: stores the employee's name


 age: stores the employee's age
 designation: stores the job title or role
 salary: stores the employee's salary

CONSTRUCTOR

public Employee(String name) {

[Link] = name;

 The constructor initializes the name of the employee when a new object is created.

 Example:

Employee e1 = new Employee("John");

Setter Methods

These methods assign values to other instance variables:

public void empAge(int empAge) {

age = empAge;

public void empDesignation(String empDesig) {

designation = empDesig;

}
public void empSalary(double empSalary) {

salary = empSalary;

They work like setters, allowing you to set values for age, designation, and salary after the object is created.

� Display Method

public void printEmployee() {

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

[Link]("Age:" + age);

[Link]("Designation:" + designation);

[Link]("Salary:" + salary);

Prints all the details of an employee.

� Example Usage

You’d usually create another class (say, [Link]) to create and use Employee objects:

public class EmployeeTest {

public static void main(String[] args) {

Employee e1 = new Employee("John");

[Link](30);

[Link]("Software Developer");

[Link](60000);

[Link]();

Output:
Name:John

Age:30

Designation:Software Developer

Salary:60000.0

METHOD OVERLOADING IN JAVA

In Java, Method Overloading allows a class to have multiple methods with the same name but different parameters,
enabling compile-time (static) polymorphism.

 Methods can share the same name if their parameter lists differ.

 Cannot overload by return type alone; parameters must differ.

 The compiler chooses the most specific match when multiple methods could apply.

The different ways of method overloading in Java are mentioned below:

1. Changing the Number of Parameters

Method overloading can be achieved by changing the number of parameters while passing to different methods.

import [Link].*;

class Product{

// Multiplying two integer values

public int multiply(int a, int b){

int prod = a * b;

return prod;

// Multiplying three integer values

public int multiply(int a, int b, int c){


int prod = a * b * c;

return prod;

class Geeks{

public static void main(String[] args)

Product ob = new Product();

// Calling method to Multiply 2 numbers

int prod1 = [Link](1, 2);

// Printing Product of 2 numbers

[Link](

"Product of the two integer value: " + prod1);

// Calling method to multiply 3 numbers

int prod2 = [Link](1, 2, 3);

// Printing product of 3 numbers

[Link](

"Product of the three integer value: " + prod2);

Output

Product of the two integer value: 2

Product of the three integer value: 6

Explanation:

 Two methods have the same name but different number of parameters.

 Compiler selects the correct method based on how many arguments are passed.
2. Changing Data Types of Parameters

In many cases, methods can be considered overloaded if they have the same name but have different parameter types,
methods are considered to be overloaded.

class Product{

public int prod(int a, int b, int c){

return a * b * c;

public double prod(double a, double b, double c){

return a * b * c;

public class Geeks {

public static void main(String[] args){

Product p = new Product();

[Link]([Link](1, 2, 3));

[Link]([Link](1.0, 2.0, 3.0));

Output

6.0

Explanation:

 Methods differ in parameter types (int vs double).

 Compiler matches the method based on the exact data type of arguments.
3. Changing the Order of Parameters

Method overloading can also be implemented by rearranging the parameters of two or more overloaded methods.

class Student {

public void studentId(String name, int rollNo){

[Link]("Name: " + name

+ ", Roll-No: " + rollNo);

public void studentId(int rollNo, String name){

[Link]("Roll-No: " + rollNo

+ ", Name: " + name);

public class Geeks{

public static void main(String[] args){

Student s = new Student();

[Link]("Sweta", 1);

[Link](2, "Gudly");

Output

Name: Sweta, Roll-No: 1

Roll-No: 2, Name: Gudly

STATIC CLASS IN JAVA


Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which
most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance
Variables, Static Methods, Static Block, and Static Classes. The class in which the nested class is defined is known as
the Outer Class. Unlike top-level classes, Nested classes can be Static. Non-static nested classes are also known
as Inner classes.

An instance of an inner class cannot be created without an instance of the outer class. Therefore, an inner class instance
can access all of the members of its outer class, without using a reference to the outer class instance. For this reason,
inner classes can help make programs simple and concise.

Remember: In static class, we can easily create objects.

Differences between Static and Non-static Nested Classes

The following are major differences between static nested classes and inner classes.

1. A static nested class may be instantiated without instantiating its outer class.

2. Inner classes can access both static and non-static members of the outer class. A static class can access only the
static members of the outer class.

Example of Static and Non-static Nested Classes


Below is the implementation of topic mentioned above:

// Java program to Demonstrate How to

// Implement Static and Non-static Classes

// Class 1

// Helper class

class OuterClass {

// Input string

private static String msg = "Static and Non Static Class";

// Static nested class

public static class NestedStaticClass {

// Only static members of Outer class


// is directly accessible in nested

// static class

public void printMessage()

// Try making 'message' a non-static

// variable, there will be compiler error

[Link](

"Message from nested static class: " + msg);

// Non-static nested class -

// also called Inner class

public class InnerClass {

// Both static and non-static members

// of Outer class are accessible in

/ this Inner class

public void display()

// Print statement whenever this method is

// called
[Link](

"Message from non-static nested class: "

+ msg);

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String args[])

// Creating instance of nested Static class

// inside main() method

[Link] printer

= new [Link]();

// Calling non-static method of nested

// static class

[Link]();

// Note: In order to create instance of Inner class


// we need an Outer class instance

// Creating Outer class instance for creating

// non-static nested class

OuterClass outer = new OuterClass();

[Link] inner

= [Link] InnerClass();

// Calling non-static method of Inner class

[Link]();

// We can also combine above steps in one

// step to create instance of Inner class

[Link] innerObject

= new OuterClass().new InnerClass();

// Similarly calling inner class defined method

[Link]();

Output

Message from nested static class: Static and Non Static Class

Message from non-static nested class: Static and Non Static Class

Message from non-static nested class: Static and Non Static Class
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It
is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

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

o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.

o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

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

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or
subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between
the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){ Programmer p=new Programmer();

[Link]("Programmer salary is:"+[Link]); [Link]("Bonus of Programmer is:"+[Link]);

}
}

Programmer salary is:40000.0


Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about
interfaces later.

When one class inherits multiple classes, it is known as multiple inheritance. For Example
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.

File: [Link]

class Animal{

void eat(){[Link]("eating...");}

class Dog extends Animal{

void bark(){[Link]("barking...");}

class TestInheritance{

public static void main(String args[]){ Dog d=new Dog();

[Link]();

[Link]();

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below,
BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
File: [Link]

class Animal{

void eat(){[Link]("eating...");}

class Dog extends Animal{

void bark(){[Link]("barking...");}

class BabyDog extends Dog{

void weep(){[Link]("weeping...");}

class TestInheritance2{

public static void main(String args[]){ BabyDog d=new BabyDog();

[Link]();

[Link]();

[Link]();

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below,
Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: [Link]
class Animal{

void eat(){[Link]("eating...");}

class Dog extends Animal{

void bark(){[Link]("barking...");}

class Cat extends Animal{

void meow(){[Link]("meowing...");}

class TestInheritance3{

public static void main(String args[]){ Cat c=new Cat();

[Link]();

[Link]();

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

}}

Output:

meowing...

eating...

class C extends A,B{//suppose if it were

public static void main(String args[]){ C obj=new C();

[Link]();//Now which msg() method would be invoked?

}
Compile Time Error

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super
reference variable.

Usage of Java super Keyword

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

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

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

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

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

class Animal{

String color="white";

class Dog extends Animal{ String color="black";

void printColor(){

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

class TestSuper1{

public static void main(String args[]){ Dog d=new Dog();

[Link]();
}}

Output:

black
white

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

2) super can be used to invoke parent class method

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

class Animal{

void eat(){[Link]("eating...");}

class Dog extends Animal{

void eat(){[Link]("eating bread...");} void bark(){[Link]("barking...");} void work(){

[Link]();

bark();

class TestSuper2{

public static void main(String args[]){ Dog d=new Dog();

[Link]();

}}
Output:

eating...
barking...

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

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

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

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

class Dog extends Animal{ Dog(){

super();

[Link]("dog is created");

class TestSuper3{

public static void main(String args[]){ Dog d=new Dog();

}}

Output:

animal is created
dog is created
Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can
be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable
or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because
final variable once assigned a value can never be changed.

class Bike9{

final int speedlimit=90;//final variable

void run(){ speedlimit=400;


}

public static void main(String args[]){ Bike9 obj=new Bike9();

[Link]();

}//end of class

Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method

class Bike{

final void run(){[Link]("running");}

class Honda extends Bike{

void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){ Honda honda= new Honda(); [Link]();

Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}

class Honda1 extends Bike{

void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){ Honda1 honda= new Honda1(); [Link]();

Output:Compile Time Erro

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

class Bike{

final void run(){[Link]("running...");}

class Honda2 extends Bike{

public static void main(String args[]){

new Honda2().run();

Output:running...
Q) What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed,
it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable

class Student{

int id;

String name;

final String PAN_CARD_NUMBER;

...

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

class Bike10{

final int speedlimit;//blank final variable

Bike10(){ speedlimit=70;

[Link](speedlimit);

public static void main(String args[]){

new Bike10();

Output: 70
Overriding Methods

Definition:
When a subclass (child class) defines a method with the same name, return type, and
parameters as a method in its superclass, the subclass’s version overrides the parent class
version.

This allows runtime polymorphism (method behavior changes depending on the object
type).

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() { // Overriding method

[Link]("Dog barks");

public class Test {

public static void main(String[] args) {

Animal a = new Dog(); // Parent reference, child object

[Link](); // Output: Dog barks

}
Final Variables, Methods, and Classes

The keyword final is used to restrict modification.

�a) Final Variable

Once assigned, its value cannot be changed.

final int MAX = 100;

// MAX = 200; � Error — cannot change value

Final Method

Cannot be overridden by a subclass.

class Vehicle {

final void start() {

[Link]("Vehicle started");

}}

class Car extends Vehicle {

// void start() { } � Error — cannot override final method

class Vehicle {

final void start() {

[Link]("Vehicle started");

class Car extends Vehicle {

// void start() { } � Error — cannot override final method

}
Final Class

Cannot be inherited by another class.

final class Shape {

void draw() {

[Link]("Drawing...");

// class Circle extends Shape { } � Error — cannot extend final class

Finalizer Methods

Definition:
The finalize() method is called by the Garbage Collector before an object is destroyed to
perform cleanup operations (like closing files or freeing resources).

class Demo {

protected void finalize() {

[Link]("Object is garbage collected");

public static void main(String[] args) {

Demo d1 = new Demo();

d1 = null;

[Link](); // Suggest JVM to run garbage collector

Abstract Methods and Classes


�Abstract Class

A class declared with the keyword abstract is incomplete and cannot be instantiated
directly.
It can have abstract methods (without body) and concrete methods (with body).

Example:

abstract class Animal {

abstract void sound(); // Abstract method (no body)

void sleep() { // Normal method

[Link]("Sleeping...");

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

public class TestAbstract {

public static void main(String[] args) {

Animal a = new Dog();

[Link]();

[Link]();

}}
Visibility Control in Java

Definition:
Visibility control in Java defines how accessible a class, variable, or method is from other
classes or packages.
This is achieved using Access Modifiers.

Access Modifiers:

package demo;

public class Person {

private String name = "John"; // accessible only in this class

protected int age = 25; // accessible in subclass

public void show() {

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

Key Points:

 private: most restrictive — used for data hiding.


 public: least restrictive — used for global access.
 protected: allows access to subclasses.
 Encapsulation is implemented through visibility control.
Arrays in Java

An array is a collection of elements of the same data type, stored in contiguous memory
locations.

One-Dimensional Array

�Example:

public class OneDArray {

public static void main(String[] args) {

int[] marks = {90, 80, 70, 85, 95};

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

[Link]("Mark " + (i+1) + ": " + marks[i]);

Output:

Mark 1: 90
Mark 2: 80
Mark 3: 70
Mark 4: 85
Mark 5: 95

Two-Dimensional Array

Used to store data in rows and columns (like a matrix).

public class TwoDArray {

public static void main(String[] args) {

int[][] matrix = {
{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

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

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

[Link](matrix[i][j] + " ");

[Link]();

Output:

1 2 3
4 5 6
7 8 9

Strings in Java

A String in Java is a sequence of characters.


Strings are objects of the class [Link].

Example:

public class StringExample {

public static void main(String[] args) {

String s1 = "Hello";
String s2 = new String("World");

[Link](s1 + " " + s2);

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

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

[Link]("Character at index 1: " + [Link](1));

Common String Methods:

Method Description
length() Returns string length
charAt(index) Returns character at position
toUpperCase() / toLowerCase() Converts case
concat() Joins two strings
equals() / equalsIgnoreCase() Compares strings

Vectors in Java

A Vector is a dynamic array — it can grow or shrink in size at runtime.


It belongs to [Link] package.

Example:

import [Link].*;

public class VectorExample {

public static void main(String[] args) {

Vector<String> v = new Vector<>();


[Link]("Apple");

[Link]("Banana");

[Link]("Cherry");

[Link]("Vector elements: " + v);

[Link]("Banana");

[Link]("After removal: " + v);

[Link]("First element: " + [Link]());

Output:

Vector elements: [Apple, Banana, Cherry]


After removal: [Apple, Cherry]
First element: Apple

Interfaces in Java

Definition:
An interface is a collection of abstract methods (and constants).
It defines what a class must do, but not how it does it.

It is a contract between the class and the outside world.

Example:

interface Animal {

void sound(); // abstract method


void eat();

class Dog implements Animal {

public void sound() {

[Link]("Dog barks");

public void eat() {

[Link]("Dog eats food");

public class InterfaceDemo {

public static void main(String[] args) {

Animal a = new Dog();

[Link]();

[Link]();

Output:

Dog barks
Dog eats food

Defining Interfaces in Java


Definition:
An interface in Java is a fully abstract class that contains only abstract methods (until Java
7) and static/default methods (from Java 8 onwards).
It defines what a class must do, but not how.

interface InterfaceName {

// constant variables

// abstract methods

Example:

interface Animal {

void eat(); // abstract method

void sound(); // abstract method

Key Points:

 Methods in an interface are public and abstract by default.


 Variables in an interface are public, static, and final by default.
 An interface cannot have constructors.
 Cannot be instantiated directly.

Extending Interfaces

Just like classes, one interface can inherit another using the keyword extends.
This allows you to create hierarchies of interfaces.

Example:

interface Animal {

void eat();

}
interface Pet extends Animal {

void play();

class Dog implements Pet {

public void eat() {

[Link]("Dog eats food");

public void play() {

[Link]("Dog loves to play");

public class ExtendInterface {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();

[Link]();

Output:

Dog eats food


Dog loves to play
Key Points:

 You can extend multiple interfaces:

interface A { void show(); }

interface B { void display(); }

interface C extends A, B { void print(); }

A class implementing C must provide implementations for all methods from A, B, and C.

Implementing Interfaces

A class implements an interface using the keyword implements.


It must provide definitions for all abstract methods declared in the interface.

Example:

interface Vehicle {

void start();

void stop();

class Car implements Vehicle {

public void start() {

[Link]("Car started");

public void stop() {

[Link]("Car stopped");

}
public class ImplementInterface {

public static void main(String[] args) {

Vehicle v = new Car(); // Interface reference

[Link]();

[Link]();

Output:

Car started
Car stopped

Key Points:

 A class can implement multiple interfaces:


 class A implements Interface1, Interface2 { ... }
 The class must override all methods from all interfaces it implements.

Accessing Interface Variables

All variables declared in an interface are automatically:

 public
 static
 final

Hence, they can be accessed without creating an object, using the interface name.

Example:

interface Constants {

int MAX = 100; // public, static, final by default

int MIN = 1;
}

public class InterfaceVariable {

public static void main(String[] args) {

[Link]("Maximum value: " + [Link]);

[Link]("Minimum value: " + [Link]);

Output:

Maximum value: 100


Minimum value: 1

Concept Keyword Description Example


interface A { void
Defining Interface interface Declares abstract methods show(); }

extends
One interface inherits interface B extends
Extending Interface A {}
another
Implementing implements
Class provides body for class C implements A
Interface interface methods {}
Accessing Interface Accessed using interface
— [Link]
Variables name
Unit IV PACKAGES, THREADS AND EXCEPTIONS

Packages in Java

1. Introduction

A package in Java is a namespace that organizes a set of related classes and interfaces.
Packages help to:

 Avoid naming conflicts

 Provide access protection

 Make searching, locating, and usage of classes easier

Think of a package as a folder in your computer that contains related files.

Types of Packages

1. Built-in Packages (System Packages):


These are predefined packages provided by Java.
Examples:

[Link] // Contains fundamental classes (String, Math, etc.)

[Link] // Utility classes (Collections, Date, Scanner)

[Link] // Input/output classes

[Link] // Networking classes

[Link] // Database connectivity (JDBC)

User-defined Packages:
These are packages created by the programmer to group related classes.

Using System Packages

To use a class from a built-in package, we use the import statement.

Example:

import [Link];
class Example {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter your name: ");

String name = [Link]();

[Link]("Hello, " + name);

Here, [Link] is a system package and Scanner is a class inside it.

Naming Conventions for Packages

 Package names are written in lowercase.


 To ensure uniqueness, package names often start with a company’s domain name in
reverse.

Examples:

 [Link]
 [Link]
 [Link]

For user projects:

package [Link];

Creating a Package

You create a package using the package keyword at the top of your Java file.

Example:

package mypackage;
public class A {

public void display() {

[Link]("Hello from package mypackage!");

Save this file as:


�mypackage/[Link]

Then compile:

javac -d . [Link]

The -d . flag tells the compiler to create the folder structure for the package.

Accessing a Package

To use the class A from the package mypackage in another program:

import mypackage.A;

class B {

public static void main(String[] args) {

A obj = new A();

[Link]();

Using a Package

There are three ways to use a class from a package:

1. Import entire package:


import mypackage.*;

Import specific class:

import mypackage.A;

Use fully qualified name (without import):

class Test {

public static void main(String[] args) {

mypackage.A obj = new mypackage.A();

[Link]();

Adding a Class to an Existing Package

To add another class to the same package, simply include the same package statement.

Example:

package mypackage;

public class B {

public void show() {

[Link]("This is class B in package mypackage");

Now both A and B belong to the mypackage.

You can use both like this:

import mypackage.*;
class Test {

public static void main(String[] args) {

A obj1 = new A();

B obj2 = new B();

[Link]();

[Link]();

Advantages of Packages

 Avoids name conflicts.


 Provides access control.
 Makes code modular and organized.
 Easier maintenance and reuse.

Concept Keyword / Example


Declare a package package mypackage;
Import a package import mypackage.*;
Compile a package javac -d . [Link]
Access a class mypackage.A obj = new mypackage.A();
Naming convention lowercase, reverse domain name

Multithreaded Programming in Java


1. Introduction

 Multithreading in Java allows a program to execute multiple parts (threads)


simultaneously.
 A thread is the smallest unit of execution within a process.
 It improves performance by performing multiple tasks concurrently (e.g., playing
music while downloading a file).

Creating Threads
In Java, there are two main ways to create threads:

Method 1: By Extending the Thread Class


class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");

public static void main(String[] args) {

MyThread t = new MyThread(); // create object

[Link](); // start the thread

Note:

 The run() method defines the code executed by the thread.


 The start() method actually starts the new thread and calls run() internally.

Steps Involved in Thread Creation and Execution

Step 1: Define a Thread

You can define a thread in two ways:

1. By extending the Thread class


2. By implementing the Runnable interface

Step 2: Write the run() Method

 The run() method contains the code that represents the task to be performed by the
thread.

public void run() {

// Code to be executed by the thread


}

Step 3: Create a Thread Object

 After defining the class, create an object of the thread class.

If extending Thread:

MyThread t1 = new MyThread();

If implementing Runnable:

MyRunnable r1 = new MyRunnable();

Thread t1 = new Thread(r1);

Step 4: Start the Thread

 Use the start() method to begin execution.


 [Link]();
 This automatically calls the run() method in a new thread of execution.

Step 5: Thread Execution

 The thread enters the Runnable state and the JVM schedules it for execution.
 The run() method executes independently of other threads.

Step 6: Thread Lifecycle Management

 Threads pass through the following states:


1. New
2. Runnable
3. Running
4. Blocked/Waiting
5. Terminated

Step 7: End of Thread

 Once the run() method finishes, the thread terminates automatically.

Example
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread(); // Step 3
[Link](); // Step 4
}
}

Method 2: By Implementing the Runnable Interface


class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running using Runnable...");
}

public static void main(String[] args) {


MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
[Link]();
}
}

This approach is preferred when you need to extend another class, since Java doesn’t
support multiple inheritance.

Life Cycle of a Thread in Java

1. Introduction
In Java, a thread is a lightweight process that allows a program to perform multiple tasks
simultaneously.
Each thread goes through a life cycle — from its creation to its termination.
Java provides various methods in the Thread class to control and manage this life cycle.

2. Definition
The life cycle of a thread refers to the different states that a thread passes through during its
execution — from born (new) to dead (terminated).

Each thread in Java is represented by an object of the Thread class, which belongs to the
[Link] package.

3. Thread States in Java


According to the Java Thread model, a thread can exist in the following five main states:

State Description

1. New (Born State) Thread is created but not yet started.

2. Runnable (Ready to run) Thread is ready to run and waiting for CPU time.

3. Running Thread is currently executing its run() method.

4. Blocked / Waiting / Sleeping Thread is temporarily inactive (waiting for resource or sleep).

5. Terminated (Dead State) Thread has completed execution or stopped due to an error.

4. Diagram: Life Cycle of a Thread


+----------------+
| New |
| (Born State) |
+----------------+
|
| start()

+----------------+
| Runnable |
| (Ready to run) |
+----------------+
|
| Scheduler picks thread

+----------------+
| Running |
+----------------+
/ | \
/ | \
sleep(), wait() | run() completes
↓ | ↓
+----------------+ | +----------------+
|Blocked/Waiting | | | Terminated |
|(Not Runnable) | | | (Dead State) |
+----------------+ | +----------------+

notify()/resume()

5. Explanation of Each State


1. New (Born State)

 Thread is created using:


 Thread t = new Thread();
 It exists but hasn’t started executing.
 Moves to Runnable when start() is called.

2. Runnable (Ready to Run State)

 Thread is ready and waiting for the CPU scheduler to assign execution time.
 Created by calling:
 [Link]();
 May enter the Running state when selected by the scheduler.

3. Running State

 The thread’s run() method is being executed.


 It performs its assigned task.
 The scheduler determines which thread runs at a given time.

4. Blocked / Waiting / Sleeping State

 A thread is temporarily inactive due to:


o Waiting for I/O completion.
o Calling sleep() method.
o Waiting for another thread (wait()).
 It will return to Runnable when the condition is met or the waiting time ends.

5. Terminated (Dead State)

 A thread enters this state when:


o Its run() method completes.
o It is stopped using stop() (deprecated).
 The thread object cannot be restarted once terminated.

6. Example Program
class ThreadLifeCycle extends Thread {
public void run() {
[Link]("Thread is running...");
try {
[Link](1000); // moves to sleeping state
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread is finished.");
}

public static void main(String args[]) {


ThreadLifeCycle t1 = new ThreadLifeCycle(); // New State
[Link]("Thread state after creation: " +
[Link]());

[Link](); // Runnable State


[Link]("Thread state after start(): " + [Link]());

try {
[Link](500); // main thread sleeps
[Link]("Thread state while running: " +
[Link]());

[Link](); // waiting for t1 to finish


[Link]("Thread state after completion: " +
[Link]());
} catch (InterruptedException e) {
[Link](e);
}
}
}

Sample Output:

Thread state after creation: NEW


Thread state after start(): RUNNABLE
Thread is running...
Thread state while running: TIMED_WAITING
Thread is finished.
Thread state after completion: TERMINATED

Important Thread Control Methods


Method Description

start() Starts a thread and calls run() method.

run() Defines code that runs in the thread.

sleep(ms) Temporarily stops the thread for given milliseconds.

join() Waits for a thread to finish execution.

yield() Gives CPU time to other threads of same priority.

isAlive() Returns true if the thread is still running.


Advantages of Multithreading
1. Efficient CPU utilization
2. Faster execution of multiple tasks
3. Improved performance and responsiveness
4. Better resource sharing
5. Parallel processing capability

Summary Points:

 Java threads pass through New → Runnable → Running → Waiting →


Terminated states.
 Controlled using methods like start(), sleep(), join(), yield().
 Managed by Thread Scheduler of the JVM.
 Thread life cycle ensures smooth multitasking and efficient execution.

5. Synchronization in Java

 When multiple threads access shared data, data inconsistency may occur.
 Synchronization ensures that only one thread accesses the shared resource at a time.

Using the synchronized keyword:


class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
[Link](n * i);
try { [Link](400); } catch (Exception e) {}
}
}
}

class MyThread1 extends Thread {


Table t;
MyThread1(Table t) { this.t = t; }
public void run() { [Link](5); }
}

class MyThread2 extends Thread {


Table t;
MyThread2(Table t) { this.t = t; }
public void run() { [Link](100); }
}

class TestSynchronization {
public static void main(String args[]) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}

Both threads use the same Table object, but synchronization ensures one thread executes the
method at a time.

6. Advantages of Multithreading

 Increases CPU utilization


 Reduces idle time
 Enables parallel processing
 Improves program efficiency

7. Key Methods in Thread Class

Method Description

start() Starts the thread and calls run()

run() Contains the thread code

sleep(ms) Pauses the thread for specified milliseconds

join() Waits for another thread to finish

isAlive() Checks if thread is active

setPriority(int) Sets priority level

getName() Returns thread name

Summary Table

Concept Keyword / Example

Create Thread extends Thread or implements Runnable

Start Thread [Link]()

Synchronization synchronized keyword

Thread States New → Runnable → Running → Waiting → Terminated


Concept Keyword / Example

Priority MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY

Multithreaded Programming in Java


1. Thread Priority

 Every thread in Java has a priority that helps the thread scheduler decide the order in
which threads are executed.
 Thread priority is an integer value between 1 and 10.

Constant Description Value

Thread.MIN_PRIORITY Minimum priority 1

Thread.NORM_PRIORITY Default priority 5

Thread.MAX_PRIORITY Maximum priority 10

Setting and Getting Priority


[Link](Thread.MAX_PRIORITY);
int p = [Link]();

�Example:

class PriorityDemo extends Thread {


public void run() {
[Link](getName() + " with priority " + getPriority());
}

public static void main(String[] args) {


PriorityDemo t1 = new PriorityDemo();
PriorityDemo t2 = new PriorityDemo();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}

Note: Thread priority only suggests execution order — the final order depends on the thread
scheduler of the JVM.

2. Synchronization in Java

 When multiple threads access shared data, data inconsistency may occur.
 Synchronization ensures that only one thread can access a shared resource at a
time.

Types of Synchronization

1. Synchronized Method
2. Synchronized Block

Example (Synchronized Method):


class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
[Link](n * i);
}
}
}

class MyThread1 extends Thread {


Table t;
MyThread1(Table t) { this.t = t; }
public void run() { [Link](5); }
}

class MyThread2 extends Thread {


Table t;
MyThread2(Table t) { this.t = t; }
public void run() { [Link](100); }
}

class TestSync {
public static void main(String[] args) {
Table obj = new Table();
new MyThread1(obj).start();
new MyThread2(obj).start();
}
}

Only one thread at a time executes printTable() — avoiding interference.

Managing Errors and Exceptions in Java


1. Errors vs Exceptions

Type Meaning Example

Serious problem beyond the control of the OutOfMemoryError,


Error
program StackOverflowError

Problems that can be handled by the


Exception ArithmeticException, IOException
program
2. Exception Handling Mechanism

Handled using try–catch–finally and throw–throws keywords.

Syntax:
try {
// Code that may cause exception
} catch (ExceptionType e) {
// Handling code
} finally {
// Code that always executes
}

Example:
class ExceptionDemo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed.");
} finally {
[Link]("End of program.");
}
}
}

3. Throw and Throws

 throw – Used to explicitly throw an exception.


 throws – Declares exceptions that a method might throw.

Example:
void checkAge(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
else
[Link]("Eligible to vote");
}

Summary:

 Thread Priority → controls the execution preference of threads.


 Synchronization → prevents data inconsistency in multithreading.
 Exception Handling → ensures smooth program execution even during runtime
errors.

Exceptions in Java
1. Definition
An exception is an unwanted or unexpected event that occurs during the execution of a
program, which disrupts the normal flow of instructions.

Java uses exception handling to detect and handle these errors so that the program can
continue running smoothly.

2. Difference Between Error and Exception

Error Exception

Occurs due to serious system-level problems. Occurs due to program-level issues.

Cannot be recovered by the program. Can be handled by the program.

Example: OutOfMemoryError, Example: ArithmeticException,


StackOverflowError IOException

3. Exception Hierarchy in Java


Throwable

├── Error
│ └── (e.g., OutOfMemoryError)

└── Exception
├── Checked Exception
│ └── (e.g., IOException, SQLException)
└── Unchecked Exception (Runtime Exception)
└── (e.g., ArithmeticException, NullPointerException)

4. Types of Exceptions

a) Checked Exceptions

 Checked at compile-time.
 Must be either handled or declared using throws.
 Example: IOException, SQLException, FileNotFoundException.

b) Unchecked Exceptions

 Occur at runtime.
 Not checked at compile-time.
 Example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException.
c) User-defined Exceptions

 Custom exceptions created by programmers using extends Exception.

5. Exception Handling Keywords

Keyword Description

try Block of code that may cause an exception

catch Handles the exception

finally Executes code whether exception occurs or not

throw Used to explicitly throw an exception

throws Declares exceptions that a method can throw

6. Syntax Example
try {
int a = 10 / 0; // May cause exception
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed!");
} finally {
[Link]("Program execution completed.");
}

Output:

Division by zero not allowed!


Program execution completed.

7. Example of User-Defined Exception


class AgeException extends Exception {
AgeException(String msg) {
super(msg);
}
}

public class TestCustomException {


static void checkAge(int age) throws AgeException {
if (age < 18)
throw new AgeException("Not eligible to vote");
else
[Link]("Eligible to vote");
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (AgeException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}

8. Advantages of Exception Handling

1. Maintains normal program flow.


2. Separates error-handling code from regular logic.
3. Provides meaningful error messages.
4. Helps in debugging and maintenance.

Types of Errors and Exceptions in Java


Java programs may fail due to various errors or exceptions during compilation or execution.
They are broadly classified as follows:

1. Errors in Java
�Definition:

Errors are serious issues that occur due to system failure or resource limitations.
They are beyond the control of the programmer and usually cannot be recovered by the
program.

Types of Errors:

Type Description Example


a) Compile- Errors detected by the compiler Syntax errors, missing semicolons,
Time Errors before the program runs. undeclared variables.
b) Runtime Errors that occur while the program Dividing by zero, accessing invalid
Errors is executing. array index.
c) Logical Program runs without crashing but
Wrong formula or incorrect logic.
Errors produces incorrect results.
d) System Occur due to system crash or lack OutOfMemoryError,
Errors of resources. StackOverflowError.

Example:
int a = 10 / 0; // Runtime error (ArithmeticException)
2. Exceptions in Java
�Definition:

An exception is an event that occurs during program execution and disrupts the normal
flow of instructions.
Exceptions can be handled by the program using Java’s exception handling mechanism.

Exception Hierarchy
Throwable

├── Error → (System level, cannot be handled)
└── Exception → (Application level, can be handled)

Types of Exceptions

Type Description Examples


Checked at compile time;
a) Checked must be handled using IOException, SQLException,
Exceptions try-catch or declared FileNotFoundException
with throws.
b) Unchecked ArithmeticException,
Occur at runtime; not
Exceptions
checked at compile time. NullPointerException,
(Runtime) ArrayIndexOutOfBoundsException
Created by the
c) User-Defined InvalidAgeException,
programmer using
Exceptions LowBalanceException
extends Exception.

Example: Exception Handling


public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // may cause exception
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
} finally {
[Link]("Program ended safely.");
}
}
}

Output:

Cannot divide by zero!


Program ended safely.
Difference Between Error and Exception

Error Exception
Occurs due to serious system failure. Occurs due to faulty code or input.
Cannot be handled by the program. Can be handled using try-catch blocks.
Example: OutOfMemoryError Example: ArithmeticException

�Summary:

 Errors → Irrecoverable problems (system or environment related).


 Exceptions → Recoverable problems handled using exception handling (try, catch,
finally, throw, throws).

Syntax of Exception Handling in Java

1. Introduction
In Java, exception handling is a mechanism to detect and manage runtime errors,
allowing the program to continue execution instead of crashing abruptly.
An exception is an unwanted event that disrupts the normal flow of a program.

Java provides a robust and object-oriented way of handling exceptions using the try,
catch, finally, throw, and throws keywords.

2. Definition
Exception Handling in Java is the process of responding to exceptions that occur during
program execution by taking appropriate actions, so that the program can continue running
normally.

3. Need for Exception Handling


Without proper exception handling, the program may terminate unexpectedly.
Exception handling helps to:

 Maintain normal program flow


 Provide user-friendly error messages
 Prevent system crashes
 Allow error recovery and debugging

4. Exception Hierarchy
Throwable
/ \
Exception Error
/ \
Checked Exception Unchecked Exception (Runtime)

Types of Exceptions:

Type When Checked Examples

Checked Checked at
IOException, SQLException, FileNotFoundException
Exceptions compile-time

Unchecked Checked at ArithmeticException, NullPointerException,


Exceptions runtime ArrayIndexOutOfBoundsException

Serious issues
Errors OutOfMemoryError, StackOverflowError
beyond control

5. Exception Handling Keywords


Keyword Description

try Defines a block of code that may throw an exception.

catch Handles the exception that occurs in the try block.

finally Always executes, whether an exception occurs or not.

throw Used to explicitly throw an exception.

throws Declares exceptions that a method might throw.

6. Syntax of Exception Handling


try {
// Code that might cause an exception
}
catch (ExceptionType e) {
// Handling code
}
finally {
// Code that always executes
}

7. Example: Basic Exception Handling


class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // may cause ArithmeticException
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero not allowed!");
}
finally {
[Link]("Program execution completed.");
}
}
}

Output:

Error: Division by zero not allowed!


Program execution completed.

8. Multiple Catch Example


try {
int arr[] = new int[3];
arr[5] = 10; // may cause ArrayIndexOutOfBoundsException
}
catch (ArithmeticException e) {
[Link]("Arithmetic error occurred.");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of range!");
}
catch (Exception e) {
[Link]("General Exception: " + [Link]());
}

Output:

Array index out of range!

9. Using throw and throws


Using throw:

Used to explicitly throw an exception.

throw new ArithmeticException("Invalid division");

Using throws:

Used in method declaration to indicate possible exceptions.

void checkAge(int age) throws ArithmeticException {


if (age < 18)
throw new ArithmeticException("Not eligible to vote");
}

10. User-Defined Exception Example


class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}

public class TestCustomException {


static void checkAge(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Age below 18 not allowed");
else
[Link]("Valid age!");
}

public static void main(String[] args) {


try {
checkAge(15);
} catch (InvalidAgeException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}

Output:

Caught Exception: Age below 18 not allowed

11. Advantages of Exception Handling


1. Improves program reliability and robustness
2. Separates error-handling code from regular logic
3. Prevents abnormal termination of the program
4. Helps identify runtime problems easily
5. Supports user-defined exception creation
12. Important Rules
1. Only one catch block executes for a given exception.
2. Catch blocks must be written from specific to general.
3. finally block always executes even if an exception occurs or not.
4. You can use nested try-catch blocks for complex programs.

13. Real-Life Example


Example: Reading a file that may not exist

import [Link].*;
class FileExample {
public static void main(String args[]) {
try {
FileReader fr = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found!");
} finally {
[Link]("File operation completed.");
}
}
}

Multiple Catch Statements in Java

Introduction
In Java, exception handling is a powerful mechanism that allows a program to handle runtime
errors and maintain normal program flow.
It is done using try, catch, finally, throw, and throws keywords.

A try block contains code that might throw an exception, and one or more catch blocks can
be used to handle different types of exceptions separately.

Definition
A Multiple Catch Statement in Java refers to using more than one catch block with a
single try block.
This allows the program to handle different types of exceptions in different ways
depending on the exception type that occurs.

Syntax
try {
// Code that may cause multiple exceptions
}
catch (ExceptionType1 e1) {
// Handling code for ExceptionType1
}
catch (ExceptionType2 e2) {
// Handling code for ExceptionType2
}
catch (Exception e) {
// General exception handler
}

Explanation
 The try block encloses code that may generate one or more exceptions.
 Each catch block handles a specific exception type.
 When an exception occurs, the JVM searches for the first matching catch block
whose parameter matches the type of the thrown exception.
 Once a suitable catch block is found, the control transfers to that block.
 Only one catch block executes for a given exception.

Example Program
class MultipleCatchExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // may cause ArithmeticException

int arr[] = new int[5];


arr[10] = 50; // may cause
ArrayIndexOutOfBoundsException

String str = null;


[Link]([Link]()); // may cause
NullPointerException
}
catch (ArithmeticException e) {
[Link]("Arithmetic Error: Division by zero!");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index is out of range!");
}
catch (NullPointerException e) {
[Link]("Null value encountered!");
}
catch (Exception e) {
[Link]("General Exception: " + [Link]());
}
finally {
[Link]("End of program execution.");
}
}
}

Output:
Arithmetic Error: Division by zero!
End of program execution.

How It Works
1. When an exception occurs inside the try block, control is immediately transferred to
the first matching catch block.
2. If the first catch block does not match the exception type, Java continues checking
the next one.
3. Once a suitable catch block is found, the rest of the catch blocks are skipped.
4. After executing the appropriate catch block, the program continues with the code after
the finally block.

Rules for Multiple Catch Blocks


1. You can have any number of catch blocks for a single try block.
2. Only one catch block will execute per exception occurrence.
3. Catch blocks must be ordered from most specific to most general.
(e.g., ArithmeticException before Exception).
4. If a superclass exception (like Exception) appears before a subclass exception, the
compiler will give an error (unreachable code).
5. Since Java 7, you can handle multiple exceptions in a single catch using the pipe (|)
operator.

Example (Java 7 Feature – Multi-catch Block)


try {
int a = 10 / 0;
}
catch (ArithmeticException | NullPointerException e) {
[Link]("Either Arithmetic or Null Pointer Exception
occurred");
}

Advantages of Multiple Catch Statements


1. Improves readability and clarity – each exception type is handled separately.
2. Allows specific handling – different responses for different error types.
3. Prevents program termination – ensures smooth program flow.
4. Simplifies debugging – helps identify the exact cause of failure.
5. Enhances reliability – makes the code more robust and error-resistant.

Common Errors in Multiple Catch Blocks


 Placing a general exception (e.g., Exception) before a specific exception causes a
compilation error:
 // ❌ Wrong order
 catch (Exception e) { }
 catch (ArithmeticException e) { } // Unreachable code
 To fix:
 // ❌ Correct order
 catch (ArithmeticException e) { }
 catch (Exception e) { }

Conclusion
Multiple Catch Statements in Java make exception handling more structured, readable, and
reliable.
They allow developers to handle various exceptions separately within the same program
block, improving error control and maintaining smooth program execution.

You might also like