0% found this document useful (0 votes)
3 views41 pages

Programming in Java-Unit III

Inheritance in Java is a key concept of Object-Oriented Programming that allows one class to inherit the features of another, promoting code reusability and method overriding. There are various types of inheritance, including single, multilevel, hierarchical, and multiple inheritance (through interfaces). The 'super' keyword is utilized to access parent class methods and fields, while abstract classes and methods provide a framework for subclasses to implement specific functionality.

Uploaded by

Shameem Sulthana
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)
3 views41 pages

Programming in Java-Unit III

Inheritance in Java is a key concept of Object-Oriented Programming that allows one class to inherit the features of another, promoting code reusability and method overriding. There are various types of inheritance, including single, multilevel, hierarchical, and multiple inheritance (through interfaces). The 'super' keyword is utilized to access parent class methods and fields, while abstract classes and methods provide a framework for subclasses to implement specific functionality.

Uploaded by

Shameem Sulthana
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/ 41

Inheritance

Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is


the mechanism in Java by which one class is allowed to inherit the features(fields and
methods) of another class. In Java, Inheritance means creating new classes based on
existing ones. A class that inherits from another class can reuse the methods and fields
of that class. In addition, you can add new fields and methods to your current class as
well.
Why Do We Need Inheritance?
 Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.
Types of Inheritance
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.

Single inheritance
Java
// Java program to illustrate the

// concept of single inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

// Parent class

class one {

public void print_green()

System.out.println("Green");

class two extends one {

public void print_for() { System.out.println("for"); }

// Driver class

public class Main {

// Main function

public static void main(String[] args)

two g = new two();

g.print_ green ();

g.print_for();

g.print_ green ();

}
Output
Green
for
Green

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes. In the below image,
class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.

Multilevel Inheritance

Java
// Java program to illustrate the

// concept of Multilevel inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

class one {

public void print_ green ()


{

System.out.println("Green");

class two extends one {

public void print_for() { System.out.println("for"); }

class three extends two {

public void print_ green()

System.out.println("Green ");

}
// Drived class

public class Main {


public static void main(String[] args)

three g = new three();

g.print_ green();

g.print_for();

g.print_ green();

Output
Green
for
Green
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one subclass. In the below image, class A serves as a base class for the derived classes
B, C, and D.

Java
// Java program to illustrate the

// concept of Hierarchical inheritance

class A {

public void print_A() { System.out.println("Class A"); }

class B extends A {

public void print_B() { System.out.println("Class B"); }

class C extends A {

public void print_C() { System.out.println("Class C"); }

class D extends A {
public void print_D() { System.out.println("Class D"); }

// Driver Class
public class Test {

public static void main(String[] args)

B obj_B = new B();

obj_B.print_A();
obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();

obj_D.print_A();

obj_D.print_D();

Output
Class A
Class B
Class A
Class C
Class A
Class D
Java support Multiple Inheritance (Through
Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.

Multiple Inheritance

Java
// Java program to illustrate the

// concept of Multiple inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

interface one {

public void print_green();

interface two {
public void print_for();

interface three extends one, two {

public void print_green();

class child implements three {

@Override public void print_ green()

System.out.println("Green");

public void print_for() { System.out.println("for"); }

// Drived class

public class Main {

public static void main(String[] args)

child c = new child();

c.print_green();

c.print_for();

c.print_green();

}
}

Output
Green
for
Green
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class
objects. An understanding of Inheritance and Polymorphism is needed in order to
understand the Java super keyword. The keyword “super” came into the picture with
the concept of Inheritance.
Characteristics of super Keyword in Java
In Java, the super keyword is used to refer to the parent class of a subclass. Here are
some of its characteristics:
 super is used to call a superclass constructor: When a subclass is created, its
constructor must call the constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the parent class.
 super is used to call a superclass method: A subclass can call a method defined in
its parent class using the super keyword. This is useful when the subclass wants
to invoke the parent class’s implementation of the method in addition to its own.
 super is used to access a superclass field: A subclass can access a field defined in
its parent class using the super keyword. This is useful when the subclass wants
to reference the parent class’s version of a field.
 super must be the first statement in a constructor: When calling a superclass
constructor, the super() statement must be the first statement in the constructor of
the subclass.
 super cannot be used in a static context: The super keyword cannot be used in a
static context, such as in a static method or a static variable initializer.
 super is not required to call a superclass method: While it is possible to use the
super keyword to call a method in the parent class, it is not required. If a method
is not overridden in the subclass, then calling it without the super keyword will
invoke the parent class’s implementation.
Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.

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.

Example: Java code to show use of super keyword with variables

// Base class vehicle

class Vehicle {
int maxSpeed = 120;

// sub class Car extending vehicle

class Car extends Vehicle {

int maxSpeed = 180;

void display()

// print maxSpeed of base class (vehicle)

System.out.println("Maximum Speed: "+ super.maxSpeed);

// Driver Program

class Test {

public static void main(String[] args)

Car small = new Car();

small.display();

Output
Maximum Speed: 120

Method Overriding

Inheritance is an OOP property that allows us to derive a new class (subclass) from
an existing class (superclass). The subclass inherits the attributes and methods of
the superclass.
Now, if the same method is defined in both the superclass and the subclass, then
the method of the subclass class overrides the method of the superclass. This is
known as method overriding.

Example 1: Method Overriding


class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code

Output:

I am a dog.

In the above program, the displayInfo() method is present in both


the Animal superclass and the Dog subclass.
When we call displayInfo() using the d1 object (object of the subclass), the method
inside the subclass Dog is called. The displayInfo() method of the subclass overrides
the same method of the superclass.
Notice the use of the @Override annotation in our example. In Java, annotations are
the metadata that we used to provide information to the compiler. Here,
the @Override annotation specifies the compiler that the method after this annotation
overrides the method of the superclass.
It is not mandatory to use @Override. However, when we use this, the method
should follow all the rules of overriding. Otherwise, the compiler will generate an
error.
Java Overriding Rules
 Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.

 We cannot override the method declared as final and static.

 We should always override abstract methods of the superclass

Dynamic method dispatch or Runtime


polymorphism in Java
Runtime Polymorphism in Java is achieved by Method overriding in which a child class overrides
a method in its parent. An overridden method is essentially hidden in the parent class, and is not
invoked unless the child class uses the super keyword within the overriding method. This method
call resolution happens at runtime and is termed as Dynamic method dispatch mechanism.
Example
Let us look at an example.

class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {

Animal a = new Animal(); // Animal reference and object


Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}

This will produce the following result −

Output
Animals can move
Dogs can walk and run

In the above example, you can see that even though b is a type of Animal it runs the move method
in the Dog class. The reason for this is: In compile time, the check is made on the reference type.
However, in the runtime, JVM figures out the object type and would run the method that belongs
to that particular object.

Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.
abstract keyword in java
In Java, abstract is a non-access modifier in java applicable for classes, and methods
but not variables. It is used to achieve abstraction which is one of the pillars of Object
Oriented Programming(OOP). Following are different contexts where abstract can be
used in Java.
Characteristics of Java abstract Keyword
In Java, the abstract keyword is used to define abstract classes and methods. Here are
some of its key characteristics:
 Abstract classes cannot be instantiated: An abstract class is a class that cannot
be instantiated directly. Instead, it is meant to be extended by other classes, which
can provide concrete implementations of its abstract methods.
 Abstract methods do not have a body: An abstract method is a method that does
not have an implementation. It is declared using the abstract keyword and ends
with a semicolon instead of a method body. Subclasses of an abstract class must
provide a concrete implementation of all abstract methods defined in the parent
class.
 Abstract classes can have both abstract and concrete methods: Abstract classes
can contain both abstract and concrete methods. Concrete methods are
implemented in the abstract class itself and can be used by both the abstract class
and its subclasses.
 Abstract classes can have constructors: Abstract classes can have constructors,
which are used to initialize instance variables and perform other initialization
tasks. However, because abstract classes cannot be instantiated directly, their
constructors are typically called constructors in concrete subclasses.
 Abstract classes can contain instance variables: Abstract classes can contain
instance variables, which can be used by both the abstract class and its subclasses.
Subclasses can access these variables directly, just like any other instance
variables.
 Abstract classes can implement interfaces: Abstract classes can implement
interfaces, which define a set of methods that must be implemented by any class
that implements the interface. In this case, the abstract class must provide concrete
implementations of all methods defined in the interface.
Overall, the abstract keyword is a powerful tool for defining abstract classes and
methods in Java. By declaring a class or method as abstract, developers can provide a
structure for subclassing and ensure that certain methods are implemented in a
consistent way across all subclasses.

Abstract Methods in Java


Sometimes, we require just method declaration in super-classes. This can be achieved
by specifying the abstract type modifier. These methods are sometimes referred to
as subclasser responsibility because they have no implementation specified in the
super-class. Thus, a subclass must override them to provide a method definition. To
declare an abstract method, use this general form:
abstract type method-name(parameter-list);
As you can see, no method body is present. Any concrete class(i.e. class without
abstract keyword) that extends an abstract class must override all the abstract methods
of the class.
Important rules for abstract methods
There are certain important rules to be followed with abstract methods as mentioned
below:
 Any class that contains one or more abstract methods must also be declared
abstract
 The following are various illegal combinations of other modifiers for methods with
respect to abstract modifiers:
1. final
2. abstract native
3. abstract synchronized
4. abstract static
5. abstract private
6. abstract strictfp
Abstract Classes in Java
The class which is having partial implementation(i.e. not all methods present in the
class have method definitions). To declare a class abstract, use this general form :
abstract class class-name{
//body of class
}
Due to their partial implementation, we cannot instantiate abstract classes. Any
subclass of an abstract class must either implement all of the abstract methods in the
super-class or be declared abstract itself. Some of the predefined classes in Java are
abstract. They depend on their sub-classes to provide a complete implementation.
For example, java.lang.Number is an abstract class. For more on abstract classes,
see abstract classes in Java.\
Example:

// Java Program to implement Abstract Keywords

// Parent Class

abstract class gfg {


abstract void printInfo();

// Child Class

class employee extends gfg {

void printInfo()

String name = "aakanksha";

int age = 21;

float salary = 55552.2F;

System.out.println(name);

System.out.println(age);

System.out.println(salary);

// driver Class

class base {

// main function

public static void main(String args[])

// object created

gfg s = new employee();


s.printInfo();

Output
aakanksha
21
55552.2

Advantages of Abstract Keywords

Here are some advantages of using the abstract keyword in Java:


 Provides a way to define a common interface: Abstract classes can define a
common interface that can be used by all subclasses. By defining common
methods and properties, abstract classes provide a way to enforce consistency
and maintainability across an application.
 Enables polymorphism: By defining a superclass as abstract, you can create a
collection of subclasses that can be treated as instances of the superclass. This
allows for greater flexibility and extensibility in your code, as you can add new
subclasses without changing the code that uses them.
 Encourages code reuse: Abstract classes can define common methods and
properties that can be reused by all subclasses. This saves time and reduces code
duplication, which can make your code more efficient and easier to maintain.
 Provides a way to enforce implementation: Abstract methods must be
implemented by any concrete subclass of the abstract class. This ensures that
certain functionality is implemented consistently across all subclasses, which can
prevent errors and improve code quality.
 Enables late binding: By defining a common interface in an abstract class, you
can use late binding to determine which subclass to use at runtime. This allows
for greater flexibility and adaptability in your code, as you can change the
behavior of your program without changing the code itself.
abstract and final class in Java
In Java, you will never see a class or method declared with both final and abstract
keywords. For classes, final is used to prevent inheritance whereas abstract classes
depend upon their child classes for complete implementation. In cases of methods,
final is used to prevent overriding whereas abstract methods need to be overridden in
sub-classes.
Package in Java
In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java
contains many pre-defined packages such as java.lang, java.io, java.net, etc. When we create
any Java program the java.lang package is imported by default. We need not to write the
package name at the top of the program. We can also create our own package by providing the
name that we want. In this section, we will learn how to create a package in Java.

We use package for the following reasons:

o The package makes the search easier for the classes and interfaces.
o It provides a fully qualified name that avoids naming conflicts.
o It also controls access.
o It organizes classes in a folder structure.
o It improves code reusability.
o Programmer can group classes and interfaces into a related package.

Creating a Package
To create a package, follow the steps given below:

o Choose a package name according to the naming convention.


o Write the package name at the top of every source file (classes, interface, enumeration,
and annotations).
o Remember that there must be only one package statement in each source file.

Package Naming Convention


We follow the naming convention rules to name a package. Java has some predefined packages
and also allows us to create our own package. So, it is possible that a programmer can create a
class with the same name as a package that already contains that type in a predefined package.

Let's take an example of the Rectangle class.

Suppose, a programmer creates a class with the name Rectangle in the package shape. The
class with the same name is already present in java.awt package. The compiler allows both
classes if they belong to the different packages. The fully qualified name of each class contains
the package name that differentiate both Rectangle classes. Therefore, the package name of the
user-defined class will be shape.Rectangle and the package name of the predefined class will
be java.awt.Rectangle.
o Package name must be in lower case that avoids conflict with the name of classes and
interfaces.
o Organizations used their internet domain name to define their package names. For
example, com.javatpoint.mypackage. Sometimes, the organization also uses the
region after the company name to name the package. For
example, com.javatpoint.region.mypackage.
o We use underscore in the package name if the domain name contains hyphen or other
special characters or package names begin with a digit or reserved keyword.

Domain Name Package Name Prefix

Hyphenated-name.example.org org.example.hyphenated_name

Example.int int_.example

123name.example.com com.example._123name

Access Protection in Packages


Access modifiers define the scope of the class and its members (data and methods). For
example, private members are accessible within the same class members
(methods). Java provides many levels of security that provides the visibility of members
(variables and methods) within the classes, subclasses, and packages.
Packages are meant for encapsulating, it works as containers for classes and other
subpackages. Class acts as containers for data and methods. There are four categories,
provided by Java regarding the visibility of the class members between classes and packages:

o Subclasses in the same package


o Non-subclasses in the same package
o Subclasses in different packages
o Classes that are neither in the same package nor subclasses

The three main access modifiers private, public and protected provides a range of ways to
access required by these categories.
Simply remember,
private cannot be seen outside of its class, public can be access from anywhere, and protected
can be accessible in subclass only in the hierarchy.
A class can have only two access modifier, one is default and another is public. If the class
has default access then it can only be accessed within the same package by any other code.
But if the class has public access then it can be access from any where by any other code.

Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
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);
}
}

class ChildClass extends ParentClass{

void accessData() {
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
}
}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


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

Output

Importing a Package
If we want to use a package in Java program it is necessary to import that package at the top of
the program by using the import keyword before the package name.

Syntax:

import packageName;

// Java Program to Import a package

// Importing java utility package


import java.util.*;

// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{

// Scanner to take input from the user object


Scanner myObj = new Scanner(System.in);
String userName;

// Display message
// Enter Your Name And Press Enter
System.out.println("Enter Your Name:");

// Reading the integer age entered using


// nextInt() method
userName = myObj.nextLine();

// Print and display


System.out.println("Your Name is : " + userName);
}
}
Input

Enter Your Name:


BCAIIYR

Output

Your Name is : BCAIIYR

Here In The Above Program, ‘java.util’ package is imported and run for a simple
program. These are called as Inbuilt Packages.

Now in order to create a package in java follow the certain steps as described
below:
1. First We Should Choose A Name For The Package We Are Going To
Create And Include. The package command In The first line in the java
program source code.
2. Further inclusion of classes, interfaces, annotation types, etc that is
required in the package can be made in the package. For example, the
below single statement creates a package name called “FirstPackage”.
Syntax: To declare the name of the package to be created. The package statement
simply defines in which package the classes defined belong.
package FirstPackage ;
Implementation: To Create a Class Inside A Package
1. First Declare The Package Name As The First Statement Of Our Program.
2. Then We Can Include A Class As A Part Of The Package.
Example
// Name of package to be created
package FirstPackage;

// Class in which the above created package belong to


class Welcome {
// main driver method
public static void main(String[] args)
{
// Print statement for the successful
// compilation and execution of the program
System.out.println(
"This Is The First Program for package..");
}
}

So, Inorder to generate the above-desired output first do use the commands as
specified use the following specified commands
Procedure:
1. To generate the output from the above program
Command: javac Welcome.java
2. The Above Command Will Give Us Welcome.class File.
Command: javac -d . Welcome.java
3. So This Command Will Create a New Folder Called FirstPackage.
Command: java FirstPackage.Welcome

Output: The Above Will Give The Final Output Of The Example Program
This Is The First Program for package

This Is The Output Of The Above Program

Java - Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of
abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.

Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default
methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes
and behaviors of an object. And an interface contains behaviors that a class
implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.

An interface is similar to a class in the following ways −

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be
in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including −

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear
in an interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

Defining Interfaces
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface −

Example

Following is an example of an interface −

/* File name : NameOfInterface.java */


import java.lang.*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}

Interfaces have the following properties −

 An interface is implicitly abstract. You do not need to use


the abstract keyword while declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract
keyword is not needed.
 Methods in an interface are implicitly public.
Example
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}

Implementing Interfaces
When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface. If a class does
not perform all the behaviors of the interface, the class must declare itself as
abstract.

A class uses the implements keyword to implement an interface. The implements


keyword appears in the class declaration following the extends portion of the
declaration.

Example
/* File name : MammalInt.java */
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Output
Mammal eats
Mammal travels

Extending Interfaces
An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

Example
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

The Hockey interface has four methods, but it inherits two from Sports; thus, a
class that implements Hockey needs to implement all six methods. Similarly, a
class that implements Football needs to define the three methods from Football and
the two methods from Sports.

Java Exceptions
In Java, Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the program’s
instructions. Exceptions can be caught and handled by the program. When an
exception occurs within a method, it creates an object. This object is called the
exception object. It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.
Major reasons why an exception Occurs
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library incompatibility,
infinite recursion, etc. Errors are usually beyond the control of the programmer, and
we should not try to handle errors

Types of Exception in Java with Examples


Java defines several types of exceptions that relate to its various class libraries. Java
also allows users to define their own exceptions.

Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java.
1. ArithmeticException: It is thrown when an exceptional condition has
occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or
greater than or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to access
a class whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not
accessible or does not open.
5. IOException: It is thrown when an input-output operation failed or
interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the
field (or variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is
not found.
9. NullPointerException: This exception is raised when referring to the
members of a null object. Null represents nothing
10. NumberFormatException: This exception is raised when a method could
not convert a string into a numeric format.
11. RuntimeException: This represents an exception that occurs during
runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods
to indicate that an index is either negative or greater than the size of the
string
13. IllegalArgumentException : This exception will throw the error or error
statement when the method receives an argument which is not accurately fit
to the given relation or condition. It comes under the unchecked exception.
14. IllegalStateException : This exception will throw an error or error message
when the method is not accessed for the particular operation in the
application. It comes under the unchecked exception.
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
 The user should create an exception class as a subclass of the Exception
class. Since all the exceptions are subclasses of the Exception class, the
user should also make his class a subclass of it. This is done as:
class MyException extends Exception
 We can write a default constructor in his own exception class.
MyException(){}
 We can also create a parameterized constructor with a string as a
parameter.
We can use this to store exception details. We can call the
superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
 To raise an exception of a user-defined type, we need to create an object to
his exception class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
 The following program illustrates how to create your own exception class
MyException.
 Details of account numbers, customer names, and balance amounts are
taken in the form of three arrays.
 In main() method, the details are displayed using a for-loop. At this time, a
check is done if in any account the balance amount is less than the
minimum balance amount to be apt in the account.
 If it is so, then MyException is raised and a message is displayed “Balance
amount is less”.

Exception Handling in Java


Exception handling in java is one of the powerful mechanisms to handle runtime errors
caused by exceptions. Exception handling plays an important role in software
development. Exception handling in java helps in minimizing exceptions and helps in
recovering from exceptions. It is one of the powerful mechanisms to handle runtime
exceptions and makes it bug-free. Exception handling helps in maintaining the flow of the
program. An exception handling is defined as an abnormal condition that may happen at
runtime and disturb the normal flow of the program.

try...catch
The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:

try {
// code
}
catch(Exception e) {
// code
}

Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block cannot be
used without the try block.
Example: Exception handling using try...catch
class Main {
public static void main(String[] args) {

try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Run Code

Output

ArithmeticException => / by zero

In the example, we are trying to divide a number by 0. Here, this code generates an
exception.
To handle the exception, we have put the code, 5/0 inside the try block. Now when
an exception occurs, the rest of the code inside the try block is skipped.
The catch block catches the exception and statements inside the catch block is
executed.
If none of the statements in the try block generates an exception, the catch block is
skipped.
Multiple Catch Clauses
Starting from Java 7.0, it is possible for a single catch block to catch multiple
exceptions by separating each with | (pipe symbol) in the catch block.
Catching multiple exceptions in a single catch block reduces code duplication and
increases efficiency. The bytecode generated while compiling this program will be
smaller than the program having multiple catch blocks as there is no code
redundancy.
Note: If a catch block handles multiple exceptions, the catch parameter is implicitly
final. This means we cannot assign any values to catch parameters.
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}

Flow Chart of Java Multiple Catch Block


// A Java program to demonstrate

// multicatch feature

import java.util.Scanner;

public class Test

public static void main(String args[])

Scanner scn = new Scanner(System.in);

try

int n = Integer.parseInt(scn.nextLine());

if (99%n == 0)

System.out.println(n + " is a factor of 99");

catch (NumberFormatException | ArithmeticException ex)

System.out.println("Exception encountered " + ex);

Input 1:
catchblock

Output 1:
Exception encountered java.lang.NumberFormatException:

For input string: " catchblock "


Input 2:
0
Output 2:
Exception encountered
java.lang.ArithmeticException: / by zero
A catch block that handles multiple exception types creates no duplication in the
bytecode generated by the compiler. That is, the bytecode has no replication of
exception handlers.
Important Points:
1. If all the exceptions belong to the same class hierarchy, we should be catching the
base exception type. However, to catch each exception, it needs to be done separately
in their catch blocks.
2. Single catch block can handle more than one type of exception. However, the base
(or ancestor) class and subclass (or descendant) exceptions can not be caught in one
statement.
For Example
// Not Valid as Exception is an ancestor of
// NumberFormatException
catch(NumberFormatException | Exception ex)
3. All the exceptions must be separated by vertical bar pipe |

Finally Block In Java


So far we have seen the try-catch and nested try block. We know that the code that is
expected to raise the exception is put in a try block. When an exception occurs, then the
remainder of the code in the try block is not executed.

Either the program terminates abruptly if an exception is not handled or the control is passed
to the exception handler.

In such a situation, there arises a need to include a code that is to be executed irrespective of
whether an exception occurs or not. This means we will execute a piece of code even when
an exception occurs and also when the exception does not occur.

But as try block exits after the exception is raised we cannot put this code in the try block.
Similarly, the catch block has an exception handler, so we cannot put this in the catch block
too.

Thus we need a separate block that contains a code that executes irrespective of whether an
exception occurs or not. Java provides a “finally” block that contains this piece of code.

Hence a finally block in Java can contain critical statements that are to be executed in the
program. The execution of these statements should be carried out even when an exception
occurs or not.

Therefore, we will put code like closing connections, stream objects, etc. or any cleanup code
in the finally block so that they can be executed even if an exception occurs.
The finally block in Java is usually put after a try or catch block. Note that the finally block
cannot exist without a try block. When the finally block is included with try-catch, it becomes
a “try-catch-finally” block.
We can skip the finally block in the exception handling code. This means that finally block is
optional.

If the try block does not raise any exception then the finally block will be executed after the
try block. If there is an exception in the try block then control will pass to the catch block first
and then the finally block.

An exception occurring in finally block behaves in the same way as any other exception.
Even if the try block contains a return statement or branching statements like break and
continue, then the finally block will still be executed.

Keeping these points in mind, let’s go ahead with the general syntax and examples of finally
block.

The general syntax of the finally block is as follows:


try {

</em><em> //code that might raise exception

</em><em> }catch {

</em><em> //code that handles exception

</em><em> }finally {

</em><em> //mandatory code to be executed

</em><em> }

Though finally block is always executed, there are certain situations or cases in which it
doesn’t execute.

These are the below cases:


 When the thread is dead.
 When the System.exit() method is used.
 When an exception occurs in the finally block.
Let’s implement a couple of programs to demonstrate the finally block.
class Main {
public static void main (String args[]) {
//try block
try
{
System.out.println ("::Try Block::");
int data = 125 / 5;
System.out.println ("Result:" + data);
}
//catch block
catch (NullPointerException e) {
System.out.println ("::Catch Block::");
System.out.println (e);
}
//finally block
finally {
System.out.println (":: Finally Block::");
System.out.println ("No Exception::finally block executed");
}
System.out.println ("rest of the code...");
}
}
Output

The above program shows a try-catch-finally block. In the try block, a valid operation is
performed and hence no exception is thrown. Therefore, the control is not passed to catch
from try but to finally block.

The following program is another example of try-catch-finally block but in this case, the
exception is thrown in the try block as we perform a divide by zero operation. Thus the
finally block is executed after the try the catch block is executed.

class Main {
public static void main(String args[]) {
//try block
try{
System.out.println("::Try block::");
int num=67/0;
System.out.println(num);
}
//catch block
catch(ArithmeticException e){
System.out.println("::Catch block::");
System.out.println("ArithmeticException::Number divided by zero");
}
//finally block
finally{
System.out.println("::Finally block::");
}
System.out.println("Rest of the code continues...");
}
}
Output

Throw An Exception In Java


Java provides a keyword “throw” using which we can explicitly throw the exceptions in the
code. For example, if we are checking arithmetic operations and want to raise some
exceptions after checking operands we can do so using the ‘throw’ keyword.
Using the throw keyword, we can throw the checked or unchecked exceptions. The throw
keyword is also used to throw custom exceptions.

The general syntax of the throw keyword is:


throw exception;
or

throw new exception_class("error message");


Given below is an example program to demonstrate the throw keyword.
public class Main{
static void validate_Age(int age){
//if specified age is &lt; 18, throw ArithmeticException
if(age&lt;18)
throw new ArithmeticException("Not eligible to vote and drive!!");
else //print the message
System.out.println("Eligible to vote and drive!!");
}
public static void main(String args[]){
//call validate_Age method
validate_Age(10);
System.out.println("rest of the code...");
}
}
Output

In the above program, we use a method to validate age. If the age is < 18, then an exception is
thrown to indicate the age is not valid.

Throws Clause
We have seen try block to declare exceptions. It contains the code that may raise exceptions.
There is another way to declare an exception and it is using the “throws” keyword.

The declaration of exception using the “throws” keyword tells the programmer that there may
be an exception specified after the “throws” keyword and the programmer should provide
corresponding handler code for this exception to maintain the normal flow of the program.

However, the question arises as to why we need a “throws” keyword when we have a more
reliable try-catch block to declare and handle exceptions.
One reason is as the number of exceptions that might possibly occur increases, the number of
catch block that handles exceptions also increases as one catch block can handle only one
exception.

Similarly, if there are many methods in a program and each method has numerous exceptions
then the code will become unnecessarily long and unmanageable.

Thus declaring an exception with the throws keyword in the method signature and then
handling the method call using try-catch seems to be a viable solution.

Another advantage of declaring exceptions using the throws keyword is that we are forced to
handle the exceptions. If we do not provide a handler for a declared exception then the
program will raise an error.

The general syntax of the throws keyword is as follows:


return_type method_name() throws exception_class_name{

//method code

}
Let us now implement a Java program to demonstrate the “throws” keyword.
In this program, we have a class Example_throw in which we have a method testMethod. In
the signature of this testMethod, we declare two exceptions IOException and Arithmetic
Exception using the throws keyword. Then in the main function, the exceptions thrown are
handled by the catch block.

import java.io.*;
class Example_Throw {
//declare exception using throws in the method signature
void testMethod(int num) throws IOException, ArithmeticException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ArithmeticException("ArithmeticException");
}
}class Main{
public static void main(String args[]){
try{
//this try block calls the above method so handle the exception
Example_Throw obj=new Example_Throw();
obj.testMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output

Built-in Exceptions in Java


 
Ty pe s of Exceptions in Java Built-in exceptions are the exceptions which are
available in Java libraries. These exceptions are suitable to explain certain error
situations. Below is the list of important built-in exceptions in Java.
Examples of Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has occurred in
an arithmetic operation.
 Java
// Java program to demonstrate

// ArithmeticException

class ArithmeticException_Demo {

public static void main(String args[])

try {

int a = 30, b = 0;

int c = a / b; // cannot divide by zero

System.out.println("Result = " + c);

catch (ArithmeticException e) {

System.out.println("Can't divide a number by 0");

}
Output:
Can't divide a number by 0

Java user-defined exception is a custom exception created and throws that

exception using a keyword ‘throw’. It is done by extending a class

‘Exception’. An exception is a problem that arises during the execution of the

program. In Object-Oriented Programming language, Java provides a

powerful mechanism to handle such exceptions. Java allows to create own

exception class, which provides own exception class implementation. Such

exceptions are called user-defined exceptions or custom exceptions. Let us

dig deeper and look at how user-defined exceptions are created in Java, its

syntax, if any, and how it is implemented by solving some examples.

Syntax:

We do not have any particular syntax for Java user-defined exception; we

will see how to create a User-defined exception.

Below is the code which will help to Create a User-defined exception class,

class SampleException{
public static void main(String args[]){
try{
throw new UserException(<value>); // used to create new exception and throw
}
catch(Exception e){
System.out.println(e);
}
}
}
class UserException extends Exception{
// code for exception class
}

Here, while creating an exception class, it needs to be extended from java.

lang.Exception.

An exception is an event that leads to sudden termination of the program

during execution at runtime.

You might also like