0% found this document useful (0 votes)
14 views37 pages

UNIT-3 OOP Lecture Notes

This document covers Object Oriented Programming concepts in Java, focusing on interfaces, their declaration, implementation, and advantages such as achieving abstraction and supporting multiple inheritance. It also discusses Java packages, their structure, access methods, and the importance of the CLASSPATH environment variable for locating class files. Additionally, it highlights the differences between classes and interfaces, including the introduction of default methods in interfaces since Java 8.

Uploaded by

bhargavialluri30
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)
14 views37 pages

UNIT-3 OOP Lecture Notes

This document covers Object Oriented Programming concepts in Java, focusing on interfaces, their declaration, implementation, and advantages such as achieving abstraction and supporting multiple inheritance. It also discusses Java packages, their structure, access methods, and the importance of the CLASSPATH environment variable for locating class files. Additionally, it highlights the differences between classes and interfaces, including the introduction of default methods in interfaces since Java 8.

Uploaded by

bhargavialluri30
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/ 37

UNIT-3 – Object Oriented Programming

❖ Interface
✓ An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
✓ Interfaces can have abstract methods and variables. It cannot have a method
body.
✓ Java Interface also represents the IS-A relationship.
Why use Java interface?
There are mainly three reasons to use interface. They are
1. It is used to achieve total abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling (means, that the classes are
independent of each other)

Note 1: Interfaces are used to implement abstraction. So, the question arises why
use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public, and static.
How to 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.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 1


UNIT-3 – Object Oriented Programming

✓ A class that implements an interface must implement all the methods


declared in the interface.

Syntax:

Internal addition by the compiler


✓ The Java compiler adds public and abstract keywords before the interface
method.
✓ Moreover, it adds public, static, and final keywords before data members.

The relationship between classes and interfaces

✓ A class extends another class, an interface extends another interface, but


a class implements an interface.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 2


UNIT-3 – Object Oriented Programming

Java Interface Example1:


✓ To implement an interface, we use keyword implements.
// Java program to demonstrate working of interface.
1. import java.io.*;
2. interface In1 // A simple interface
3. {
final int a = 10; // public, static, and final
void display(); // public and abstract
4. }
5. class TestClass implements In1 // A class that implements the interface.
6. {
public void display() // Implementing the capabilities of interface
{
System.out.println("Java For LBRCE");
}
7. public static void main (String[] args)
8. { Output:
9. TestClass t = new TestClass();
10. t.display(); Java For LBRCE
11. System.out.println(a); } } 10
Java Interface Example2: Drawable
✓ In this example, the Drawable interface has only one method. Its
implementation is provided by Rectangle and Circle classes.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 3


UNIT-3 – Object Oriented Programming

✓ In a real scenario, an interface is defined by someone else, but its


implementation is provided by different implementation providers.
Moreover, it is used by someone else.
✓ The implementation part is hidden by the user who uses the interface.
1. interface Drawable{ //Interface declaration: by first user
2. void draw();
3. }
4. //Implementation: by second user
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle implements Drawable{
9. public void draw(){System.out.println("drawing circle");}
10. }
11. //Using interface: by third user
12. class TestInterface1{
13. public static void main(String args[]){
14. Drawable d=new Circle(); //Upcasting
15. d.draw();
16. } }
Output:
drawing circle

Multiple inheritance in Java by interface

✓ If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 4


UNIT-3 – Object Oriented Programming

Example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7(); Output:
13. obj.print();
14. obj.show(); Hello
15. } } Welcome

✓ Multiple inheritance is not supported in the case of class because of


ambiguity. However, it is supported in case of an interface because there is
no ambiguity.

✓ It is because its implementation is provided by the implementation class.

Example:
1. interface Printable{ // Single class can be able to implement
2. void print(); multiple Interfaces which are having same
3. }
method print(). And there is no ambiguity.
4. interface Showable{
5. void print();
6. }

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 5


UNIT-3 – Object Oriented Programming

7. class TestInterface3 implements Printable, Showable{


8. public void print(){System.out.println("Hello");}
9. public static void main(String args[]){
10. TestInterface3 obj = new TestInterface3(); Output:
11. obj.print();
12. } } Hello

Interface inheritance
✓ A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }

7. class TestInterface4 implements Showable{


8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print(); Output:
14. obj.show();
15. } } Hello
Welcome
Java 8 Default Method in Interface

✓ Since Java 8, we can have method body in interface. But we need to make it
default method.

Example:

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 6


UNIT-3 – Object Oriented Programming

1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. } Output:
14.}
default method
drawing rectangle

Differences between Class and an Interface:


S.
Class Interface
no
The keyword used to create a class is The keyword used to create an interface is
1.
“class” “interface”
Interface can have only abstract methods.
A class can have both an abstract as
2. Java 8 onwards, it can have default
well as concrete methods.
methods.
3. A class can be instantiated i.e., An Interface cannot be instantiated i.e.,

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 7


UNIT-3 – Object Oriented Programming

objects of a class can be created. objects cannot be created.


It can be inherited by a class by using the
It can be inherited by another class keyword ‘implements’ and it can be
4.
using the keyword ‘extends’. inherited by an interface using the
keyword ‘extends’.
Multiple Inheritance is NOT
5. Interface supports Multiple Inheritance.
supported.
final, non-final, static, and non-static Only static and final variables are
6.
variables supported. permitted.
Interface cannot implement an interface;
7. A class can implement an interface.
it can extend an interface.
A class can have any type of
8. Interface can only have public members.
members like private, public.
A class can have constructor
9. Interface cannot have a constructor.
methods.

❖ Java Packages
✓ 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.
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.
Example: The package keyword is used to create a package in java.
1. //save as Simple.java
Output:
Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE Welcome to package 8
UNIT-3 – Object Oriented Programming

2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package"); } }
Syntax to compile java package: javac -d directory javafilename
Eg: javac -d . Simple.java
✓ The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination.
✓ The .(dot) represents the current folder.

How to run java package program


✓ Need to use fully qualified name e.g. mypack.Simple to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple

❖ Accessing a package from another package


✓ There are three ways to access the package from outside the package.
1. import packagename.*;
2. import packagename.classname;
3. fully qualified name.
1) Using packagename.*
✓ If you use packagename.* then all the classes and interfaces of this package
will be accessible but not subpackages.
✓ The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example:
1. //save by A.java
2. package pack;
3. public class A{

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 9


UNIT-3 – Object Oriented Programming

4. public void msg(){


5. System.out.println("Hello");}
6. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A(); Output:
8. obj.msg();
9. } } Hello

2) Using packagename.classname
✓ If you import packagename.classname then only declared class of this
package will be accessible.
Example:
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){
5. System.out.println("Hello");}
6. }

1. //save by B.java
2. package mypack;
3. import pack.A;
4. class B{
5. public static void main(String args[]){ Output:
6. A obj = new A();
7. obj.msg(); Hello
8. } }
3) Using fully qualified name

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 10


UNIT-3 – Object Oriented Programming

✓ If you use fully qualified name, then only declared class of this package will
be accessible.

✓ Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class

✓ Fully qualified name is packagename.classname is directly using in a class


of another package.

Example:
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){
5. System.out.println("Hello");}
6. }

1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A(); //using fully qualified name
6. obj.msg();
7. } } Output:

Note: Hello
✓ If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages.
✓ Hence, you need to import the subpackages as well.

❖ Subpackages in Java
✓ Package inside the package is called the subpackage.
✓ It should be created to categorize the package further.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 11


UNIT-3 – Object Oriented Programming

✓ Sun Microsystem has defined a package named java that contains many
classes like System, String, Reader, Writer, Socket etc.
✓ These classes represent a group.
E.g., Reader and Writer classes are for Input/Output operation,
Socket and ServerSocket classes are for networking etc and so on.
✓ So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc.
✓ And put the Input/Output related classes in io package, Server and
ServerSocket related classes in net packages and so on.
✓ The standard of defining package is domain.company.package.
E.g., com.lbrce.eee or org.sssit.dao.

Example:
1. package com.lbrce.eee;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. } } Output:
To Compile: javac -d . Simple.java Hello subpackage
To Run: java com.lbrce.eee Simple

❖ Directory structure (Understanding CLASSPATH)


✓ The package name is closely associated with the directory structure used to
store the classes.
✓ The classes belonging to a specific package are stored together in the same
directory. Furthermore, they are stored in a sub-directory structure specified
by its package name.
✓ For example, the class Circle of package com.zzz.project1.subproject2 is
stored as “$BASE_DIR\com\zzz\project1\subproject2\Circle.class”,
where $BASE_DIR denotes the base directory of the package.
✓ Clearly, the “dot” in the package name corresponds to a sub-directory of the
file system.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 12


UNIT-3 – Object Oriented Programming

✓ The base directory ($BASE_DIR) could be located anywhere in the file


system.
✓ Hence, the Java compiler and runtime must be informed about the location
of the $BASE_DIR to locate the classes.
✓ This is accomplished by an environment variable called CLASSPATH.
✓ CLASSPATH is like another environment variable PATH, which is used
by the command shell to search for the executable programs.
✓ CLASSPATH describes the location where all the required “.class” files are
available which are used in the application.
✓ Java Compiler and JVM use CLASSPATH to locate the required files.
✓ If the CLASSPATH is not set, Java Compiler will not be able to find the
required files and hence will throw the following error.
Error: Could not find or load main class <class name>
Setting CLASSPATH:
CLASSPATH can be set by any of the following ways:
1. CLASSPATH can be set permanently in the environment:
✓ In Windows, choose Control Panel -> System -> Advanced ->
Environment Variables -> choose “System Variables” (for all the users)
or “User Variables” (only the currently login user) -> choose “Edit” (if
CLASSPATH already exists) or “New” -> Enter “CLASSPATH” as the
variable name -> Enter the required directories and JAR files (separated by
semicolons) as the value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-
api.jar”).
✓ Take note that you need to include the current working directory (denoted by
‘.’) in the CLASSPATH.
✓ To check the current setting of the CLASSPATH, issue the following
command: > SET CLASSPATH
2. CLASSPATH can be set temporarily for that CMD shell session by issuing the
following command:

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 13


UNIT-3 – Object Oriented Programming

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar


3. Instead of using the CLASSPATH environment variable, you can also use the
command-line option -classpath or -cp of the javac and java commands.
Example:
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
Note: PATH is used to define where the system can find the executable(.exe) files
and CLASSPATH is used to specify the location of .class files.

❖ Exception Handling
Exception:
✓ An 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.
✓ Exception occurs in the code written by the developers.
✓ When executing Java code, different errors can occur.
➢ coding errors made by the programmer,
➢ errors due to wrong input, or other unforeseeable things.
✓ When an error occurs, Java will normally stop and generate an error
message.
✓ The technical term for this is: Java will throw an exception (throw an error).
✓ When an error is detected, an exception is thrown.
✓ Any exception that is thrown must be caught by the exception handler.
✓ If the programmer has forgotten to provide an exception handler, the
exception will be caught by the catch-all exception handler provided by the
system.
Advantages of Exceptions
✓ It separates error handling code from regular code.
✓ It could propagate error reporting up the call stack of methods.
✓ The grouping or categorizing of exceptions is a natural outcome of the class
hierarchy.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 14


UNIT-3 – Object Oriented Programming

Example of Exception
1. import java.util.Scanner;
2. public class ExcptionExample
3. {
4. public static void main(String args[])
5. {
6. Scanner sc = new Scanner(System.in);
7. System.out.print("Enter a number: ");
8. int number = sc.nextInt();
9. System.out.println("You have entered: "+number);
10. } }
✓ Run the above program and enter a float value deliberately to generate an
exception.
Output:

✓ It shows the InputMismatchException. Because the program accepts an


integer value.
✓ Observe that the next statement is skipped, and the program is terminated.
✓ In Java, Exception and Error both are subclasses of the Java Throwable
class that belongs to java.lang package.

Error Vs Exception:
✓ Error is an action that is inaccurate or incorrect according to syntax.
✓ It indicates a serious problem, that mainly occur due to the lack of system
resources. It cannot be caught or handled.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 15


UNIT-3 – Object Oriented Programming

✓ An example of errors is OutOfMemoryError, LinkageError, etc. are the


subclasses of the Error class.
Example of Error
1. public class ErrorExample {
2. public static void main(String args[]) {
3. recursiveDemo(10); }
4. public static void recursiveDemo(int i) {
5. while(i!=0)
6. {
7. i=i+1;
8. recursiveDemo(i);
9. } } }
Output:
✓ On running the program, we get the StackOverflowError, not an exception.

Exception Hierarchy
✓ All exception and errors types are sub classes of class Throwable, which is
base class of hierarchy.
✓ One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. NullPointerException is an
example of such an exception.
✓ Another branch, Error are used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself (JRE).
StackOverflowError is an example of such an error.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 16


UNIT-3 – Object Oriented Programming

Types of exceptions
✓ There are two types of exceptions in Java:
1) Checked exceptions :
✓ These are the exceptions that are checked at compile time.
✓ Compiler checks them during compilation to see whether the programmer
has handled them or not.
✓ If these exceptions are not handled/declared in the program, you will get
compilation error.
Example:
Consider the following Java program that opens the file at location “C:\test\a.txt”
and prints the first three lines of it.
The program does not compile, because the function main() uses FileReader() and
FileReader() throws a checked exception FileNotFoundException.
It also uses readLine() and close() methods, and these methods also throw checked
exception IOException.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 17


UNIT-3 – Object Oriented Programming

import java.io.*;
class Example_checked {
public static void main(String[] args) {
// Reading file from path in local directory
FileReader file = new FileReader("C:\\test\\a.txt");
// Creating object as one of ways of taking input
BufferedReader fileInput = new BufferedReader(file);
// Printing first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
// Closing file connections using close() method
fileInput.close();
} }
Output:

✓ To fix the above program, we either need to specify a list of exceptions


using throws, or we need to use a try-catch block.

2) Unchecked exceptions :
✓ Runtime Exceptions are also known as Unchecked Exceptions.
✓ These exceptions are not checked at compile-time, so compiler does not
check whether the programmer has handled them or not.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 18


UNIT-3 – Object Oriented Programming

✓ But it is the responsibility of the programmer to handle these exceptions and


provide a safe exit.
✓ For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
✓ Compiler will never force you to catch such exception or force you to
declare it in the method using throws keyword.
Example:
// Java Program to Illustrate Un-checked Exceptions
class Example_Unchecked {
public static void main(String args[]) {
// Here we are dividing by 0 which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1

Exception handling :
1) try block
✓ The try block contains set of statements where an exception can occur.
✓ While writing a program, if there are certain statements in a program can
throw an exception, enclosed them in try block and handle that exception.
Syntax of try block : try {
//statements that may cause an exception
}
2) catch block

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 19


UNIT-3 – Object Oriented Programming

✓ Catch block is used to handle the uncertain condition of try block.


✓ A try block is always followed by a catch block, which handles the
exception that occurs in associated try block.
✓ A single try block can have several catch blocks associated with it.
✓ When an exception occurs in try block, the corresponding catch block that
handles that exception executes.
✓ If an exception occurs in try block, then the control of execution is passed to
the corresponding catch block.
Syntax of try - catch blocks :
try
{
//statements that may cause an exception
}
catch ( exception(type) e(object) )
{
//error handling code
}

Example: try catch block


✓ A single try block can have multiple catch blocks associated with it, you
should place the catch blocks in such a way that the generic exception
handler catch block is at the last (see in the example below).
✓ The generic exception handler can handle all the exceptions, but you should
place is at the end, if you place it at the before all the catch blocks then it
will display the generic message.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw exception, so we
handled it by placing these statements inside try and handled the
exception in catch block
*/

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 20


UNIT-3 – Object Oriented Programming

num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}

catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception occurs in
try block */
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle all
the exceptions. This will execute if the exception is not handled by
previous catch blocks. */
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
} }

Output:
You should not divide a number by zero
I'm out of try-catch block in Java.

Multiple catch blocks :


The following are the rules about multiple catch blocks –
1. A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or
NullPointerException or any other type of exception, this handles all of
them.
2. If no exception occurs in try block, then the catch blocks are completely
ignored.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 21


UNIT-3 – Object Oriented Programming

3. Corresponding catch blocks execute for that specific type of exception:


catch(ArithmeticException e) is a catch block that can hanlde
ArithmeticException, catch(NullPointerException e) is a catch block that
can handle NullPointerException.
4. If there are multiple catch blocks and these catch blocks executes
sequentially when an exception occurs in try block.
5. Which means if you put the last catch block ( catch(Exception e)) at the first
place, just after try block then in case of any exception this block will
execute as it can handle all exceptions.
6. So generic catch block should be placed at the last to avoid such situations.
Example :
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block..."); } }
Output:
Warning: ArithmeticException

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 22


UNIT-3 – Object Oriented Programming

Out of try-catch block...

Catching multiple exceptions :


Let us take an example to understand how to handle multiple exceptions.
import java.util.*;
import java.lang.*;
class Example{
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the value for num1: ");
int num1 = s.nextInt(); int num2 = 10;
try{
int arr[]=new int[7];
arr[10]=10/num1;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
System.out.println("Out of the try-catch block");
int sum = num1+num2;
System.out.println("Sum of num1 and num2 is : " +sum);
}
}
Output:

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 23


UNIT-3 – Object Oriented Programming

✓ In the above example, if num1 is a positive number other than 0, then


exception is access arr[10], so corresponding
ArrayIndexOutOfBoundsException executes.

✓ If num1 is 0, then corresponding ArithmeticException executes. After that,


all the other statements out of try- catch blocks will executes.
Nested try - catch block
✓ When a try catch block is present in another try block then it is called the
nested try catch block.
✓ Each time a try block does not have a catch handler for a exception, then the
catch blocks of parent try block are inspected for that exception, if match is
found that that catch block executes.
✓ If neither catch block nor parent catch block handles exception then the
system generated message would be shown for the exception, like what we
see when we do not handle exception.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 24


UNIT-3 – Object Oriented Programming

Syntax of Nested try Catch


....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
Example 1 :
class NestingDemo{
public static void main(String args[])
{
//main try-block
try{
//try-block2
try{
//try-block3
try{

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 25


UNIT-3 – Object Oriented Programming

int arr[]= {1,2,3,4};


/* Trying to display the value of an element which does
not exist. The code should throw an exception */
System.out.println(arr[10]);
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}

catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
}
}
Output:
ArrayIndexOutOfBoundsException handled in main try-block
✓ As you can see that the ArrayIndexOutOfBoundsException occurred in the
grandchild try-block3.
✓ Since try-block3 is not handling this exception, the control then gets
transferred to the parent try-block2 and looked for the catch handlers in try-
block2.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 26


UNIT-3 – Object Oriented Programming

✓ Since the try-block2 is also not handling that exception, the control gets
transferred to the main (grandparent) try-block where it found the
appropriate catch block for exception.
✓ This is how the nesting structure works.
Observation:
If there an exception in try block 2 then execution of try block 3 is skipped and
corresponding catch block of try block 2 is executed and will get output as
Arithmetic Exception handled in try-block2.
Example 2 :
class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 27


UNIT-3 – Object Oriented Programming

catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement...");
}
}
Output:

✓ The above example shows how the nested try block works. There are two
try-catch blocks inside main try block’s body. Marked them as block 1 and
block 2.
✓ Block 1: It divided an integer by zero and it caused an ArithmeticException,
since the catch of block1 is handling ArithmeticException "Exception: e1"
displayed.
✓ Block 2 : In block2, ArithmeticException occurred but block 2 catch is only
handling ArrayIndexOutOfBoundsException so in this case control jump to
the Main try-catch(parent) body and checks for the ArithmeticException
catch handler in parent catch blocks.
✓ Since catch of parent try block is handling this exception, the message
“Inside parent try catch block” displayed as output.
✓ Parent try Catch block: No exception occurred here so the “Next
statement...” displayed.
✓ The important point to note here is that whenever the child catch blocks are
not handling any exception, the jumps to the parent catch blocks, if the
exception is not handled there as well then the program will terminate
abruptly showing system generated message.
Finally block:

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 28


UNIT-3 – Object Oriented Programming

✓ A finally block contains all the crucial statements that must be executed
whether exception occurs or not.
✓ The statements present in this block will always execute regardless of
whether exception occurs in try block or not such as closing a connection,
stream etc.
Syntax of Finally block
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
Example:
class finally_exam
{
public static void main(String args[])
{
try
{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException");
}
finally
{
System.out.println("finally block");
}

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 29


UNIT-3 – Object Oriented Programming

System.out.println("Out of try-catch-finally block"); }


Output:

“throw” exception :
✓ In Java we have already defined exception classes such as
ArithmeticException, NullPointerException, ArrayIndexOutOfBounds
exception etc.
✓ These exceptions are set to trigger on different-2 conditions. For example
when we divide a number by zero, this triggers ArithmeticException, when
we try to access the array element out of its bounds then we get
ArrayIndexOutOfBoundsException.
✓ We can define our own set of conditions or rules and throw an exception
explicitly using throw keyword.
✓ For example, we can throw ArithmeticException when we divide number by
5, or any other numbers, what we need to do is just set the condition and
throw any exception using throw keyword. Throw keyword can also be used
for throwing custom exceptions,
Syntax :
throw new <exception_class>(“<error message>");
For example:
throw new ArithmeticException("dividing a number by 5 is not
allowed in this program");
Example:
Write a Java program, where we need to only register the students when their
age is less than 12 and weight is less than 40, if any of the condition is not met
then the user should raise an appropriate Exception with the warning message
“Student is not eligible for registration”.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 30


UNIT-3 – Object Oriented Programming

public class ThrowExample {


static void checkEligibilty(int stuage, int stuweight){
if(stuage<12 && stuweight<40) {
throw new ArithmeticException("Student is not eligible for
registration"); }
else { System.out.println("Student Entry is Valid!!");
}}
public static void main(String args[])
{
System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}}
Output:

Example:
import java.io.*;
class thr {
void sample() {
try {
System.out.println("Inside Sample()");
throw new NullPointerException("This is My data.."); }
catch(NullPointerException ne) {
System.out.println(ne); }
finally {
System.out.println("Close All...");
}}}

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 31


UNIT-3 – Object Oriented Programming

c lass thrw {
Public static void main(String args[])
{
thr t =new thr();
t.sample();
}}

Throws clause
✓ As we know that there are two types of exception checked and unchecked.
Checked exception (compile time force you to handle them, if you don’t
handle them then the program will not compile.
✓ On the other hand unchecked exception Runtime doesn’t get checked during
compilation.
✓ Throws keyword is used for handling checked exceptions . By using throws
we can declare multiple exceptions in one go.
using throws, we can declare multiple exceptions
public void myMethod()
{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}}
The code will become unnecessary long and will be less-readable

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 32


UNIT-3 – Object Oriented Programming

Alterative – using throws keyword


public void myMethod() throws ArithmeticException,
NullPointerException {
// Statements that might throw an exception
}
public static void main(String args[]) {
try {
myMethod();
}
catch (Exception e) {
// Exception handling statements
}}
Example: Throwing Multiple Exceptions
import java.io.*;
class Main {
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
// code that may produce NullPointerException
………
// code that may produce IOException
………
// code that may produce InvalidClassException
……… }
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1){
System.out.println(e1.getMessage());
} catch(InvalidClassException e2){
System.out.println(e2.getMessage()); } } }

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 33


UNIT-3 – Object Oriented Programming

User defined Exception :


✓ Custom exception or user-defined exception are used to customize the
exception according to user need.
✓ Using the custom exception, we can have your own exception and message.
✓ In order to create custom exception, we need to extend Exception class that
belongs to java.lang package.
✓ The exception is thrown using throw keyword.
✓ Exception is obtained using “getMessage()” function on the object created.
Reasons to use custom exceptions:
✓ To catch and provide specific treatment to a subset of existing Java
exceptions.
✓ It is useful for the application users or the developers to understand the exact
problem.
Example 1: User Defined Exception
// I. Class that represents user-defined exception
class UserException extends Exception {
public UserException(String s) {
// Call constructor of parent Exception
super(s); } }
// II. A Class that uses above UserException
public class UsingException {
public static void main(String args[]) {
try {
// III. Throw an object of user defined exception
throw new UserException(“Exception Raised");
}
catch (UserException ex) {
System.out.println("Caught the Exception");
// IV. Print the message from UserException object
System.out.println(ex.getMessage()); } } }

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 34


UNIT-3 – Object Oriented Programming

Example 3: User Defined Exception


class InvalidAgeException extends java.lang.Exception {
public InvalidAgeException(String str) {
super(str); } }
public class TestCustomException1 {
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18) {
throw new InvalidAgeException("age is not valid to vote"); }
else {
System.out.println("welcome to vote"); } }
// main method
public static void main(String args[]) {
try {
// calling the method
validate(13);
}
catch (InvalidAgeException ex) {
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex.getMessage()); }
System.out.println("rest of the code..."); } }

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 35


UNIT-3 – Object Oriented Programming

Assertion :
✓ Assertion is a statement in java. It can be used to test your assumptions
about the program.
✓ While executing assertion, it is believed to be true.
✓ If it fails, JVM will throw an error named AssertionError.
✓ It is mainly used for testing purpose.
Syntax of using Assertion:
There are two ways to use assertion.
First way is: assert expression;
Second way is: assert condition : expression;
Enable The Assertion :
To enable the assertion, -ea or -enableassertions switch of java must be used.
Compile : javac filename.java
Run it by: java -ea classname

Example :
import java.util.*;

class AssertionExample {
public static void main( String args[] ) {
Scanner s = new Scanner( System.in );
System.out.print("Enter ur age ");

int value = s.nextInt();


assert value>=18:" Not valid";

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 36


UNIT-3 – Object Oriented Programming

System.out.println("value is "+value); } }

Assertion Examples:
1. Write a Java program to check a given integer is odd, if the given integer is
even must raise an AssertionError otherwise produce an appropriate
message as given integer is odd.
2. Write an Exception handling Program which include the Assert Statement in
try block and handle the raised exception from assert statement.
Where to use Assertions
• Arguments to private methods. Private arguments are provided by
developer’s code only and developer may want to check his/her assumptions
about arguments.
• Conditional cases.
• Conditions at the beginning of any method.
Where not to use Assertions
• Assertions should not be used to replace error messages
• Assertions should not be used to check arguments in the public methods as
they may be provided by user.
• Assertions should not be used on command line arguments.

Jagadeeswara Rao P, Asst. Prof, CSE, LBRCE 37

You might also like