22CS202-Unit 2 Notes
22CS202-Unit 2 Notes
UNIT – II
Inheritance can be defined as the process of acquiring all the properties and behaviors of one
class to another. Acquiring the properties and behavior of child class from the parent class.
Inheritance represents the IS-A relationship, also known as parent-child relationship. 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.
Example
• As displayed in the 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.
1
22CS202 – Java Programming (Theory Course with Lab Component)
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.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
Based on 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.
2
22CS202 – Java Programming (Theory Course with Lab Component)
Single Inheritance
Single inheritance enables a derived class to inherit properties and behaviour from a single
parent class. It allows a derived class to inherit the properties and behaviour of a base class,
thus enabling code reusability as well as adding new features to the existing code.
3
22CS202 – Java Programming (Theory Course with Lab Component)
{
Studentobj = newStudent();
obj.input();
obj.display();
}
}
Output
Enter Roll Number: 22
Enter Name: Coder Website
Enter class: 12th
/******* Student details printed ********/
Roll Number is: 22
Your name is: Coder Website
Your class is: 12th
Multi-level Inheritance
The multi-level inheritance includes the involvement of at least two or more than two
classes. One class inherits the features from a parent class and the newly created sub-class
becomes the base class for another new class.
Example
class students
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno = no;
sname = name;
}
public void putstud()
{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class marks extends students
{
protected int mark1,mark2;
4
22CS202 – Java Programming (Theory Course with Lab Component)
Output
Student No : 100
Student Name : Elon
Mark1 : 78
Mark2 : 89
Total : 167
Hierarchical inheritance
When two or more derived class inherits the properties and behavior from same parent class.
It is known as hierarchical inheritance.
In other words, when several classes inherit their features from the same class, the type of
inheritance is said to be hierarchical.
When two or more classes inherits a single class, it is known as hierarchical inheritance.
5
22CS202 – Java Programming (Theory Course with Lab Component)
Example:
/ * This program is used for Hierarchical inheritance example. */
class Numbers
{
int a = 10;
int b = 20;
}
class AddNumbers extends Numbers
{
/* This method is used to add */
public void showAdd()
{
System.out.println(a + b);
}
}
class MultiplyNumbers extends Numbers
{
/* This method is used to multiply. */
public void showMultiplication()
{
System.out.println(a * b);
}
}
class Test
{
public static void main(String args[])
{
//creating base classes objects
AddNumbers obj1 = new AddNumbers();
MultiplyNumbers obj2 = new MultiplyNumbers();
//method calls
obj1.showAdd();
obj2.showMultiplication();
}
}
Output
30
200
6
22CS202 – Java Programming (Theory Course with Lab Component)
Example
/* Parent class */
class ParentClass
{
int num = 120;
}
/* sub class childClass extending parentClass */
class ChildClass extends ParentClass
{
int num = 100;
void display()
{
//printing the num without use of super keyword
System.out.println("Value of Num in child class: " + num);
// printing the num with use of super keyword
System.out.println("Value of Num in parent class: " + super.num);
}
7
22CS202 – Java Programming (Theory Course with Lab Component)
}
class Main{
public static void main(String[] args)
{
ChildClass a = new ChildClass();
a.display();
}
}
Output:
Value of Num in child class: 100
Value of Num in parent class: 120
When we create the object of sub class, the new keyword invokes the constructor of
child class, which implicitly invokes the constructor of parent class. So, the order to execution
when we create the object of child class is: parent class constructor is executed first and then
the child class constructor is executed.
It happens because compiler itself adds super()(this invokes the no-arg constructor of
parent class) as the first statement in the constructor of child class.
Example
/* Parent class */
class ParentClass
{
void function()
{
System.out.println("This is method of parent class");
}
}
8
22CS202 – Java Programming (Theory Course with Lab Component)
Output:
This is method of parent class
This is method of child class
Example
/* Parent class */
class ParentClass
{
//parent class constructor
ParentClass()
{
System.out.println("This is constructor parent class");
}
}
/* sub class childClass extending parentClass */
class ChildClass extends ParentClass
{
//child class constructor
ChildClass()
{
//call parent constructor
super();
System.out.println("This is constructor of child class");
}
}
Output:
This is constructor parent class
This is constructor of child class
9
22CS202 – Java Programming (Theory Course with Lab Component)
➢ If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
➢ In other words, if a subclass provides the specific implementation of the method that
has been declared by one of its parent classes, it is known as method overriding.
Example
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();
}
}
import java.util.Scanner;
interface maths
{
public void add();
public void sub();
public void mul();
public void div();
}
class Arithmetic implements maths
{
@Override
public void add()
{
10
22CS202 – Java Programming (Theory Course with Lab Component)
11
22CS202 – Java Programming (Theory Course with Lab Component)
Output:
When a child class declares a same method which is already present in the parent class then
this is called method overriding.
Example
class Parentclass
{
//Overridden method
void display()
{
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
//Overriding method
void display()
{
System.out.println("Child class method");
}
void printMsg(){
//This would call Overriding method
display();
//This would call Overridden method
super.display();
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printMsg();
12
22CS202 – Java Programming (Theory Course with Lab Component)
}
}
Output:
Child class method
Parent class method
A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body). In Java, a separate
keyword abstract is used to make a class abstract. An abstract class cannot be instantiated. To
access the members of an abstract class, we must inherit it.
13
22CS202 – Java Programming (Theory Course with Lab Component)
{
int rectarea;
void Area()
{
rectarea=a*b;
System.out.println(“Area of rectangle is:“ +rectarea);
}
}
class Triangle extends Shape
{
int triarea;
void Area()
{
triarea=(int) (0.5*a*b);
System.out.println(“Area of triangle is:“ +triarea);
}
}
class Circle extends Shape
{
int circlearea;
void Area()
{
circlearea=(int) (3.14*a*a);
System.out.println(“Area of circle is:“+circlearea);
}
}
public class Demo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Area();
Triangle t=new Triangle();
t.Area();
Circle c=new Circle();
c.Area();
}
}
14
22CS202 – Java Programming (Theory Course with Lab Component)
A method which is declared as abstract and does not have implementation is known as an
abstract method. They are declared with the purpose of having the sub class provide
implementation. They must be declared within an abstract class.
abstract void Methodname(); //no body of method hence
syntax
Example
Example 1
15
22CS202 – Java Programming (Theory Course with Lab Component)
{
System.out.println ("Method of abstract class Multiply");
}
}
// Regular class extends abstract class
class AbstractMethodEx1 extends Multiply
{
// if the abstract methods are not implemented, compiler will give an error
public intMultiplyTwo (int num1, int num2)
{
return num1 * num2;
}
public intMultiplyThree (int num1, int num2, int num3)
{
return num1 * num2 * num3;
}
// main method
public static void main (String args[])
{
Multiply obj = new AbstractMethodEx1();
System.out.println ("Multiplication of 2 numbers: " + obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " + obj.MultiplyThree (5, 8, 10));
obj.show();
}
}
Output
Multiplication of 2 numbers: 500
Multiplication of 3 numbers: 400
Method of abstract class Multiply
16
22CS202 – Java Programming (Theory Course with Lab Component)
17
22CS202 – Java Programming (Theory Course with Lab Component)
Output
Hello , we are in parent method
Hello , we are in child method
Hello , we are in parent method
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java. In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Declare an interface
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static, and final by default. A class that implements an interface must implement all the methods
declared in the interface.
Syntax
interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}
18
22CS202 – Java Programming (Theory Course with Lab Component)
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Once the interface is declared, we can use it in a class using the “implements” keyword in
the class declaration. This ‘implements’ keyword appears after the class name as shown
below:
Output
The area of rectangle is 200
Multiple Inheritance
19
22CS202 – Java Programming (Theory Course with Lab Component)
Multiple inheritance in java is the capability of creating a single class with multiple super
classes. Unlike some other popular object-oriented programming languages like C++, java
does not provide support for multiple inheritance in classes.
20
22CS202 – Java Programming (Theory Course with Lab Component)
}
class multipledemo
{
public static void main(String args[])
{
result r=new result();
r.get(10,”kumar”,”Chennai”);
r.getmarks(60,70,80);
r.display();
r.displaymarks();
}
}
Output
Register number = 10
Name = kumar
Address = Chennai
Total = 210
Average = 70
Hybrid Inheritance
• In Java, the hybrid inheritance is the composition of two or more types of inheritance.
• The main purpose of using hybrid inheritance is to modularize the code into well-
defined classes. It also provides the code reusability.
• The hybrid inheritance can be achieved by using the following combinations:
• Single and Multiple Inheritance (not supported but can be achieved through
interface)
• Multilevel and Hierarchical Inheritance
• Hierarchical and Single Inheritance
• Multiple and Multilevel Inheritance
class HumanBody {
public void displayHuman() {
System.out.println("Method defined inside HumanBody class"); }
}
interface Male {
public void show();
21
22CS202 – Java Programming (Theory Course with Lab Component)
}
interface Female {
public void show();
}
public class Child extends HumanBody implements Male, Female {
public void show() {
System.out.println("Implementation of show() method defined in interfaces
Male and Female");
}
public void displayChild() {
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
}
//parent class
class GrandFather {
public void showG() {
System.out.println("He is grandfather.");
} }
//inherits GrandFather properties
class Father extends GrandFather {
public void showF() {
System.out.println("He is father.");
} }
//inherits Father properties
class Son extends Father {
public void showS() {
System.out.println("He is son.");
22
22CS202 – Java Programming (Theory Course with Lab Component)
} }
//inherits Father properties
public class Daughter extends Father {
public void showD() {
System.out.println("She is daughter.");
}
public static void main(String args[]) {
Son obj = new Son();
obj.showS(); // Accessing Son class method
obj.showF(); // Accessing Father class method
obj.showG(); // Accessing GrandFather class method
Daughter obj2 = new Daughter();
obj2.showD(); // Accessing Daughter class method
obj2.showF(); // Accessing Father class method
obj2.showG(); // Accessing GrandFather class method
} }
Hierarchical and Single Inheritance
class C {
public void disp() {
System.out.println("C"); }
}
class A extends C {
public void disp()
{
System.out.println("A");}
}
class B extends C {
public void disp() {
System.out.println("B"); }
}
public class D extends A {
public void disp() {
System.out.println("D"); }
public static void main(String args[]) {
D obj = new D();
obj.disp(); }
}
23
22CS202 – Java Programming (Theory Course with Lab Component)
•Static Methods in Interface are those methods, which are defined in the interface with
the keyword static.
• Unlike other methods in Interface, these static methods contain the complete definition
of the function and since the definition is complete and the method is static, therefore
these methods cannot be overridden or changed in the implementation class.
• Like Default Method in Interface, the static method in an interface can be defined in
the interface, but cannot be overridden in Implementation Classes.
• To use a static method, Interface name should be instantiated with it, as it is a part of
the Interface only.
When to use Interface?
• In the section on Interface, it was noted that a class that implements an interface must
implement all the interface's methods.
• It is possible, however, to define a class that does not implement all the interface's
methods, provided that the class is declared to be abstract. For example,
abstract class X implements Y {
// implements all but one method of Y
}
class XX extends X {
// implements the remaining method in Y
}
• In this case, class X must be abstract because it does not fully implement Y, but class
XX does, in fact, implement Y.
Example
24
22CS202 – Java Programming (Theory Course with Lab Component)
interface my_interface
{
static void static_fun()
{
System.out.println("In the newly created static method");
}
void method_override(String str);
}
public class Demo_interface implements my_interface
{
public static void main(String[] args)
{
Demo_interfacedemo_inter = new Demo_interface();
my_interface.static_fun();
demo_inter.method_override("In the override method");
}
@Override
public void method_override(String str)
{
System.out.println(str);
}
}
Output
In the newly created static method
In the override method
• A simple static method is defined and declared in an interface which is being called in
the main() method of the Implementation Class InterfaceDemo.
• Unlike the default method, the static method defines in Interface hello(), cannot be
overridden in implementing the class.
interface NewInterface {
// static method
static void hello()
{
System.out.println("Hello, New Static Method Here");
}
// Public and abstract method of Interface
void overrideMethod(String str);
}
// Implementation Class
public class InterfaceDemo implements NewInterface {
public static void main(String[] args)
{
InterfaceDemo interfaceDemo = new InterfaceDemo();
// Calling the static method of interface
25
22CS202 – Java Programming (Theory Course with Lab Component)
NewInterface.hello();
Output
Hello, New Static Method Here
Hello, Override Method here
• In this program, the scope of the static method definition is within the interface only.
• If same name method is implemented in the implementation class, then that method
becomes a static member of that respective class.
interface PrintDemo {
// Static Method
static void hello()
{
System.out.println("Called from Interface PrintDemo");
}
}
public class InterfaceDemo implements PrintDemo {
public static void main(String[] args)
{
// Call Interface method as Interface
// name is preceding with method
PrintDemo.hello();
// Call Class static method
hello();
}
// Class Static method is defined
static void hello()
{
System.out.println("Called from Class");
}
}
Output
Called from Interface PrintDemo
Called from Class
26
22CS202 – Java Programming (Theory Course with Lab Component)
Package is a collection of predefine classes and interface. Java provides different type of inbuilt
packages for different task. Programmer can also create own packages. All Java predefine
classes are distributed into several different package.
Advantage of Java Package
• Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
• Java package provides access protection
• Java package removes naming collision
lang Package: Lang stands for language. This package contains that class which are essential
for every java program.
Lang is the default package of java which means it is optional to import Lang package in
program
io package: io stands for input/output. This package contains that class which are essential for
input and output. Some classes of input/output package are;
util package: util stands for utility package this package contains different type of classes
related to various task.
awt package (swing): awt stands for abstract windowing tool. With the help of this package,
we can create GUI interface. This package provides many GUI tools.
27
22CS202 – Java Programming (Theory Course with Lab Component)
applet: with the help of applet function, we can create a java program which can be embedded
into HTML page by which web browser execute the java program. Web browser must be java
enabled.
Sql Package: sql stands for structure query language. This package provides a complete range
of classes which is needed for jdbc (java database connectivity). Some important classes of sql
package are:
Net package: net stands for networking. This package contains classes to implement or create
connection between two or more systems or if we want to implement client server approach
then. We can use the classes of net package.
Types of packages
➢ Programmers can define their own packages to bundle group of classes/interfaces, etc.
It is a good practice to group related classes implemented, so that a programmer can
easily determine that the classes, interfaces, enumerations, and annotations are related.
➢ Since the package creates a new namespace there is no chance for any name conflicts
with names in other packages. Using packages, it is easier to provide access control and
it is also easier to locate the related classes.
Built-in Packages
These packages consist of many classes which are a part of Java API. Some of the commonly
used built-in packages are:
1. java.lang: Contains language support classes(e.g. classed which defines primitive data
types, math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support : for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus etc.).
6. java.net: Contain classes for supporting networking operations.
28
22CS202 – Java Programming (Theory Course with Lab Component)
Creating a package
➢ While creating a package, name for the package is chosen and included in
the package statement at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that are included in the package.
➢ The package statement should be the first line in the source file.
➢ There can be only one package statement in each source file, and it applies to all types
in the file. If a package statement is not used then the class, interfaces, enumerations,
and annotation types will be placed in the current default package.
Example 1
Package Pack1
public class Demo
{
public void Show()
{
System.out.print(“Package called”);
}
}
➢ To compile the Java programs with package statements, you must use -d option as
shown below.
➢ javac -d Destination_folder file_name.java
➢ Then a folder with the given package name is created in the specified destination, and
the compiled class files will be placed in that folder.
➢ Now a package/folder with the package name will be created in the current directory
and these class files will be placed in it.
29
22CS202 – Java Programming (Theory Course with Lab Component)
Syntax
javac -d directory java_filename
Example to Compile:
javac -d Pack1 Demo.java
Example to Execute:
java Pack1.Demo
import Pack1.*;
class A
{
public static void main(String …args)
{
Demo ob1= new demo();
ob1.Show();
}
}
Example 2
Arithmetic operations using packages
package arithmetic;
public class MyMath
{
public intadd(intx,int y)
{
return x+y;
}
public intsub(intx,int y)
{
return x-y;
}
public intmul(intx,int y)
{
return x*y;
}
public double div(intx,int y)
{
return (double)x/y;
}
30
22CS202 – Java Programming (Theory Course with Lab Component)
public intmod(intx,int y)
{
return x%y;
}
}
Note: Move to parent directory, write the following file and execute it.
import arithmetic.*;
class Test
{
public static void main(String as[])
{
MyMath m=new MyMath();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
/* Output: */
13
3
40
1.6
3
Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.
For example,
If you want to use class/interface from a certain package, you can also use its fully
qualified name, which includes its full package hierarchy.
import java.util.Date;
31
22CS202 – Java Programming (Theory Course with Lab Component)
Syntax
import packageName.ClassName;
Let us look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;
import java.util.Scanner;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(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.
Syntax
import packageName.*;
Example
package myPackage;
import java.util.*;
public class ImportingExample
{
32
22CS202 – Java Programming (Theory Course with Lab Component)
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 compiler will not be able to figure out which Date class do we want. This problem can be
solved by using a specific import statement:
import java.util.Date;
import java.sql.*;
If we need both Date classes then, we need to use a full package name every time we declare
a new object of that class.
33
22CS202 – Java Programming (Theory Course with Lab Component)
Access Modifiers
Important points
2.8 Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
34
22CS202 – Java Programming (Theory Course with Lab Component)
Definitions:
• An exception is an abnormal condition that arises in a code sequence at run time.
• An exception is a runtime error.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Suppose there are 10 statements in program and there occurs an exception at statement
5, rest of the code will not be executed i.e., statement 6 to 10 will not run. If we perform
exception handling, rest of the statement will be executed.
Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.
Unchecked Exception
35
22CS202 – Java Programming (Theory Course with Lab Component)
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
If we have null value in any variable, performing any operation by the variable occurs
an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Exception Hierarchy
36
22CS202 – Java Programming (Theory Course with Lab Component)
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we cannot use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we cannot use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It does not throw an exception. It is always used
with method signature.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
37
22CS202 – Java Programming (Theory Course with Lab Component)
Example Program:
public class TryDemo
{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
finally block
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block
• Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Example
class TestFinallyBlock
{
public static void main(String args[])
{
Try
{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e)
{
System.out.println(e);
}
//executed regardless of exception occurred or not
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
38
22CS202 – Java Programming (Theory Course with Lab Component)
Output
5
finally block is always executed
rest of the code…
Example
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output
Arithmetic Exception occurs
rest of the code
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException
while the outer try block can handle the ArithemeticException (division by zero).
39
22CS202 – Java Programming (Theory Course with Lab Component)
Syntax
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
40
22CS202 – Java Programming (Theory Course with Lab Component)
}
//inner try block 2
try{
inta[]=new int[5];
going to divide by 0
java.lang.AritmeticException: / by zero
java.lang.ArrayIndexOutOfBoundException: Index 5 out of bounds for length 5
other statement
normal flow
Syntax
Example
41
22CS202 – Java Programming (Theory Course with Lab Component)
else {
System.out.println("Student Entry is Valid!!");
}
}
Output
Syntax
Example
import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
42
22CS202 – Java Programming (Theory Course with Lab Component)
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output
exception handled
normal flow...
43
22CS202 – Java Programming (Theory Course with Lab Component)
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the
size of the string
• User Defined Exception or custom exception is creating your own exception class and
throws that exception using ‘throw’ keyword. This can be done by extending the class
Exception.
• Following are few of the reasons to use custom exceptions:
• To catch and provide specific treatment to a subset of existing Java exceptions.
• Business logic exceptions: These are the exceptions related to business logic
and workflow.
• It is useful for the application users or the developers to understand the exact
problem.
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}
The keyword “throw” is used to create a new Exception and throw it to the catch block.
Example:
44
22CS202 – Java Programming (Theory Course with Lab Component)
45