KEMBAR78
Java-Unit 2 | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
36 views27 pages

Java-Unit 2

Inheritance is a core concept of Object-Oriented Programming in Java that allows a subclass to inherit properties and behaviors from a superclass, promoting code reuse and hierarchical relationships. There are various types of inheritance such as single, multilevel, hierarchical, and multiple inheritance (via interfaces). Additionally, Java employs access modifiers to control member visibility and utilizes keywords like 'this' and 'super' for referencing class members and parent class methods, respectively.

Uploaded by

arul85700
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)
36 views27 pages

Java-Unit 2

Inheritance is a core concept of Object-Oriented Programming in Java that allows a subclass to inherit properties and behaviors from a superclass, promoting code reuse and hierarchical relationships. There are various types of inheritance such as single, multilevel, hierarchical, and multiple inheritance (via interfaces). Additionally, Java employs access modifiers to control member visibility and utilizes keywords like 'this' and 'super' for referencing class members and parent class methods, respectively.

Uploaded by

arul85700
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
You are on page 1/ 27

UNIT-2

Inheritance
Basic concepts:

 Inheritance is one of the four fundamental concepts of Object-Oriented Programming (OOP), along
with Encapsulation, Abstraction, and Polymorphism.
 In Java, inheritance allows a class (called a child class or subclass) to acquire the properties and
behaviors (fields and methods) of another class (called a parent class or superclass).
 It enables the reuse of existing code, which improves the modularity and maintainability of the
software system.
 Inheritance helps model hierarchical relationships between classes and represents "is-a" relationships.
For instance, a Dog is an Animal, and a Car is a Vehicle.

Why use inheritance in Java?


 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

Important Terminologies Used in Java Inheritance

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

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

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

 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
}

Types of inheritance
There are five types of inheritance available in Java programming. They are as follows:
1. Single level inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
In Java programming, multiple inheritance and hybrid inheritance are supported through the interface only.

 In java programming, multiple and hybrid inheritance is supported through interface only.
 Multiple inheritance is not supported in Java through class.

1.Single Inheritance:

Definition: A subclass inherits from only one superclass. It is the simplest form of inheritance where one class
extends another class.
Key Point: A class can only inherit from one parent class.

Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}

Output:
This animal eats food
The dog barks

2. Multilevel Inheritance:
Definition: A class is derived from another class, which is already a subclass of another class. This forms a
chain of inheritance where a class inherits from a parent class, and that parent class inherits from another class.
Key Point: Involves a series of inheritance in levels, where each level inherits from the class above it.

3. Hierarchical Inheritance:
Definition: Multiple classes inherit from a single superclass. All subclasses share the same parent class but can
have their own additional features or behaviors.
Key Point: Multiple subclasses are derived from the same parent class.

4. Multiple Inheritance (via Interfaces):


Definition: Java does not support multiple inheritance through classes, but it can be achieved using interfaces. A
class can implement more than one interface, inheriting features from multiple sources.
Key Point: A class can inherit from multiple interfaces, but not from multiple classes.

5. Hybrid Inheritance (via Interfaces):


Definition: A combination of two or more types of inheritance, typically achieved using interfaces and classes.
This allows for a more complex inheritance structure, combining features of different types.
Key Point: Uses a mix of class inheritance and interface inheritance to create a hybrid model.

Member access rules:


 Java, member access rules determine how the members (fields, methods, constructors, etc.) of a class
can be accessed from different parts of the program.

 These rules are based on the access modifiers used to declare the members.
Types of Access Modifiers in Java

There are four types of access modifiers available in Java:


1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default (Package-Private):
 No keyword required: If you don't specify any access modifier, it’s called default access.
 What it means: The member (like a variable or method) is only accessible within the same package.
Other classes outside the package cannot access it.
 Where it's used: When you want to keep things accessible only within related classes in the same
package.
 Example:
// File: Animal.java (same package)
class Animal {
int age = 5; // Default access (no keyword)

void display() {
System.out.println("Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.display(); // Can access age and display() within the same package
}
}
 Output:Age: 5

2. Private:
 What it means: A private member is only accessible within the same class. No other class can access it,
not even subclasses or classes in the same package.
 Where it's used: When you want to keep things hidden and only used inside the class, like sensitive
data.
 Example:
class Animal {
private int age = 5; // Private access

private void display() {


System.out.println("Age: " + age);
}

public void show() {


// You can call private methods inside the class
display();
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.show(); // Calling public method, which can call private methods inside Animal class

// animal.display(); // Error: display() has private access in Animal


}
}
 Output:Age: 5

3. Protected:
 What it means: A protected member is accessible within the same package and also
by subclasses (even if the subclass is in a different package).
 Where it's used: When you want subclasses to access a member, but don’t want it to be completely
public.
 Example
class Animal {
protected int age = 5; // Protected access

protected void display() {


System.out.println("Age: " + age);
}
}

public class Dog extends Animal {


public void bark() {
// Can access protected members from Animal class
display();
System.out.println("The dog barks!");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // Accessing protected members through subclass
}
}
 Output:
Age: 5
The dog barks!

4. Public:

 What it means: A public member is accessible from anywhere in the program. Any class, inside or
outside the package, can access it.
 Where it's used: When you want to allow other classes to access and use this member freely.
 Example:
public class Animal {
public int age = 5; // Public access

public void display() {


System.out.println("Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.display(); // Accessing public method from another class
System.out.println("Age: " + animal.age); // Accessing public variable from another class
}
}
 Output:
Age: 5
Age: 5
Usage of this and super key words:

 In java, super keyword is used to access methods of the parent class while this is used to access
methods of the current class.
 this keyword is a reserved keyword in java
 i.e, we can’t use it as an identifier. It is used to refer current class’s instance as well as static members.
 It can be used in various contexts as given below:
 to refer instance variable of current class
 to invoke or initiate current class constructor
 can be passed as an argument in the method call
 can be passed as argument in the constructor call
 can be used to return the current class instance
Example:

// Program to illustrate this keyword


// is used to refer current class
class RR {
// instance variable
int a = 10;

// static variable
static int b = 20;

void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;

System.out.println(a);

// referring current class(i.e, class RR)


// static variable(i.e, b)
this.b = 600;

System.out.println(b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}

Output
100
600

Super keyword:

 super is a reserved keyword in java i.e, we can’t use it as an identifier.


 super is used to refer super-class’s instance as well as static members.
 super is also used to invoke super-class’s method or constructor.
 super keyword in java programming language refers to the superclass of the class where the super
keyword is currently being used.
 The most common use of super keyword is that it eliminates the confusion between the superclasses
and subclasses that have methods with same name.

super can be used in various contexts as given below:


 it can be used to refer immediate parent class instance variable
 it can be used to refer immediate parent class method
 it can be used to refer immediate parent class constructor.
Example:
// Program to illustrate super keyword
// refers super-class instance

class Parent {
// instance variable
int a = 10;

// static variable
static int b = 20;
}

class Base extends Parent {


void rr()
{
// referring parent class(i.e, class Parent)
// instance variable(i.e, a)
System.out.println(super.a);

// referring parent class(i.e, class Parent)


// static variable(i.e, b)
System.out.println(super.b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use 'super'
// in static context.
// super.a = 700;
new Base().rr();
}
}

Output
10
20

Similarities in this and super


 We can use this as well as super anywhere except static area. Example of this is already shown above
where we use this as well as super inside public static void main(String[]args) hence we get Compile
Time Error since cannot use them inside static area.
 We can use this as well as super any number of times in a program.
 Both are non-static keyword.

Method overloading:
 If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
 If we have to perform only one operation, having same name of the methods increases the readability
of the program.
Different ways to overload the method
There are two ways to overload the method in java
o By changing number of arguments
o By changing the data type
In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

 In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers.
 In this example, we are creating static methods so that we don't need to create instance for calling
methods.
Example:

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

Output:
22
33

2) Method Overloading: changing data type of arguments

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

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

Output:
22
24.9

Method Overriding in Java

1.If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java.
2.In other words, If a subclass provides the specific implementation of the method that has been declared by one
of its parent class, it is known as method overriding.

Rules for Java Method Overriding


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

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

Example:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running

Example of method overriding

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely

Abstract class:

 An abstract class in Java is a class that cannot be instantiated on its own.


 It can have both abstract methods (methods without a body) and concrete methods (methods with a
body).
 The purpose of an abstract class is to provide a common base for other classes, where some behavior is
shared and some behavior is left for subclasses to define.

Key Points:
Abstract Methods: Must be implemented by subclasses.
Concrete Methods: Can be inherited and used directly by subclasses.
Cannot be Instantiated: You cannot create an object of an abstract class directly.
Constructor: Abstract classes can have constructors that are called by subclass constructors.

Syntax of Abstract Classes


public abstract class Shape {
// Abstract method
public abstract double area();
// Concrete method
public void display() {
System.out.println("This is a shape.");
}
}

Example:

abstract class Animal {


public abstract void sound(); // Abstract method

public void sleep() { // Concrete method


System.out.println("The animal is sleeping");
}
}

class Dog extends Animal {


public void sound() {
System.out.println("Woof");
}
}

public class Main {


public static void main(String[] args) {
Animal dog = new Dog();
dog.sound(); //
dog.sleep(); //
}
}

Output:
Woof
The animal is sleeping

Dynamic Method Dispatch in Java

 Dynamic method dispatch is also known as run time polymorphism.


 It is the process through which a call to an overridden method is resolved at runtime.
 This technique is used to resolve a call to an overridden method at runtime rather than compile time.
 To properly understand Dynamic method dispatch in Java, it is important to understand the concept of
upcasting because dynamic method dispatch is based on upcasting.

Key Points:

 Runtime Polymorphism: The method to be called is decided at runtime based on the object being
referred to.
 Method Overriding: A subclass provides its own implementation of a method that is already defined
in the superclass.
 Superclass Reference: You can have a superclass reference pointing to a subclass object, and the
method that gets called depends on the actual object type at runtime.

Example:
// Superclass
class Animal {
// Method in superclass
public void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass Dog
class Dog extends Animal {
// Overriding the sound method
public void sound() {
System.out.println("Dog barks");
}
}

// Subclass Cat
class Cat extends Animal {
// Overriding the sound method
public void sound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
// Superclass reference but subclass objects
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

// Calling overridden methods


myAnimal.sound(); // Output: Animal makes a sound
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}
Output:
Animal makes a sound
Dog barks
Cat meows

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.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//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


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }

Output:Compile Time Error

3) Java final class


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

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }

Output:Compile Time Error

Packages

Java Package
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form, built-in package and user-defined package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
 Here, we will have the detailed learning of creating and using user-defined packages.
Package in Java: Definition

In Java, a package is a namespace used to organize classes and interfaces into groups. It helps
in structuring and organizing large codebases, preventing naming conflicts, and making code easier to
maintain and reuse.

Access protection in java package

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.
🔔 The public members can be accessed everywhere.

🔔 The private members can be accessed only inside the same class.

🔔 The protected members are accessible to every child class (same package or other packages).

🔔 The default members are accessible within the same package but not outside the package.

Let's look at the following example java code.

Example

classParentClass{
int a =10;
publicint b =20;
protectedint c =30;
privateint d =40;

voidshowData(){
System.out.println("Inside ParentClass");
System.out.println("a = "+ a);
System.out.println("b = "+ b);
System.out.println("c = "+ c);
System.out.println("d = "+ d);
}
}

classChildClassextendsParentClass{

voidaccessData(){
System.out.println("Inside ChildClass");
System.out.println("a = "+ a);
System.out.println("b = "+ b);
System.out.println("c = "+ c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
publicclassAccessModifiersExample{

publicstaticvoidmain(String[] args){

ChildClass obj =newChildClass();


obj.showData();
obj.accessData();

}
Importing Packages in java

In java, the import keyword used to import built-in and user-defined packages. When a package has imported, we

can refer to all the classes of that package using their name directly.

The import statement must be after the package statement, and before any other statement.

Using an import statement, we may import a specific class or all the classes from a package.

🔔 Using one import statement, we may import only one package or a class.

🔔 Using an import statement, we can not import a class directly, but it must be a part of a package.

🔔 A program may contain any number of import statements.

Importing specific class

Using an importing statement, we can import a specific class. The following syntax is employed to import a

specific class.

Syntax
import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.

Example

package myPackage;

importjava.util.Scanner;

publicclassImportingExample{

publicstaticvoidmain(String[] args){

Scanner read =newScanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number "+ i);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class

called Scanner from java.util package.

Importing all the classes

Using an importing statement, we can import all the classes of a package. To import all the classes of the package,

we use * symbol. The following syntax is employed to import all the classes of a package.

Syntax

import packageName.*;

Let's look at an import statement to import a built-in package.

Example
package myPackage;

importjava.util.*;

publicclassImportingExample{

publicstaticvoidmain(String[] args){

Scanner read =newScanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number "+ i);

Random rand =newRandom();

int num = rand.nextInt(100);

System.out.println("Randomly generated number "+ num);


}
}

In the above code, the class ImportingExample belongs to myPackage package, and it also importing all the

classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.

🔔 The import statement imports only classes of the package, but not sub-packages and its classes.

🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-package.

Consider the following import statement.

importjava.util.*;

The above import statement util is a sub-package of java package. It imports all the classes of util package only,

but not classes of java package.


Interfaces
Interfaces in Java
An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures,
default methods, static methods, and nested types. Interfaces are used to represent a contract or a set of methods
that a class must implement. A class implements an interface by providing the implementation for all of the
methods declared in the interface.

1. Definition of an Interface
In Java, an interface is defined using the interface keyword. It can contain abstract methods (methods without a
body), default methods (with an implementation), static methods, and constants.

Example of a simple interface:


// Interface definition
interface Animal {
// abstract method (implicitly public and abstract)
void sound();

// constant
int MAX_AGE = 100;

// default method with implementation


default void sleep() {
System.out.println("This animal is sleeping");
}

// static method
static void breathe() {
System.out.println("Breathing...");
}
}

// Class implementing the Animal interface


class Dog implements Animal {
// Implementing the sound method
public void sound() {
System.out.println("Woof");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of Dog
Dog dog = new Dog();

// Calling the implemented method from Animal interface


dog.sound(); // This will print "Woof"

// Calling the default method from Animal interface


dog.sleep(); // This will print "This animal is sleeping"

// Accessing the static method from Animal interface


Animal.breathe(); // This will print "Breathing..."

// Accessing the constant from Animal interface


System.out.println("Maximum age: " + Animal.MAX_AGE); // This will print "Maximum age: 100"
}
}Output:
Woof
This animal is sleeping
Breathing...
Maximum age: 100

2. Implementing an Interface

A class implements an interface using the implements keyword. The class is required to provide
implementations for all of the interface's abstract methods.
Example:
// Interface definition
interface Animal {
// abstract method (implicitly public and abstract)
void sound();

// constant
int MAX_AGE = 100;

// default method with implementation


default void sleep() {
System.out.println("This animal is sleeping");
}

// static method
static void breathe() {
System.out.println("Breathing...");
}
}

// Dog class implementing the Animal interface


class Dog implements Animal {
// Implementing the sound method
public void sound() {
System.out.println("Woof");
}
}

// Cat class implementing the Animal interface


class Cat implements Animal {
// Implementing the sound method
public void sound() {
System.out.println("Meow");
}
}

public class Main {


public static void main(String[] args) {
// Create objects of Dog and Cat
Dog dog = new Dog();
Cat cat = new Cat();

// Calling the implemented method from Animal interface


dog.sound(); // Output: Woof
cat.sound(); // Output: Meow

// Calling the default method from Animal interface


dog.sleep(); // Output: This animal is sleeping
cat.sleep(); // Output: This animal is sleeping

// Accessing the static method from Animal interface


Animal.breathe(); // Output: Breathing...
// Accessing the constant from Animal interface
System.out.println("Maximum age: " + Animal.MAX_AGE); // Output: Maximum age: 100
}
}
output:
Woof
Meow
This animal is sleeping
This animal is sleeping
Breathing...
Maximum age: 100

3. Extending an Interface
In Java, interfaces can extend other interfaces. When an interface extends another interface, it inherits the
abstract methods of the parent interface and can declare additional abstract methods of its own.
An interface can extend one or more interfaces, similar to how classes can inherit from multiple interfaces.
Example of extending interfaces:
// Mammal interface with walk method
interface Mammal {
void walk();
}

// Animal interface extends Mammal and adds sound method


interface Animal extends Mammal {
void sound();
}

// Dog class implements Animal interface


class Dog implements Animal {
// Implementing the sound method
public void sound() {
System.out.println("Woof");
}

// Implementing the walk method


public void walk() {
System.out.println("Dog is walking");
}
}

public class Main {


public static void main(String[] args) {
// Create a Dog object
Dog dog = new Dog();

// Calling the sound method


dog.sound(); // Output: Woof

// Calling the walk method


dog.walk(); // Output: Dog is walking
}
}
Output:
Woof
Dog is walking
EXCEPTION HANDALING

An exception is a condition that is caused by a run time error in the program.


 An exception is an abnormal condition that arises in a code sequence at run time. It is a condition that is
caused by a run-time error in a program.
 It can be generated by the Java run-time system, or they can be manually generated by your code. If we
want the program to continue with the execution of the remaining code, then we should try to catch the
exception object thrown by the error condition and then display an appropriate message for taking
corrective actions. This is known as exception handling.
 The purpose of exception handling is to provide a means to detect and report an exceptional circumstance
so that appropriate actions can be taken.
 The error handling code that performs the following tasks:
 Find the problem (Hit the exception)
 Inform that an error has occurred (Throw the exception)
 Receive the error information (Catch the exception)
 Take corrective actions (Handle the exceptions)

 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Program
statements that you want to monitor for exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown.
 Using catch we can catch this exception and handle it in some relational manner. System-generated
exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use
the keyword throw.
Try -Catch Blocks:
 The default exception handler provided by the Java run-time system is useful for debugging; we will
usually want to handle an exception yourself. It provides two benefits. First, it allows you to fix the error;
second, it prevents the program from automatically terminating.
 To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a
try block. Immediately following the try block, include a catch clause that specifies the exception type
that you wish to catch.
 The following example illustrates the use of simple try and catch statements:

try

Statement; // generates an exception

catch (Exception-type e)
{

Statement; // Processes the exception

Example:

 To illustrate how easily this can be done, the following program includes a try block and a catch clause
which processes the ArithmeticException generated by the division-by-zero error.
class Error4

public static void main(String arg[])

int d = 10;

int e = 5;

int f = 5;

int x, y;

try

x = d /(e-f);

catch (ArithmeticException k)

System.out.println ("Division by zero");

y = d / (e+f);

System.out.println(y);

FINALLY

creating own exceptions

 Java supports another statement known as finally statement that can be used to handle an exception that
is not caught by any of the previous catch statements.
 The finally block can be used to handle any exception generated within a try block. It may be added
immediately after the try block or after the last catch block shown as follows:
try
{

statement;

catch(Exception-Type-1 e )

statement;

...

...

catch(Exception-Type-n e)

statement;

finally

statement;

 finally creates a block of code that will be executed after a try/catch block has completed and before the
code following the try/catch block.
 The finally block will execute whether or not an exception is thrown. If an exception is thrown, the
finally block will execute even if no catch statement matches the exception.
 We can use this statement to perform certain housekeeping operations such as closing files and releasing
system resources.
Example:

class Error6

public static void main(String arg[])

int a[] = {10,15};

int b = 10;

try

int x = a[1] / b - a[1];

catch (ArrayIndexOutOfBoundsException k)

{
System.out.println ("Array Index Error");

finally

System.out.println("Catch is not found");

Throws- built in exception

 There may be times when we would like to throw our own exceptions. We can do this by using the
keyword throws as follows:
throw new Throwable_subclass;

Example:

throw new ArithmeticException();

throw new NumberFormatexception();

Program:

import java.lang.Exception;

class MyException extends Exception

MyException (String message)

super (message);

class TestMyException

public static void main(String args[])

int x=5 , y=1000;

try

float z = (float) x / (float) y;

if(z < 0.01)

throw new MyException ("Number is too small");


}

catch (MyException e)

System.out.println ("Caught my exception ");

System.out.println (e.getMessage());

finally

System.out.println("I am always here");

Output:

Caught my exception

Number is too small

I am always here

---------------------------------------------------UNIT 2 COMPLETED------------------------------------------------------

You might also like