You are on page 1of 43

Java Programming

UNIT-3
Inheritance, packages, exceptions

Topics covered in this unit:


• Inheritance:
– types of inheritance
– super keyword
– final keyword
– overriding and abstract class
– Interfaces
• Packages:
– creating the packages
– using packages
– importance of CLASSPATH
– java.lang package.
• Exception handling:
– importance of try-catch, throw, throws and finally block.
– user-defined exceptions, Assertions.

Hierarchical Abstractions:
• Humans manage complexity through abstraction.
• For example, people do not think of a car as a set of tens of thousands of individual parts.
• They think of it as a well defined object with its own unique behavior.
• This abstraction allows people to use a car without being overwhelmed by the complexity of the
parts that form the car.
• They can ignore the details of how the engine, transmission, and braking systems work.
• These hierarchical abstractions are achieved by aggregation or inheritance.
Aggregation:
• Aggregation in Java is a relationship between two classes that is best described as a "has-a" and
"whole/part" relationship.
• It is a more specialized version of the association relationship.
• The aggregate class contains a reference to another class and is said to have ownership of that
class. Each class referenced is considered to be part-of the aggregate class.
• Ownership occurs because there can be no cyclic references in an aggregation relationship.
Inheritance:
• Inheritance is an important pillar of OOP(Object Oriented Programming).
• It is the mechanism in java by which one class is allow to inherit the features(fields and
methods) of another class.
Hierarchy caused by Aggregation Vs inheritance:

Aggregation Vs Inheritance:
• Both associations describe trees (hierarchies)
• Aggregation tree describes “a-part-of “relationships.
• Inheritance tree describes "kind-of" relationships.
• Aggregation is part-of or part-whole relationship (by reference)
Ex : Car has Engine and Transmission
• Inheritance is kind of or is-a or parent-child relationship
Ex: Car and Bus are kind of Vehicles
• Aggregation relates instances (involves two or more different objects)
• Inheritance relates classes (a way to structure the description of a single object)
Inheritance:
• Inheritance is the mechanism of deriving new class from old one.
• Old class is known as Base class or super class or parent class.
• The inherited new class is known as derived class or sub class or child class.
• The sub class inherits all of its instance variables and methods defined by super class.
• The sub class also adds its own specialized features.
• A child class of one parent can be the parent of another child, forming class hierarchies.
• The class hierarchy determines how methods are executed.
• inheritance is transitive.
• The benefits of inheritance is code reusability, better ability to extend ( adding new features ) or
enhance ( improving the existing features ).
Benefits of inheritance:
• The most frequent use of inheritance is for deriving classes using existing classes, which provides
reusability. The existing classes remain unchanged. By reusability, the development time of
software is reduced.
• The derived classes extend the properties of base classes to generate more dominant objects.
• The same base classes can be used by a number of derived classes in class hierarchy.
• When a class is derived from more than one class, all the derived classes have similar properties
to those of base classes
Important terminology in inheritance:
 Super Class: The class whose features are inherited is known as super class(or a base class or a
parent class).
 Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Defining a sub class to super class:
• Syntax to define a sub class
class <sub_class_name> extends <super_class_name>
{
// members in the sub class
}
• 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.
• In the terminology of Java, a class which is inherited is called parent or super class or base class
• The new class is called child class or subclass or derived class.

Types of inheritance:

Simple(Single) inheritance:
• Classes are inherited from other class by declaring them as a part of its definition
• For e.g.
– class MySubClass extends MySuperClass
• extends keyword declares that MySubClass inherits the parent class MySuperClass.
• Simple inheritance is a parent-child relationship between two classes.
• It allows sharing of the behavior of the parent class into its child classes
• The child class can add new behavior or override existing behavior from parent.
• Java forces a class to have exactly one parent
Program to demonstrate Simple(single) inheritance:

Output:
Multi-Level Inheritance:
• It is a ladder or hierarchy of single level inheritance.
• Multiple classes are involved in inheritance, but one class extends only one.
• The lowermost subclass can make use of all its super classes' members.

Program to explain Multi-level inheritance:

class Rectangle {
int length;
int width;
Rectangle() { }
public Rectangle(int l, int w) {
length = l;
width = w;
}
}
class Box extends Rectangle {
int height;
Box() { }
public Box (int l, int w, int h) {
length = l;
width = w;
height = h;
}
public int volume() {
return (length * width * height);
}
}
class SolidBox extends Box {
int density;
public SolidBox(int l, int w, int h, int d) {
length = l;
width = w;
height = h;
density = d;
}
public int weight() {
return(super.volume() * density);
}
}
class MultiLevelInheritTest
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(5,8);
System.out.println("Area of rectangle : " + (r1.length * r1.width));
Box b1 = new Box(7,5,9);
System.out.println("Volume of the box : " + b1.volume());
SolidBox m1 = new SolidBox(10,15,25,3);
System.out.println( "Volume of the Solid box : " + m1.volume());
System.out.println("The weight of the Solid Box : " + m1.weight() + " KiloGrams.");
}
}
Output:

Order of Execution of Constructors in multi-level inheritance:


• A constructor for the base class is always called during the construction process for a derived
class, chaining up the inheritance hierarchy so that a constructor for every base class is called.
• This makes sense because the constructor has a special job: to see that the object is built
properly.
• A derived class has access to its own members only, and not to those of the base class (whose
members are typically private).
• Only the base-class constructor has the proper knowledge and access to initialize its own
elements. Therefore, it’s essential that all constructors get called, otherwise the entire object
wouldn’t be constructed.
• It will silently call the default constructor if you don’t explicitly call a base-class constructor in
the derived-class constructor body
• In the case where a class has no constructors, the compiler will automatically synthesize a
default constructor.
• If we want to call parameterized contractor of base class, then we can call it using super().
• The point to note is base class constructor call must be the first line in derived class constructor.
Output:

Method Overriding:
• 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 subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
• The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its requirement.

• In object-oriented terms, overriding means to override the functionality of an existing method

Usage of Java Method Overriding


• Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
• The access level cannot be more restrictive than the overridden method's access level. For
example: If the super class method is declared public then the overridding method in the sub
class cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared private or final or static cannot be overridden.
• If a method cannot be inherited, then it cannot be overridden.
• A subclass in a different package can only override the non-final methods declared public or
protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not.
• Constructors cannot be overridden.
Program to demonstrate Method Overriding:

Output:
Method overloading Vs overriding:

Hierarchical Inheritance:

• In this type of inheritance there are multiple classes which are derived from one base class.
• It is used when one class feature is required in multiple classes.

Dynamic Method Dispatch:

• A virtual function exhibits dynamic binding while execution.


• In java, all instance methods are by default virtual functions.
• So method overriding exhibits Dynamic polymorphism.
• Calling an overridden instance method by an object reference is not based on type of the object
reference.
• It is based on type of object associated with object reference, which are bonded during runtime
based upon runtime object.

Dynamic Method Dispatch demonstrating with the support of Hierarchical Inheritance:

class Animal {
void show() {
System.out.println("I am animal");
}
}
class Cow extends Animal {
// overriding method
void show() {
System.out.println("I am Cow");
}
}
class Cat extends Animal {
// overriding method
void show() {
System.out.println("I am Cat");
}
}
class Dog extends Animal {
// overriding method
void show() {
System.out.println("I am Dog");
}
}
class DynamicMethodDispatch {
public static void main(String[] args) {
Animal a1;
a1 = new Animal();
a1.show();
// up casting
a1 = new Cow();
a1.show();

a1 = new Cat();
a1.show();

a1 = new Dog();
a1.show();
}
}
Output:
Super keyword:
• Super keyword is used to access super class members.
• We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have data fields with same name.
• The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
• The super keyword can also be used to invoke the parent class parameterized constructor from
sub class constructor.
• When super class constructor is invoked in subclass constructor, the call for super class
constructor should be first statement in sub class constructor.

Program to demonstrate ‘super’ keyword:

class Parent {
int x;
Parent(int i ) {
x = i;
}
void show() {
System.out.println(" Parent : x = " + x);
}
}
class Child extends Parent {
int x;
int y;
Child(int i, int j, int k) {
super(i);
x = j;
y = k;
}
void show() {
System.out.println("Parent : x = " + super.x);
System.out.println("Child : x = " + x);
System.out.println("Child : y = " + y);
}
void parent_show() {
super.show();
}
}
class SuperDemo {
public static void main(String[] args) {
Child c1 = new Child(2,3,4);
c1.show();
c1.parent_show();
}
}
Output:

Final keyword:
• final keyword is used in different contexts. First of all, final is a non-access modifier
applicable only to a variable, a method or a class.
• Declaring constants (used with variable and argument declaration)
– final int MAX=100;
• Preventing method overriding by subclass (used with method declaration)
– final void show (final int x)
• Preventing to create subclass (used with class declaration).
– final class Demo {}

Final variables
– When a variable is declared with final keyword, it’s value can’t be modified, essentially, a constant.
– If the final variable is a reference, this means that the variable cannot be re-bound to reference
another object, but internal state of the object pointed by that reference variable can be changed
– For example, you can add or remove elements from final array or final collection.
– It is good practice to represent final variables in all uppercase, using underscore to separate words.
Example:
int x = 30; final int y = 30;
x = 45; // O.K. x = 45; // error, because y is final constant.

Final methods:
• A final method cannot be overridden.
• It means that a sub class can call the final method of parent class, but it cannot override it.
• Final methods exhibit early binding.
• The use of final method is to protect against accidental overriding,  or maybe performance.
Example :

class A {
int x = 10;
final void show() {
System.out.println(“x = “ + x);
}
}
class B extends A {
void show() { // raises compilation error- final method cannot be overriden
// code
}
}

Final Classes:
• We can also declare an entire class final.
• We cannot write subclass to final class.
• This is particularly useful, for example, when creating an immutable class like the String class.

final class Demo {


// code
}
class Test extends Demo { //raises compilation error – cannot inherit final class.
// code
}

Abstract Class:
• Abstraction is the quality of dealing with ideas rather than events.
• In Object-oriented programming, abstraction is a process of hiding the implementation details
from the user, only the functionality will be provided to the user.
• In other words, the user will have the information on what the object does instead of how it
does it.
• In Java, abstraction is achieved using Abstract classes and interfaces.
• In general, every method has implementation in the class definition.
Ex: void show()
{
System.out.println("This is concrete method");
}

• But an abstract method does not have method body, only declaration.(like pure virtual functions
in C++).
• Ex: abstract void show();
• An abstract method contains a method signature, but no method body. Instead of curly braces,
an abstract method will have a semi colon (;) at the end.
• When a class contains at least one abstract method, the class is known as abstract class.
• Ex: abstract class Demo
{
int x, y;
Demo( int a, int b) {
x = a;
y = b;
}
void show() {
System.out.println("x = " + x + ", y = " + y);
}
abstract void add();
}
Program to demonstrate an abstract class:
abstract class Shape
{
int dim1;
int dim2;
Shape(int a, int b) {
dim1 = a;
dim2 = b;
}
abstract double area();
}
class ImpRectangle extends Shape
{
ImpRectangle(int a, int b) {
super(a,b);
}
public double area() {
return (dim1*dim2);
}
}
class ImpTriangle extends Shape
{
ImpTriangle(int a, int b) {
super(a,b);
}
public double area() {
return (dim1*dim2)/2;
}
}
class AbstractTest
{
public static void main(String[] args) {
Shape r = new ImpRectangle(20,25);
Shape t = new ImpTriangle(20,25);
System.out.println("Area of Rectangle : " + r.area());
System.out.println("Area of Triangle : " + t.area());
}
}
Output:

Rules for abstract class:


 Abstract classes may or may not contain abstract methods, i.e., methods without body ( public
void get(); )
 But, if a class has at least one abstract method, then the class must be declared abstract.
 If a class is declared abstract, it cannot be instantiated. Even though it contains constructor.
 An abstract class can have a mix of some abstract methods and some concrete methods
(method with body).
 To use an abstract class, you have to inherit it from another class, provide implementations to
the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the abstract methods
in it.
Use of abstract classes:
 Abstract Classes are a good fit if you want to leave out implementation details to the child class
but don't want to allow an instance of your class to be directly instantiated.
 We can say an abstract class is a partially define a class.
 Abstract classes provide reusability as well as flexibility to extend.
 Concrete methods of abstract class can be shared by all its sub classes. At the same time, the
abstract class enforces sub classes, to write own implementations to the abstract methods.
 So, all subclasses of abstract class have same method signatures and different implementations
against all abstract methods of abstract class.
Interfaces:
• An interface in the Java is an abstract type.
• It is used to specify a behavior that subclasses must implement.
• So interface in java is a blueprint of different subclasses.
• Interfaces are declared using the interface keyword.
• It has static constants and abstract methods only.
• The interface in java is a mechanism to achieve abstraction.
Defining an interface:
interface <interface_name>
{
Constant1
Constant2
.......
ConstantN
Abstract_method1();
Abstract_method2();
................
Abstract_methodN();
}
Example:
interface Shape
{
double PI = 3.14;
void area();
void perimeter();
}
Defining sub class to implement interface abstract methods:
class <subclass_name> implements <interface_name>
{
Implementation for Abstract_method1();
Implementation for Abstract_method2();
................
Implementation for Abstract_methodN();
}

Program to demonstrate to use inerface:


interface Shape
{
double PI = 3.14;
void area();
void perimeter();
}
class Circle implements Shape
{
double radius;
Circle(double r) { radius = r; }
public void area() {
System.out.println("Area of circle : " + (PI * radius * radius));
}
public void perimeter() {
System.out.println("Perimeter of circle : " + (2 * PI * radius));
}
}
class InterfaceTest1
{
public static void main(String[] args)
{
Shape c1 = new Circle(12.5);
c1.area();
c1.perimeter();
}
}
Output:

Rules working with interfaces:


• All the data members declared in the interface are by default public static final variables(static
constants).
• All the methods declared in the interface are by default public abstract methods.
• An interface does not contain any constructors
• An interface is not extended by a class; it is implemented by a class.
• The subclass uses the implements keyword to implement an interface.
• All methods of interface should be implemented in the subclass, otherwise it becomes abstract
class.
• Every abstract method of interface should be implemented with public access level.
• A class can extend only one class, but implement many interfaces.(multiple inheritance)
Program to demonstrate multiple-inheritance with Interfaces:
interface Shape {
double PI = 3.1415;
void area();
void volume();
}
interface Units
{
String AREA_UNITS = " sq. cm.";
String VOLUME_UNITS = " c. c.";
}
class Sphere implements Shape, Units
{
double radius;
Sphere(double r) { radius = r; }
public void area()
{
System.out.println("Surface Area of Sphere : " +
(4* PI * radius * radius) + AREA_UNITS);
}
public void volume()
{
System.out.println("Volume of Sphere : " +
((4.0/3)* PI * Math.pow(radius,3)) + VOLUME_UNITS);
}
}
class Cube implements Shape, Units // multiple-inheritance
{
double side;
Cube(double s)
{
side = s;
}
public void area()
{
System.out.println("Surface Area of Cube : " +(6 * side * side) + AREA_UNITS);
}
public void volume()
{
System.out.println("Volume of Cube : " + Math.pow(side,3) + VOLUME_UNITS);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Shape s[] = { new Sphere(12.5), new Cube(9.7) };
for(Shape obj : s) {
obj.area();
obj.volume();
}
}
}

Output:

Purpose of Interfaces:
• Interfaces are used to separate abstraction from implementation.
• It is used to identify a common set of methods for the group of classes that implement the
interface.
• It is also used to share constants between classes.
• Interfaces are used to provide the benefits of multiple-inheritance without its implementation
difficulties.
• Interfaces without methods are known as marker interfaces, which are used to provide eligibility
to perform some actions like serialization etc.,
• Interfaces are used to create a collection of non-related sub class objects like an array.
• Interfaces provide a control on its sub classes to maintain the method signatures are same
across all its sub classes. (Dynamic polymorphism with non-related classes)
• Reference variables of interfaces can provide security across internet, in client server
programming.

Interfaces Vs abstract classes Vs Concrete classes:


Comparison between abstract class and interface:

Abstract class Vs Interface

Extending Interfaces:
• An interface can extend another interface. The ‘extends’ keyword is used to extend an interface,
and the child interface inherits the methods of the parent interface.
• An interface can extend more than one parent interface. The ‘extends’ keyword is used once,
and the parent interfaces are declared in a comma-separated list.
Program to demonstrate extending interfaces:
interface Inter1 {
void meth1();
}
interface Inter2
{
void meth2();
}
interface Inter3 extends Inter1,Inter2 {
void meth3();
}
class OurClass implements Inter3 {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class InterfaceExtend {
public static void main(String[] args) {
Inter3 x = new OurClass();
x.meth1();
x.meth2();
x.meth3();
}
}
Output:

Packages:
• A package is generally a collection of classes and interfaces
• It provides a unique namespace for the classes, to avoid naming conflictions.
• Declaration of package statement resides at the top of a Java source file.
• A package can contain the following.
– Classes
– Interfaces
– Enumerated types
– Annotations
• Class that reside inside a package cannot be referred by their own name alone.
• The package name has to precede the name of the class, which is known as fully qualified name.
• If the package keyword is not used in any class for mentioning the name of the package, then it
becomes part of the default/unnamed package.
• So, the main purpose of packages is to provide a contextual namespace within which a class
resides.
• Java provides a syntax for package names
– Package names always in small letters and the words in the package name are separated
by periods.
– Ex: org.financial.inventory;
• Packages also provide a specific scope, known as package scope. All the classes defined in the
package can share the members declared without any access specifier.
Categories of Packages

The Java Packages are categorized into two categories (i) Java API Packages (ii) User Defined
Packages.

1. Java API Packages –Java API provides large number of classes grouped into different packages
according to the functionality. Most of the time we use the package available with Java API.

2. User Define Packages


We can also define our own packages, as per the functional modules.
The general form of the package statement will be as followed: package pkg;
Example: package inventorypack;
Example: package org.dept.inventory;
Java Uses file system directories to store packages. For example, the " .class" files for any
classes you declare to be part of the "inventorypack" must be store in the "inventorypack " directory.
The class within the package "org.dept.inventary " must be store in the "org\dept\inventory"
directory path.
Notes: 1. The case for the package name is significant.
2. The directory name must match with package name.

Steps involved working with packages:


STEP-1 : Defining a Package:
• Creating a package is quite easy: simply include a package command as the first statement in a
Java source file.
• Any classes declared within that file will belong to the specified package.
• The package statement defines a name space in which classes are stored.
Example:
- Create a staging directory for example : d:\javalab\>
- Create a source program with name Circle.java
- The command is
D:\javalab\> notepad Circle.java
Circle.java

STEP-2: Compiling the source program:


Ex: d:\javalab\>javac -d . Circle.java
In the above command –d represents to create sub directory path as per the package name, and the
. (period) represents current directory.

STEP-3: Executing the .class file:


Ex: d:\javalab\>java com.aditya.demo.Circle
Output:

STEP-4: Finding Packages and CLASSPATH:

• Java run-time-system should know where to look for packages that you create?
• The answer has two parts.
• First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if your package is in the current directory, or a subdirectory of the current directory,
it will be found.
• Second, you can specify a directory path or paths by setting the CLASSPATH environmental
variable.
• The .class file in the above example is created in the directory path:
D:\javalab\com\aditya\demo\Circle.class
Here D:\javalab -- base directory path.
com\aditya\demo -- package directory path.
• Now the base directory path is need to store in CLASSPATH environment variable

STEP-5 : importing the class defined in a package, in another class defined in other package.

ImportTest.java

Output:

Package and Member Accessing

• The visibility of an element is specified by the access specifiers:


public, private, and protected and also the package in which it resides.
• Java provides a number of access modifiers to set access levels for classes, variables, methods,
and constructors. The four access levels are −

• Visible to the package, the default. No modifiers are needed.


• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses (protected).
• The different access levels are explained in different categories of classes as below:

Programs to demonstrate with Access Specifers:

a) With in the scope of same class:

Class1.java

Output:
b) With in the scope of sub class in the same package:

Output:

c) With in the scope of non-sub class in the same package:

Output:
d) With in the scope of sub class in the other package:

Output:

d) With in the scope of non-sub class in the other package:

Output:
java.lang. package:
 java.lang is a special package, as it is imported by default in all the classes that we create.
 There is no need to explicitly import the lang package.
 It contains the classes that form the basic building blocks of Java.
 Some of the important classes from this package are:
o Object class
o Math class
o String class
o StringBuffer class
o Wrapper classes - Boolean, Integer, Long, Float, Double etc.,
o Exception classes - ArithmeticException, ArrayIndexOutOfBoundsException etc.,
o System, Process, Runtime classes
o Thread class
java.lang.Object Class
 Object class is the parent of all the classes (predefined and user-defined) in Java.
 For all the classes that we have created so far or will be creating further, Object class is the
parent by default and there is no need to explicitly inherit the Object class.
Methods in Object class:

java.lang.String class:
 Strings are basically immutable objects in Java.
 Immutable means once created, the strings cannot be changed.
 Whenever we create strings, it is this class that is instantiated.
 In Java, strings can be instantiated in two ways:
String x = "Hello";
String y = new String ("Hello");

 When a string object is created from assigning a string literal, the object is created in String
intern pool.
 When a string object is created with constructor, then the object is created in heap memory.
 Equality of two strings are checked in two ways
 Using equals() method: This method returns true if both strings have same content.
 Using == (equality operator) : this operator checks whether both strings have same hashcode.

java.lang.Math Class

Math class is static class. It contains all static methods to perform mathematical operations.
Wrapper classes:
 Java contains some data structures which won't accept to store primitive data types.
 Then we have to take support of some classes to convert primitive data types in to class objects.
 These classes are known as wrapper classes.
List of Wrapper classes are:

How to convert primitive data type into Wrapper class object:


double a = 4.3; // primitive
Double b = new Double(a); // converting into object
Each Wrapper class also contains a method to return the primitive value
Double c = b.doubleValue();
Converting primitive to Wrapper:
int v = 56;
Integer var1 = new Integer(v);
float x = 17.8f;
Float var2 = new Float(x);
Converting Wrapper to primitive:
int a = var1.intValue();
float b = var2.floatValue();
Parsing methods from string type to primitive types:
int a = Integer.parseInt("123");
long b = Long.parseLong("3456");
float c = Float.parseFloat("3.124");
double d = Double.parseDouble("3789.23");
byte e = Byte.parseByte("56");
short f = Short.parseShort("5634");
Boxing and unboxing:
• From JDK 5.0 onwards Boxing is introduced.
• Converting primitive types into wrapper class object automatically is known as boxing.
• Ex: int num = 45;
Integer i1 = num; // boxing
• Converting Wrapper class object into primitive type is known as unboxing
• Ex: Integer i2 = new Integer(45);
int var1 = i2; // unboxing
• In boxing, primitive type variables are stored in stack memory, where Wrapper class objects are
stored in heap memory.
• For storing in data structures, we use boxing and unboxing.

Exception Handling

What is exception?
• An exception (or exceptional event) is a problem that arises during the execution of a program.
• When an Exception is occurred, the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended.
• Therefore, these exceptions are to be handled.
Examples for Exceptions:
• Divide by zero Ex: 12/0
• Negative array size Ex: int[] a = new int[ -10];
• Index of array element is more than the size Ex: int[] arr = new int[5]; arr[10] = 25;
• File not found physically in the memory when going to read
• Network connection failed etc.,
Program to demonstrate about exception:

Output:
Case 1: Normal Execution
Case 2: Exception raised

What happened when exception is raised?


• When exception is raised at the time of execution, JVM stops the execution immediately, and
displays the information about the exception:
o a) name of thread
o b) name of the exception
o c) description of the exception
o d) method name where exception raised.
o e) Line no in source program, where exception is raised.

Types of exceptions:
• An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
o A user has entered an invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of communications or the JVM has
run out of memory.
• Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
• Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.
• Checked exceptions − A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions.
• Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. 
• Errors − These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer.

Exception Hierarchy
• All exception classes are subtypes of the java.lang.Exception class.
• The exception class is a subclass of the Throwable class.
• Other than the exception class there is another subclass called Error which is derived from the
Throwable class.
• Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs.
• Errors are generated to indicate errors generated by the runtime environment.
Some Built-in Exceptions:

Exception Handling Techniques:


Java provides five keywords for exception handling: try, catch, throw, throws, and finally.

Handling exception with try-catch-finally block:


• The try block contains set of statements where an exception can occur.
• A try block is always followed by a catch block, which handles the exception that occurs in
associated try block.
• A try block must be followed by catch blocks or finally block or both.
• A catch block is where you handle the exceptions; this block must follow the try block.
• A single try block can have several catch blocks associated with it.
• You can catch different exceptions in different catch blocks.
• When an exception occurs in try block, the corresponding catch block that handles that
particular exception executes.
Flow of control in try/catch/finally blocks:

1. If exception occurs in try block’s body then control immediately transferred(skipping rest of the
statements in try block) to the catch block. Once catch block finished execution then finally
block and after that rest of the program.
2. If there is no exception occurred in the code which is present in try block then first, the try block
gets executed completely and then control gets transferred to finally block (skipping catch
blocks).
3. If a return statement is encountered either in try or catch block. In this case finally block runs.
Control first jumps to finally and then it returned back to return statement

Program to demonstrate try-catch statement:

Output:
Case 1: normal execution:

Case2: Exception raised:


Multiple catch blocks:

Output:

Case 1: Raised ArithmeticException:

Case 2: Raised InputMismatchException:


Finally Block:
• The finally block always executes when the try block exits.
• This ensures that the finally block is executed even if an unexpected exception occurs.
• But finally is useful exception handling — it allows the programmer to avoid having cleanup
code accidentally bypassed by a return, continue, or break.
• Putting cleanup code in a finally block is always a good practice, even when no exceptions are
anticipated.
Output: case 1: No exception raised:

Case 2: Exception raised and handled:

Case 3: Exception raised but not handled:

Throw Statement:
• The throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception.
• The throw keyword is normally used to throw custom exception.

Program to demonstrate throw keyword:


Output:

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.
• When a method has statements prone to generate checked exceptions, the programmer has
two choices:
 the checked exception has to be handled with in same method.
 Otherwise the unhandled exception is listed in the throws clause
• points to remember about throws keyword:
throws keyword is required only for checked exception.
throws keyword is required only to convince compiler and usage of throws
keyword does not prevent abnormal termination of program.
 By the help of throws keyword we can provide information to the caller of the
method about the exception.
Program to demonstrate throws keyword:

Output:

Throw vs throws keywords:

throw keyword throws keyword


throw is a statement throws is a clause
Used to generate an exception object explicitly in Used to list out the unhandled exceptions in a
the program. method.
Used in the method body. Added at the end of method signature.
Declaring your Own Exceptions:

• You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException class.
Program to demonstrate user defined exception:
import java.util.Scanner;
class NotEligibleException extends Exception {
public String toString() {
return "You are not eligible for voting..";
}
}
class ThrowDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try
{
System.out.print("Enter your age : ");
int age = sc.nextInt();
if(age < 18)
{
throw new NotEligibleException();
} else {
System.out.println("Welcome! You are eligible for voting!");
}
}
catch (NotEligibleException ne)
{
System.out.println(ne);
}
}
}
Output:
Case 1:

Case 2 :
Assertions:
• Assertions are statements, used to test a condition is fulfilled or not.
• Generally assertions are used in testing phase only.
Program to demonstrate assertions:

Output:

Note: When working with assertions, we need to include the option -ea along with java
command.
List of questions asked in previous question papers:

Part-A
a) What happens when there is no suitable try block to handle exception?
b) Why to use finally block in java exception handling.
c) How java supports multiple inheritance?
d) Explain about the importance of extend and implement keywords.
e) Differentiate class, abstract class and interface.
f) Give the basic keywords used in exception handling.
h) How to create and use a package in Java program?
i) What is an assertion? What is its use in programming?
j) What is abstract class? Discuss with example.
k) What is the difference between an interface and an abstract class?
l) "Abstract classes can be defined without any abstract methods" - support this statement with
proper reasoning.

Part-B
1. a) Write an example program to show the calling sequence of constructors.
b) How to create packages and use them in java?
2. a) What is an exception? Explain exception handling in java with examples.
b) Write a program to implement multiple inheritances.
3. Give a detail note on interfaces and packages in java with examples.
4. What is inheritance? Explain in detail inheritance in java with examples.
5. a) Differentiate method overloading with method overriding with examples.
b) What is interface? How to create it and access it? Explain with example.
6. a) With suitable code segments illustrate various uses of ‘final’ keyword.
b) How to handle multiple catch blocks for a nested try block? Explain with an example.
7. a) Explain multilevel inheritance with the help of abstract class in your program.
b) How to define a user exception in a program? Illustrate with an example.
8. a) How Packages differ from Interfaces? Explain it with a suitable example program to
calculate student marks statement.
b) What is an exception? How are exceptions handled in Java programming? Explain
9. What are the benefits of inheritance? Explain various forms of inheritance with suitable code
segments.
10. a) What are different types of inheritances? Discuss with examples for each.
.b) Write short notes on Java built in exceptions and chained exceptions.
11. a) What are the different forms of inheritance? Explain.
b) What are the various types of exceptions available in Java? Also discuss on how they are handled?
12. b) Explain various access specifies supported by Java with an example
13. a) Explain Creating Packages and Accessing a Package with examples.
b) Write a Java program to find the area and perimeter of square and circle using interface
14. a) Explain about Exception Handling in Java with examples.
b) Explain how final keyword is used to prevent overriding and inheritance.
15. What is meant by access protection? Explain different access specifiers supported by Java with
an example of each.
16. a) What is the use of super keyword in Java? Explain in detail.
b) What is the importance of abstract classes? Show it with an example.
17. a)What is an interface? Explain the definition and implementation of interface in Java.
b) Explain usage of following words in exception handling: throw, throws, finally.
18. a) What is meant by multilevel hierarchy? Explain with an example program in Java.
b) Illustrate the concept of method overriding with an example program.
19. a) Define package? Explain the process of finding a package.
b) Write a short note on i) Nested Interfaces. ii) Difference between class and interfaces.
20. a) Write a program to illustrate the usage of try and catch blocks in Java.
b) What is CLASSPATH? Explain its role in finding packages.
21. a) What cautions need to be taken while importing Explain with an example program for importing
packages?
b) What is an exception? Write about the fundamentals of exception handling used in Java.
Java programming-assignment-3
Part-A

a) What happens when there is no suitable try block to handle exception?


b) Why to use finally block in java exception handling.
c) How java supports multiple inheritance?
d) Differentiate class, abstract class and interface.
e) How to create and use a package in Java program?
f) What is an assertion? What is its use in programming?
g) "Abstract classes can be defined without any abstract methods" - support this statement with
proper reasoning.
h) What are the benefits of inheritance?
i) What are the various types of exceptions available in Java?

Part-B

1. a) How to create packages and use them in java?


b) What is an exception? Explain exception handling in java with examples.
2. a) Differentiate method overloading with method overriding with examples.
b) What is interface? How to create it and access it? Explain with example.
3. a) With suitable code segments illustrate various uses of ‘final’ keyword.
b) How to handle multiple catch blocks for a nested try block? Explain with an example.
4. a) Explain multilevel inheritance with the help of abstract class in your program.
b) How to define a user exception in a program? Illustrate with an example.
5.a) Explain various forms of inheritance with suitable code segments.
b) How Packages differ from Interfaces?
6. a) What is the importance of abstract classes? Show it with an example.
b) Explain various access specifies supported by Java with an example

Programs

a) Write an example program to show the calling sequence of constructors.


b) Write a program to implement multiple inheritances.
c) Write a Java program to find the area and perimeter of square and circle using interface
d) Write a program to illustrate the usage of try and catch blocks in Java.

You might also like