0% found this document useful (0 votes)
4 views31 pages

Java (Sem 4) Unit 3

Unit 3 of the OOP using Java course covers key concepts such as polymorphism, interfaces, packages, and exception handling. It explains method overloading and overriding, final variables, abstract methods and classes, and the structure of interfaces. Additionally, it discusses multiple inheritance through interfaces and the creation and usage of user-defined packages in Java.

Uploaded by

kvdc2005
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)
4 views31 pages

Java (Sem 4) Unit 3

Unit 3 of the OOP using Java course covers key concepts such as polymorphism, interfaces, packages, and exception handling. It explains method overloading and overriding, final variables, abstract methods and classes, and the structure of interfaces. Additionally, it discusses multiple inheritance through interfaces and the creation and usage of user-defined packages in Java.

Uploaded by

kvdc2005
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/ 31

OOP using Java-II BSC(sem-4)-All Comp.

Groups UNIT – 3

Unit – 3
 Polymorphism
 Interfaces
 Packages
 Exception Handling
__________________________________________________________________________

Q) Explain Method Overloading (Static/Compile Time Polymorphism) and


Method Over Riding(Dynamic/Run Time Polymorphism).
(OR)
Explain types of Polymorphism in Java .

A) Since Java is object-oriented language , it supports Polymorphism . It means “ one can have many forms “.
In java, it is implemented with concepts “Method Over Loading and Method OverRiding“.

**Method Overloading(Static/Compile Time Polymorphism) : It is process of defining the same method


with different parameter lists.

Here different parameter list means changing the number or type of parameters.

Sometimes if required we can change the definition also, i.e. a single method performs different operations.

Example program

class Shape
{
void area(float radius) // one float parameter
{
System.out.println(“Area of Circle : “+ (3.14*radius *radius));
}

void area(int length , int width) // same method with two int parameters
{
System.out.println(“Area of Rectangle : “+ (length * width));
}
}
class MOverLoad
{
public static void main ( String args[ ] )
{
Shape x = new Shape();
x.area(7.5 f ); // calculates area of circle
x.area(10 , 20 ); // same method calculates area of Rectangle also
}}

output : Area of circle : 176.625000

Area of Rectangle : 200

Krishnaveni Degree College :: Narasaraopet page 1


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

- Polymorphism(Method OverLoading) with private ,static and final methods :

We can perform Method overloading for the methods which are declared as private ,static and final also as shown in
below Example code :

class Shape
{
private static final void area(float radius) // one float parameter
{
System.out.println(“Area of Circle : “+ (3.14*radius *radius));
}

private static final void area(int length , int width) // same method with two int params
{
System.out.println(“Area of Rectangle : “+ (length * width));
}
}

**Method OverRiding( Dynamic/ Run Time Polymorphism) : It is process of change (override /change ) the
definition of Super class method in its Sub class .

In this process , we does not change return type and parameter list.

The following program shows the method overriding :

class A
{
int x ;
void display( )
{
System.out.println(“From class A , x = “+x);
}
definition of }
display ( ) class B extends A
method changed in {
sub class void display( )
{
System.out.println(“ From class B, x*x =“ +(x*x));
System.out.println(“Method Overriding”);
}
}

classOverRide
{
public static void main(String args[ ])
{
A a=new A( );
a.x=5;
a.display( );

B b =new B( );
b.x=5;
b.display( );
}
}
Output : From class A , x = 5
From class B , x*x = 25 Method Overriding

Krishnaveni Degree College :: Narasaraopet page 2


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

- Polymorphism(Method OverRiding) with private ,static and final methods :

We can perform Method OverRiding for static methods but not possible with private and final methods

Static method (No Error) private and final methods (Give Error)

class A class A
{ {
static void display( ) private final void display( )
{ {
System.out.println(“From class A , x = “+x ) ; System.out.println(“From class A , x = “+x ) ;
} }
} }
class B extends A class B extends A
{ {
static void display( ) private final void display( )
{ {
System.out.println(“From class B , x*x = “+(x*x) ) ; System.out.println(“From class B , x*x = “+(x*x) ) ;
System.out.println(“Method Overriding”); System.out.println(“Method Overriding”);
} }
} }

………………………………………………………………………………………………………………………………………………………….

Q) Explain about final variables ,final methods, final classes and finalizer

Generally using Inheritance concept , we can use and change the variables and methods of Super class in its
related Subclasses. But we can restrict (stop) this changing of superclass properties in subclasses by using final
keyword.

final variables :
 The variables declared with final keyword are called “final variables”.
 These cannot be changed in subclasses.

final methods :
 The methods declared with final keyword are called “final methods”.
 These cannot be changed in subclasses.

The following program shows the working of final variables and methods :
class A
{
final int x ;
final void display( )
{
System.out.println(“x : “+x);
}
gives error when }
display ( ) class B extends A
method changed {
in subclass void display( )
{
System.out.println(“x * x : “ +(x*x));
System.out.println(“Method Overriding”);
}}

Krishnaveni Degree College :: Narasaraopet page 3


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

As shown above , the Superclass properties which are declared with final cannot be changed in its Sub classes .
final classes :
 The classes declared with final keyword are called “final classes”
 These classes cannot be inherited to Subclasses.
Ex : final class A
{
______
______
}
class B extends A /* gives error because A is final class */
{
______
______
}

finalize( ) / finalizer / Destructor :


 finalize( ) is predefined method. It is used to release the resources hold by the objects .
 It is opposite to constructor so it is also called as “Destructor” or finalizer method.
_______________________________________________________________________________________________

Q) Explain about abstract methods and abstract classes.

abstract methods :
 The methods which are declared with “abstract” keyword are called “abstract methods”.
 These must be overridden (redefined) in its related Subclasses.
 These have only declaration (return type and parameter list) not definition(body of method)

abstract classes :
 The classes which have abstract methods are called “abstract classes”.
 These are declared with abstract keyword and must be Sub classed.

The following program shows abstract classes and methods :

abstract class A
{
abstract void display( ) ; //only method declaration
abstract method }
display ( ) class B extends A
defined {
in subclass void display( )
{
System.out.println(“welcome”);
System.out.println(“abstract method”);
}
}
As shown above, the methods which are declared as “abstract” are must be defined in related subclasses.
 Rules to declare abstract methods and classes :
 we cannot create objects directly for abstract classes.
 abstract methods should be defined in related Sub classes.
 cannot declare constructors and static methods as abstract.
_____________________________________________________________________________________________________

Krishnaveni Degree College :: Narasaraopet page 4


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Chapter -2 INTERFACES

Q )Explain about Interfaces (or) Explain declaring, implementing and Extending of Interfaces.

Interface : It is also like class which is combination of variables and methods .But contains only final variables and
abstract methods.

The Interfaces are developed and used in java programs are as follows :
 Declaring a Interface
 Implementing a Interface
 Extending a Interface

Declaring a Interface : Interfaces are declared by using keyword “interface” as follows :

Syntax : interface Name_of_Interface


{
final variables ;
abstract methods ;
}

Implementing /Accessing aInterface :


 To use the variables and methods of an Interface , it should be implemented(defined).
 For this we define a new class and special keyword “ implements “ as follows

Syntax : class Name_of_Class implements Name_of_Interface


{
---------
---------
}
The following program shows how to declare and implement an interface :

/* Declaring Interface */

interface A
{
final static int x=10 ;
public void display ( ) ;
}

/* implementing Interface */

class B implements A
{
public void display ( )
{
System.out.println(“x value = “ + x) ;
} }
}

/* main class definition */


class InterfaceEx
{
public static void main( String args[ ] )
{

Krishnaveni Degree College :: Narasaraopet page 5


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

B b=new B( );
A a;
a=b;
a.display( );
}
}

Output : x value =10

Extending a Interface :
 Like classes , Interfaces are participated in Inheritance by using extends keyword.
 Then the variables and methods of an Interface are accessed by another Interface.

ex : interface A
{
int x =10;
void displayA( );
}
interface B extends A /* interface B is derived from interface A */
{
int y=20;
void displayB( );
}
class C implements B
{
void displayA ( )
{
System.out.println(“x value = “ + x) ;
}
void displayB ( )
{
System.out.println(“y value = “ + x) ;
}
}
Since interface B is derived from A , when class C implementing interface Bthe variables and methods of interface A
also used by class C through B .
________________________________________________________________________________________

Q) Explain Multiple Inheritance in Java using Interfaces.

Multiple Inheritance : If Single Sub Class is derived from more than one Super Class , it is
called “Multiple Inheritance “ . It is represented as :

Super Class A B Super Class

Here the Sub Class C is derived from two Super Classes A and B .

In Java , the Multiple Inheritance is not possible with classes. But by using “ Interfaces“ concept, we can develop
Multiple Inheritance as follows :

Krishnaveni Degree College :: Narasaraopet page 6


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

interface A
{
int x=10 ;
public void displayA ( ) ;
}

class B
{
int y=20;
void displayB ( )
{
System.out.println(“y value = “ + y) ;
}
}
class C extends B implements A /* C derived from A and B */
{
public void displayA ( )
{
System.out.println(“x value =”+ x) ;
}
}

/* main class definition */

class Multiple
{
public static void main( String args[ ] )
{
C k =new C ( );

k.displayA( ); /* class C use methods of both A and B */


k.displayB( );
}
}
Output : x value =10
y value =20

As shown above , the class C is derived from two (more than one )super classes A and B . similarly , class C can use the
properties of both A and B.
In this way we can develop Multiple Inheritance using Interfaces in Java.

___________________________________________________________________________________________________________

Krishnaveni Degree College :: Narasaraopet page 7


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Chapter -3 PACKAGES

Q) Explain about Different types of Packages in Java.


( or )
Explain about creation of User defined Packages in Java.

Package :Package is the group of classes , interfaces etc. These classes are used by
other programs by importing that package.
Types of Packages :In Java, Packages are two types. They are :
1.System Defined(Java API) Built-in Packages
2. User Defined Packages

1.System Defined(Java API) Packages: These are provided by Java


API(Application Programing Interface). They are :
 java.lang: It contains classes for language support.
 java.util : It contains Vector classes.
 java.io : It contains classes for input – output related operations.
 java.awt : It contains classes to develop Buttons , Menus etc.
 java.net : It contains classes for Networking Operations.
 java.applet : It contains classes to develop Applet programs.

2. User Defined Packages :These packages are created by programmers. The


process creating and usage of User Defined packages as follows :

 Creating a Package
 Adding a class to existing Package
 Importing Packages
 Creating a Package : It is the process of declaring a package name and defining
classes for that package.
To declare a package we a special keyword “package” as follows :

Syntax : package Package_name ;

public class Class_name


{
variables ;
methods ;
}

Note : open “Notepad” and type the code as follows

Krishnaveni Degree College :: Narasaraopet page 8


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Example : package P1 ;

public class A
{
public int x ;
public void displayA( )
{
System.out.println(“ From class A in pack P1 , x = “ + x );
}
}

In the above program, we create an User Defined package ‘ P1 ’ and it contains a


class ‘ A ‘ .

 Saving the Package : To save a Package program , we follow below steps :


 create a new folder with name same as package name ( Ex : P1 )
 save the file with name same as “public class name.java” in folder
P1. Ex : A.java

 Compiling the Package : To compile above package program, goto folder P1


and compile as follows at command prompt.
C:\> P1> javac A.java (or) C:\> javac –d . A.java

 Adding Interface(or)class to an Existing Package :

It is possible to add one more class/interface to the same Package. For Example ,
the above package ‘P1 ’ contains class A. Now we can add another an interface I to
the package P1
For this ,open another notepad file and type as follows :

package P1;

public interface K
{
public void show( ) ;

Now the User Defined package ‘ P1 ’ one class A and an interface B .

 Saving: To save the above program, go to folder P1 and save as “ B.java”

 Compiling : To compile above program, goto folder P1and compile as follows


at command prompt.

C:\> P1>javac B.java (or) C:\>javac –d . B.java

Krishnaveni Degree College :: Narasaraopet page 9


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

 Importing Packages :To use the classes of a package, we need to import the
packages into our programs. For this, we use keyword “ import” as follows :

Ex : import P1.* ; //symbol * represents all classes of P1 are imported


( or )
import P1.A ; // here A represents only class A of P1 is imported

The following program shows how to import package P1 into another program.
open new notepad file and type as follows :

import P1.A ;
import P1.B ;

public class B implements K /* using interfaceK in pack P1*/


{
public void show()
{
System.out.println(“From interface K in pack p1”);
}
}
class use_pack
{
public static void main( String args[ ] )
{
A a = new A( ); /* using class A in pack P1*/
a.x = 10 ;
a.displayA( ) ;
K i;
B b=new B();
b=i;
b.show( ) ;
}
}

Now save the above code as “ use_pack.java “ in the drive where folder P1 exists.
After that compile and execute “use_pack.java “ at command prompt as follows :

C:>javac use_pack.java

C:> java use_pack

then output will be as follows :

Krishnaveni Degree College :: Narasaraopet page 10


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

From class A in pack P1 , x = 10


From interface K in pack P1

Note 1: In the above program(use_pack.java) , we are not defining classes A and B but
we are using those classes by importing package P1 into our program , since P1
contains classes A and B.

Note 2: This is main advantage of creating packages. i.e. the classes/interfaces of one
program are used in another program.

.........................................................................................................................
choice Q ) Explain the following :

a) Extending classes from packages( Inheritance in Packages)


b) Hiding classes from packages

a) Extending classes from packages( Inheritance in Packages) :

Sometimes it is need to extend ( derive new classes ) from the classes of a package
into our program. For this , import that package and derive new classes by using
the keyword “extends “ ( like Inheritance programs ).

For example package P1 contains the class A as follows :

package P1 ;

public class A
{
public int x ;
public void display( )
{
System.out.println(“ From class A in pack P1 , x = “ + x );
}
}

Now we derive a new class C from class A in another new program as follows :

import P1.A;

class C extends A
{
void displayC()
{
System.out.println(“ C derived from A , x = “ + x ) ;
}
}
class Ext_pack
{
public static void main( String args[ ] )
{
C obj = new C ( );
Krishnaveni Degree College :: Narasaraopet page 11
OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

obj.x = 10 ;// class C uses variable of class A


obj.displayC( ) ;
}
}
In the above program , class C is derived from class A and this class A existed in
Package P1. According to Inheritance property the variables and methods of class A
are used by class C. This is Inheritance or extending of packages.

Output :C derived from A , x = 10

b) Hiding classes from packages :

Sometimes there is need to stop the accessing ( importing ) of classes from the
package into another programs. This is called “ hiding of classes “ .
For this process , we declare the classes as “ not public “ ,i.e. the keyword “public”
should not use before class definition.

For example the package P1 contains class A and class B as follows :

package P1 ;

public class A
{
-------
-------
}

class B
{
-------
-------
}

As shown above the class B is not declared with “public” , so it is not accessible into
other programs . But class A is accessible in other programs.

Ex : import P1.A ; // no error


import P1.B ; // gives error

....................................................................................................................

Krishnaveni Degree College :: Narasaraopet page 12


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Q) Explain creating Sub Packages(packages Hierarchy).

Sometimes a package may contain other sub packages also. i.e. a package is
defined in other (already existed) package. Then we can import those sub packages in
Hierarchical manner as follows

Syntax : import Main_pack_name[.Sub_pack_name].Class_Name;

Ex : import java.awt.color ; //System defined package


import P.p1.B; // User defined packae

Here java and P are the main packages .awt and p1 are sub packages. Color and B
are classes defined in sub packages.

The Hierarchical representation of “awt” package is as follows:

Example for Creation of Hierarchy of Packages(User defined) :

a) Creation of Main Package mp :


package mp ;
public class A
{
public void displayA()
{
System.out.println(“From Main Pack mp “);
}
}
Save the above code as “A.java” in folder mp. After that , go to folder mp and compile
at command prompt as follows :
C:\>mp>javac A.java or C:\> javac -d . A . java

Krishnaveni Degree College :: Narasaraopet page 13


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

b) Creation of Sub package sp :


package mp .sp ;
public class B
{
public void displayB()
{
System.out.println(“From Sub Pack sp “);
}
}

Now create a new folder sp should as sub folder in folder mp which is already
created.
Save the above code as “B.java” in folder sp. After that go to folder sp and compile at
command prompt as follows :
C:\>mp\cd sp
C:\>mp\sp>javac B.java

c) Importing subpackage and its classes from main package :

import mp.sp.*;

class pack_Hier
{
public static void main(String args[])
{
B b=new B();
b.displayB();
}
}
Above code saved as “pack_Hier.java” in drive where folder P is located.
compile as : C:\>javac pack_Hier.java
Run as : C:\>java pack_Hier

Output : From subpackage sp

In the above program , we created sub package sp in the main package mp and
import them into “pack_Hier.java”

Krishnaveni Degree College :: Narasaraopet page 14


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Q) Explain Access Specifiers / Access Modifiers(Visibility control) in Java


(or)
Explain different levels of Access Protection.

Sometimes we need to restrict the access of the variables and methods at outside of
the classes or packages. For this we use some keywords as modifiers before the
variables and methods. These are called “Access Modifiers or Access Specifiers” .

Java supports three access modifiers : 1. public


2. protected
3. private
These are used to change the access location of the variables and methods as shown
below :

public: It is used to giving the access at any where.

protected: It is the access level between public friendly access.

friendly : It is default level access. i.e. no access modifier is used.

private protected :It is limited to that class and its sub class only.

private: It is access level which is limited to that class only.

………………………………………………………………………………………………………………………………………………………

Krishnaveni Degree College :: Narasaraopet page 15


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Q) Explain about JAR( Java ARchive) Files creation. (or)

Explain about usage of JAR( Java ARchive) in packages or in Execution of Java Programs.

A ) A JAR ( Java ARchive ) file is a special file format which is used to compress so many packages , .class
files , .. etc. into a single archive(collection) file.

It is similar to “. ZIP File “ but difference is (. zip ) files are first extracted and then used where as “ . jar
files “ are used and executed directly.

Creation of “. jar “ File :


To create a “ . jar file , first select or create some “. class files “ or packages etc.
For example , create three packages p1,p2 and p3 which contains classes and after that create “. jar file“
to compress these three packages and class files into a single file.

Creating package p1 : (save as A . java)

package p1 ;

import p2.*;
import p3.* ;

public class A
{
public static void main(String args [ ])
{
System.out.println(“From class A in pack p1”);
B.displayB( ) ;
C.displayC( ) ;
}
}

creating package p2 : (save as B. java)

Note : methods declared as “static ‘ bcoz to access them with class name

package p2 ;

public class B
{
public static void display( )
{
System.out.println(“From class B in pack p2”);
}
}

Krishnaveni Degree College :: Narasaraopet page 16


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

creating package p3 : (save as C . java)

package p3 ;

public class C
{
public static void display C ( )
{
System.out.println(“From class C in pack p3”);
}
}

Now compile the above three packages at command prompt as follows :

C :\> javac –d . C . java


C :\> javac –d . B . java
C :\> javac –d . A . java
then three packages(folders) created . (as shown below : )
(Note: Images/screen shots are for understanding only no need to draw in Exam)

a) Now create “ . jar file “ the above three packages and their class files at command prompt.
For this , we use special command “jar” as follows :

C : \> jar - c f p1. jar p1

The above statement creates .jar file with p1 name. (as shown below :)

Krishnaveni Degree College :: Narasaraopet page 17


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

b) To add remaining packages p2 and p3 to “p1.jar” use jar command as follows :

C : \ > jar - u f p1. jar p2

C : \ > jar - u f p1. jar p3

Now the “ p1.jar “ file compressed and contains all the ( . class files ) of three different packages
as single Executable file. (as shown above)

c) To see the contents of “p1.jar” file use “ jar “ command as follows :

C : \ > jar - t f p1. jar

To see the advantage of a “.jar file” , delete all the packages(folders) p1,p2,p3 from the “Drive C : “ and
run the p1.jar file , then we will get output of all the deleted packages even they are deleted .

d) To run “ p1.jar “ file :

- First set class path at command prompt as follows :

C:\> set classpath = . ; C :\> p1. jar

- After that , run(Execute) “ p1.jar “ file as follows :

C : \ > java p1 . A

Then we will get output as follows :

From class A in pack p1


From class B in pack p2
From class C in pack p3

Note : Actually p1,p2,p3 folders are deleted but we can archive classes and get output from the
“. jar file “ , because the “p1.jar compress and contain all the classes into a single file .
This is main advantage of jar files.
……………………………………………………………………………………………………………………………………………………………………….

Krishnaveni Degree College :: Narasaraopet page 18


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Q) Explain how to create API ( A pplication P rogramming I nterface ) Document in Java.

A) - API(Application Programming Interface ) document is a HTML( Hyper Text Markup Language ) file.
- It contains description of all the features of a software , a product or a technology.

- In Java , we can create these type of API documents for packages , classes .. etc . Then those API
documents contain description (information) about classes , variables, methods related to that package

- For Ex ,create a package “api_pack” which contains two classes Addition and Subtraction as follows :

package api_pack ;

public class Addition


{
/** this method is used to find sum of given two integers
<br>parameters :int x,int y
<br>return type : int
<br>Exceptions : Nil
*/
public static int sum ( int x , int y )
{
return ( x + y ) ;
}
}

Save as : Addition . java in folder “api_pack”


Compile as : C : / >javac –d . Addition.java

package api_pack ;

public class Subtraction


{
public static int diff ( int a , int b )
{
return ( a - b ) ;
}
}

Save as : Subtraction . java in folder “api_pack”


Compile as : C : / > javac - d . Subtraction . java
Creating API document :
First we goto “api_pack “ folder and Type a special command “ javadoc * . java ” at command
prompt as follows :
C : / > api_pack > javadoc * . java

Krishnaveni Degree College :: Narasaraopet page 19


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Then different html files and other files are created in the folder “api_pack “ folder as shown below :

Among those files select “ index. html “ and open in any browser(iexplore,chrome etc) , then we will get
API document with for package “ api_pack “ as shown below : ( in exam,draw below table or below screenshot)

Package class Tree Deprecated Index help


PREV CLASS NEXT CLASS

api_pack
class Addition
java.lang.object

public class Addition


extends java.lang.object

Method summary
int sum(int x,int y) this method is used to find sum of given two integers

Krishnaveni Degree College :: Narasaraopet page 20


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

…………………………………………………………………………………………………………………………………………………………

Krishnaveni Degree College :: Narasaraopet page 21


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Chapter – 3 Exception Handling


Q)Define Exception . Explain Exception Handling process.
( OR )
Explain different types of Errors. Explain how Errors andExceptions handled in Java.
( OR )
Explain the following statements :
a) try block b) catch block c) finally block

Ans) Error : While developing a program , the programmer may make mistakesand
these mistakes are called “Errors”.
These errors are three types :
1. Compile-time ( Syntax ) Errors
2. Run-time Errors
3. Logical Errors

1. Compile-Time ( Syntax ) Errors : These errors are found at compilation time of


the program. These errors are raised by mistakes in syntax of that programing
language. For Example :
 Missing semicolons
 Mismatch or unclosed of brackets in classes and methods
 spelling mistakes of identifiers and keywords ,..etc
Due to these errors , we cannot execute the program.

2. Run-Time Errors : These errors are found at execution time (Run time)of the
program. These Errors may raised because of following conditions :
 Dividing an integer by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a wrong data type value into an array etc.
Due to these Errors, we can’t get the desired output, or program may terminated etc.

3. Logical Errors : These errors raised because of errors in logic of the program.
The programmer might be using wrong formula or the design of the program itself
is wrong.

 Exception : The Runtime error condition is called “Exception”.


Due to these Exceptions, we may face problems like System crash, program
termination, etc. So we should handle these Exceptions to get desired output .

Exception Handling : The process of catching an exception and continues the


execution of remaining code without any disturbance is known as “Exception
Handling”.

Krishnaveni Degree College :: Narasaraopet page 22


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Due to this process so we overcome problems caused by Exceptions at Runtime.


Java supports the Exception Handling mechanism with the following steps :
1. Find the problem.
2. Inform that an error has occurred (throw the exception).
3. Receive the error information (catch the exception).
4. Take corrective actions (handle the exceptions).
To implement the above steps in a program ,we use the below syntax :
try
{
…………..
…………..
}
catch( ExceptionType e )
{
………….
………….
}

Here try , catch are the keywords and according to concept these are called
“Exception Handlers” ( Exception Handling statements/blocks ).

 try block : In this block, we write the statements which may raises Exceptions.
If an Exception is raised, try block throws that Exception to “catch block”.
i.e. try block performs step1 and step2 of Exception Handling process.

 catch block : This block receives an Exception thrown by “try block” , and wewrite
the statements to handle that Exception.
i.e. catch block performs step3 and step4 of Exception Handling process.
The following program shows the Exception Handling Process :
class ExHandle
{
public static void main( String args [ ] )
{
int a , b c;

a = 10 ;
b=5;
c=5;

Krishnaveni Degree College :: Narasaraopet page 23


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

try
{
int x = a / ( b – c ) ; /* raise ArithmeticException */
System.out.println(“ x value : “ + x ) ;
}
catch( ArithmeticException e )
{
System.out.println( “Division by zero is not possible “ ) ;
}
int y = a / ( b + c ) ;
System.out.println(“ y value : “ + y ) ;
}
}
Explanation : As shown above, the integer ‘a’ is dividing by zero (b-c=0).Generally it is
not possible , so it is Arithmetic Exception which leads to runtime error. This Exception is
raised in try block and throws into catch block. Then catch block display necessary
information and continue the execution of remaining code.
Then the output will be :

Advantages of Exception Handling:

 Separating the statements(code) which have runtime errors in program.

 No disturbance for execution of remaining(correct) code.

 Programmer can identify Error Type and necessary action.

Q) Explain Different types of Exceptions in Java

Exception : Exception is a RunTime-Error condition.These


Exceptions are two types :
a) Checked Exceptions
b) Unchecked Exceptions

Krishnaveni Degree College :: Narasaraopet page 24


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

a) Checked Exceptions :
 These should be handled in the code itself using try-catch blocks.

 These exceptions are checked at compilation time by the java compiler.

 These exceptions are extend from the “ java.lang.Exception” class.


b) Unchecked Exceptions :
 These exceptions are not compulsory handled in the program code,
because the JVM ( Java Virtual Machine ) handles such exceptions.

 These are extended from “ java.lang.RuntimeException” class.

The following table shows common pre-defined Exceptions in Java :

Sno Exception name Meaning


Caused by math errors such as
1 ArithmeticException division by zero

Caused due to accessing the array


2 ArrayIndexOutOfBoundsExce indices which out of range
ption
Caused due to assignment to an
3 ArrayStoreException array element of an incompatible
type.
Caused when a conversion between
4 NumberFormatException string and number fails

5 NullPointerException Caused when referring a null object


6 FileNotFoundException Caused when access non existing
file
7 NegativeArraySizeException when assign –ve value as array size
8 OutOfMemoryException Caused when there is no enough
memory for an object
9 IOException Caused when i/o operations failed
10 StackOverFlowException Caused when the system runs out of
stackspace

Krishnaveni Degree College :: Narasaraopet page 25


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Q ) Explain Multiple catch Statements and finally block.

Multiple catch Statements : Sometimes there is need to handle more than one
Exception in the program, then we use more than one “catch” Statement(block).

finally statement :This is special statement block. It can receive any type of Exception.
The statements in this block are guaranteed to execute irrespective of Exception.

Here “finally” is the reserved keyword like try and catch .

The following program shows the working of multiple catch and finally statements:
class ExHandle
{
public static void main( String args [ ] )
{
int a[ ] = { 10,5 } ;
int b = 5 ;try
{
int x = a[2] / ( b - a[1] ) ; /*raise ArrayOutOfBounds Exception */
System.out.println(“ x value : “ + x ) ;
}
catch( ArithmeticException e )
{
System.out.println( “Division by zero is not possible “ ) ;
}
catch( ArrayIndexOutOfBoundsException e )
{
System.out.println(“ You are accessing out of bound element“ ) ;
}
catch( ArrayStoreException e )
{
System.out.println( “ Wrong Datatype values stored” ) ;
}
finally
{
int y = a[1] / a[0] ;
System.out.println(“ y value = “ + y ) ;
}
}
}

Krishnaveni Degree College :: Narasaraopet page 26


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

Explanation: In the above program, we are accessing a[2](i.e. third element in Array)
but it is not exist because there are two elements in given array “a”. So when
Exception raised, the related catch block( 2 nd catch block) is executed and remaining
catch blocks are not executed.
Similarly , finally block is executed irrespective of exceptions.

Output : You are accessing out of bound element


y value : 2

……………………………………………………………………………………………………………
Q ) Explain about user defined Exceptions(our own Exceptions)
( or )
Explain about “ throw “ and “throws” clauses (statements).

In Java , it is possible to define our own Exceptions. The user defined Exceptions are
defined by extending the predefined class “Exception”.

throw : It is one of the Exception handler. It is used to throw (sent) the user defined
Exceptions.
The throw statement use the following syntax :

throw new throwable_Subclass (“message”) ;

The following program shows the creation of User Defined Exceptions :

import java.lang.Exception ;
class myExcep extends Exception
{
myExcep(String msg)
{
super(msg);
}
}

class UDEx
{
public static void main(String args[ ])
{
int x , y ;
x=5;
y=1000;
float z = (float) x / (float) y ;

Krishnaveni Degree College :: Narasaraopet page 27


OOP using Java-II BSC(sem-4)-All Comp. Groups UNIT – 3

try
{
if (z<0.01)
throw new myExcep("Number is too small") ;
}
catch(myExcep e)
{
System.out.println(e.getMessage()) ;
}
finally
{
System.out.println("z value : "+z);
}
}
}
Explanation : In the above program, “myExcep” is user defined Exception.When z
value is less than 0.01, User Defined Exception is raised and it is caught by catch block.
Then object “e” contains the error message “ Number is too small ” and it is
displayed by method “getMessage()” .

Output : Number is too small


z value : 0.005

throws : It is special keyword which is used with methods. It specifies that, themethod
might throw one or more Exceptions.

Syntax : type method-name(parameter-list) throws exception-list


{
// body of method
}

Example: static void divide( ) throws ArithmeticException


{
int x = a / b ;
}

Krishnaveni Degree College :: Narasaraopet page 28


OOP with Java -II BSC(SEM-4) All Comp Groups Unit - 3

Q) Explain how to rethrow an Exception .


Normally, catch block are used to handle the exceptions raised in the try block. The exception can
re-throw using throw keyword, if catch block is unable to handle it. This process is called as re-
throwing an exception.

classReThrowEx
{
public void division()
{
int n1=30;
int n2=0;
try
{
int x=n1/n2;
System.out.println("x value "+x);
}
catch(ArithmeticException e)
{
throw e ; //Exception rethrow to catch block in main class
}
}
}
class oop22
{
public static void main(String[] args)
{
ReThrowEx r = new ReThrowEx();
try
{
r.division( ) ;
}
catch ( Exception e )
{
System.out.println(e.getMessage());
System.out.println("This Exception rethrown by division method and caught by main method");
}
}
}
output : / by zero
This Exception rethrown by division method and caught by main method

-----------------------------------------------------------------------------------------------------------

Krishnaveni Degree College :: Narasaraopet Page 29


OOP with Java -II BSC(SEM-4) All Comp Groups Unit - 3

Unit - 3 Questions

1) Explain Method Overloading (Static/Compile Time Polymorphism) and


Method Over Riding(Dynamic/Run Time Polymorphism).
(OR)
Explain types of Polymorphism in Java .

2Q) Explain about final variables ,final methods, final classes and finalizer

3Q) Explain about abstract methods and abstract classes.

4Q )Explain about Interfaces (or) Explain declaring, implementing and Extending of Interfaces.

5Q) Explain Multiple Inheritance in Java using Interfaces.


6Q) Explain about Different types of Packages in Java.
( or )
Explain about creation of User defined Packages in Java.

7Q )choice Explain the following :


a) Extending classes from packages( Inheritance in Packages)
b) Hiding classes from packages

8Q) Explain creating Sub Packages(packages Hierarchy).

9Q) Explain Access Specifiers / Access Modifiers(Visibility control) in Java


(or)
Explain different levels of Access Protection.

10Q) Explain about JAR( Java ARchive) Files creation. (or)


Explain about usage of JAR( Java ARchive) in packages or in Execution of Java Programs.

11Q) Explain how to create API ( A pplication P rogramming I nterface ) Document in Java.

12Q)Define Exception . Explain Exception Handling process.


( OR )
Explain different types of Errors. Explain how Errors and Exceptions handled in Java.
(OR )
Explain the following statements :
a)try block b) catch block c) finally block

13Q) Explain Different types of Exceptions in Java

14Q ) Explain Multiple catch Statements and finally block.

15Q ) Explain about user defined Exceptions(our own Exceptions)


( or )
Explain about “ throw “ and “throws” clauses (statements).

16Q) Explain how to rethrow an Exception .

Krishnaveni Degree College :: Narasaraopet Page 30


OOP with Java -II BSC(SEM-4) All Comp Groups Unit - 3

Krishnaveni Degree College :: Narasaraopet Page 31

You might also like