JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword,...

60
1 JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using packages, importance of CLASSPATH and java.lang package. Exception handling, importance of try, catch, throw, throws and finally block, user defined exceptions, Assertions.. Inheritance:- The process of getting properties and behaviors from one class to another class is called inheritance. Properties : variables Behaviors : methods 1. The main purpose of the inheritance is code extensibility whenever we are extending automatically the code is reused. 2. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. 3. Inheritance is also known as is-a relationship means two classes are belongs to the same hierarchy. 4. By using extends keyword we are achieving inheritance concept. 5. In the inheritance the person who is giving the properties is called parent the person who is taking the properties is called child. 6. To reduce length of the code and redundancy of the code sun peoples introducing inheritance concept. Why use inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Different types of inheritance: Below are the different types of inheritance which is supported by Java. Single Inheritance Multiple Inheritance (Through Interface) Multilevel Inheritance Hierarchical Inheritance Hybrid Inheritance (Through Interface) Lets see about each one of them one by one. 1. Single Inheritance in Java Single Inheritance is the simple inheritance of all, When a class extends a`nother class(Only one class) then we call it as Single inheritance. The below diagram represents the single inheritance in java where Class B extends only one class Class A. Here Class B will be

Transcript of JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword,...

Page 1: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

1

JAVA PROGRAMMING UNIT-III:

Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class.

Interfaces, creating the packages, using packages, importance of CLASSPATH and java.lang

package. Exception handling, importance of try, catch, throw, throws and finally block, user

defined exceptions, Assertions..

Inheritance:- The process of getting properties and behaviors from one class to another class is called

inheritance.

Properties : variables

Behaviors : methods

1. The main purpose of the inheritance is code extensibility whenever we are

extending automatically the code is reused.

2. The idea behind inheritance in java is that you can create new classes that are

built upon existing classes.

3. Inheritance is also known as is-a relationship means two classes are belongs to the same

hierarchy.

4. By using extends keyword we are achieving inheritance concept.

5. In the inheritance the person who is giving the properties is called parent the

person who is taking the properties is called child.

6. To reduce length of the code and redundancy of the code sun peoples introducing

inheritance concept.

Why use inheritance in java

● For Method Overriding (so runtime polymorphism can be achieved).

● For Code Reusability.

Different types of inheritance:

Below are the different types of inheritance which is supported by Java.

Single Inheritance

Multiple Inheritance (Through Interface)

Multilevel Inheritance

Hierarchical Inheritance

Hybrid Inheritance (Through Interface)

Lets see about each one of them one by one.

1. Single Inheritance in Java

Single Inheritance is the simple inheritance of all, When a class extends a`nother class(Only

one class) then we call it as Single inheritance. The below diagram represents the single

inheritance in java where Class B extends only one class Class A. Here Class B will be

Page 2: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

2

the Sub class and Class A will be one and only Super class.

Single Inheritance Example

public class ClassA

{

public void dispA()

{

System.out.println("disp() method of ClassA");

}

}

public class ClassB extends ClassA

{

public void dispB()

{

System.out.println("disp() method of ClassB");

}

public static void main(String args[])

{

//Assigning ClassB object to ClassB reference

ClassB b = new ClassB();

//call dispA() method of ClassA

b.dispA();

//call dispB() method of ClassB

b.dispB();

}

}

Output :

disp() method of ClassA

Page 3: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

3

disp() method of ClassB

2. Multiple Inheritance in Java

Multiple Inheritance is nothing but one class extending more than one class. Multiple

Inheritance is basically not supported by many Object Oriented Programming languages

such as Java, Small Talk, C# etc.. (C++ Supports Multiple Inheritance). As

the Child class has to manage the dependency of more than one Parent class. But you can

achieve multiple inheritance in Java using Interfaces.

// Java program to illustrate the

// concept of Multiple inheritance

import java.util.*;

import java.lang.*;

import java.io.*;

interface one

{

public void print_geek();

}

interface two

{

public void print_for();

}

interface three extends one,two

{

public void print_geek();

}

class child implements three

{

@Override

public void print_geek() {

System.out.println("Geeks");

Page 4: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

4

}

public void print_for()

{

System.out.println("for");

}

}

// Drived class

public class Main

{

public static void main(String[] args)

{

child c = new child();

c.print_geek();

c.print_for();

c.print_geek();

}

}

3. Multilevel Inheritance in Java

In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the

derived class act as the parent class to other class. As seen in the below

diagram. ClassB inherits the property of ClassA and again ClassB act as a parent for ClassC.

In Short ClassA parent for ClassB and ClassB parent for ClassC.

MultiLevel Inheritance Example

public class ClassA

{

public void dispA()

{

System.out.println("disp() method of ClassA");

Page 5: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

5

}

}

public class ClassB extends ClassA

{

public void dispB()

{

System.out.println("disp() method of ClassB");

}

}

public class ClassC extends ClassB

{

public void dispC()

{

System.out.println("disp() method of ClassC");

}

public static void main(String args[])

{

//Assigning ClassC object to ClassC reference

ClassC c = new ClassC();

//call dispA() method of ClassA

c.dispA();

//call dispB() method of ClassB

c.dispB();

//call dispC() method of ClassC

c.dispC();

}

}

Output :

disp() method of ClassA

disp() method of ClassB

disp() method of ClassC

4. Hierarchical Inheritance in Java

In Hierarchical inheritance one parent class will be inherited by many sub classes. As per

the below example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will be

acting as a parent class for ClassB, ClassC and ClassD.

Page 6: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

6

Hierarchical Inheritance Example

public class ClassA

{

public void dispA()

{

System.out.println("disp() method of ClassA");

}

}

public class ClassB extends ClassA

{

public void dispB()

{

System.out.println("disp() method of ClassB");

}

}

public class ClassC extends ClassA

{

public void dispC()

{

System.out.println("disp() method of ClassC");

}

}

public class ClassD extends ClassA

{

public void dispD()

{

System.out.println("disp() method of ClassD");

Page 7: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

7

}

}

public class HierarchicalInheritanceTest

{

public static void main(String args[])

{

//Assigning ClassB object to ClassB reference

ClassB b = new ClassB();

//call dispB() method of ClassB

b.dispB();

//call dispA() method of ClassA

b.dispA();

//Assigning ClassC object to ClassC reference

ClassC c = new ClassC();

//call dispC() method of ClassC

c.dispC();

//call dispA() method of ClassA

c.dispA();

//Assigning ClassD object to ClassD reference

ClassD d = new ClassD();

//call dispD() method of ClassD

d.dispD();

//call dispA() method of ClassA

d.dispA();

}

}

Output :

disp() method of ClassB

disp() method of ClassA

disp() method of ClassC

disp() method of ClassA

disp() method of ClassD

disp() method of ClassA

5. Hybrid Inheritance in Java

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again Hybrid

Page 8: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

8

inheritance is also not directly supported in Java only through interface we can achieve this.

Flow diagram of the Hybrid inheritance will look like below. As you can ClassA will be

acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be acting

as Parent for ClassD.

class A

{

Void m1() parent class/

Void m2() super class/

Void m3() base class

}

class B extends A

{

Void m4()

Void m5() derived class

}

Class C extends B

{

Void m6();

}

Note 1:- It is possible to create objects for both parent and child classes.

a. If we are creating object for parent class it is possible to call only parent specific

methods.

A a=new

A();

a.m1();

a.m2();

Page 9: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

9

a.m3();

b. if we are creating object for child class it is possible to call parent specific and child

specific.

B b=new B(); b.m1(); b.m2();

b.m3(); b.m4(); b.m5();

c. if we are creating object for child class it is possible to call parent specific methods

and child specific methods.

C c=new

C();

c.m1();

c.m2();

c.m3();

c.m4();

c.m5();

c.m6();

Note:- 1. Every class in the java programming is a child class of object.

2. The root class for all java classes is Object class.

3. The default package in the java programming is java.lang package.

Both declarations are same:-

class Test { };

class String

{ };

class Test extends Object { };

class String extends Object

{ };

Super:

The super keyword in java is a reference variable which is used to refer immediate parent class

object. Whenever you create the instance of subclass, an instance of parent class is created

implicitly which is referred by super reference variable.

Super keyword is used to represent

1) Call the Super class variable.

2) Call the super class constructor.

3) Call the super class methods.

Calling of super class variables:-

Super keyword is not required class Parent {

int a=10;

Super keyword is required class Test1 {

int a=10;

Page 10: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

10

int b=20; };

class Child extends Parent

{

int x=100;

int y=200; void add(int i,int j) {

System.out.println(i+j);

System.out.println(x+y);

System.out.println(a+b);

}

public static void main(String[] args)

{

Child c=new Child();

c.add(1000,2000);

} };

int b=20; };

class Test extends Test1

{

int a=100;

int b=200; void add(int a,int b) {

System.out.println(a+b);

System.out.println(this.a+this.b); System.out.println(super.a+super.b);

}

public static void main(String[] args)

{ Test t=new Test(); t.add(1000,2000);

}

};

Calling of super class methods:-

Super keyword is not required

class Parent

{

void m1()

{

System.out.println("parent class method");

}

};

class Child extends Parent

{

void m2()

{

m1(); System.out.println("child class method");

}

void m3()

{

m1(); System.out.println("child class method");

m2();

}

public static void main(String[] arhs)

Super keyword is required

class Parent

{

void m1()

{

System.out.println("parent class method");

}

};

class Child extends Parent

{

void m1()

{

System.out.println("child class method");

}

void m2()

{

this.m1(); System.out.println("child class

method");

super.m1();

}

Page 11: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

11

{

Child c=new Child();

c.m3();

}}

public static void main(String[] arhs)

{

Child c=new Child();

c.m2();}};

Calling of super class constructors:-

Ex 1:- inside the constructors super keyword must be first statement of the constructor otherwise

the compiler raise compilation error.

No compilation error class Test1

{

Test1(int i,int j)

{

System.out.println(i);

System.out.println(j);

System.out.println("two arg constructor");

}

}; class Test extends Test1 {

Test(int i)

{

super(100,200); System.out.println("int -arg constructor");

}

public static void main(String[] args)

{ Test t=new Test(10);

} }

Compilation error

class Test1

{

Test1(int i,int j)

{

System.out.println(i); System.out.println(j);

System.out.println("two arg constructor");

}

};

class Test extends Test1

{

Test(int i)

{

System.out.println("int -arg constructor");

super(100,200);

}

public static void main(String[] args)

{

Test t=new Test(10);

}

}

Note: -

Inside the constructors it is possible to call only one constructor at a time that calling

must be first statement of the constructor.

Inside the constructor if we are providing super and this key words at that situation the

Compiler will place the zero argument “super ();” keyword at first line of the

constructors.

If we are declaring any constructor calling then compiler won’t generate any type of

keywords.

Page 12: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

12

Strictfp:-

Strictfp is a modifier applicable for classes and methods.

If a method is declared as strictfp all floating point calculations in that method will

follow IEEE754 standard. So that we will get platform independent results.

If a class is declared as strictfp then every concrete method in that class will

follow IEEE754 standard so we will get platform independent results.

Native:-

Native is the modifier only for methods but not for variables and classes.

The native methods are implemented in some other languages like C and C++ hence

native methods also known as “foreign method”.

For native methods implementation is always available in other languages and we are

not responsible to provide implementation hence native method declaration should

compulsory ends with “;”.

Ex: - public native String intern ();

Public static native void yield ();

Public static native void sleep (long);

Final Keyword:-

Final is the modifier applicable for classes, methods and variables (for all instance,

Static and local variables).

If a class is declared as final, then we cannot inherit that class i.e., we cannot create

any child class for that final class.

Every method present inside a final class is always final by default but every variable

present inside the final class need not be final.

The main advantage of final modifier is we can achieve security as no one can be

allowed to change our implementation.

But the main disadvantage of final keyword is we are missing key benefits of Oops

like inheritance and polymorphism. Hence is there is no specific requirement never

recommended to use final modifier.

Case 1:-

Ex :-overriding the method is possible.

class Parent

{

void andhra()

{

System.out.println("Andhra Pradesh");

Ex:- overrding the method is not possible

class Parent

{

void andhra()

{

System.out.println("Andhra Pradesh");

Page 13: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

13

}

}

class Child extends Parent

{

void andhra()

{

System.out.println("division is not possible");

}

public static void main(String[] args)

{

Child c=new Child();

c.andhra();

}

};

}

}

class Child extends Parent

{

final void andhra()

{

System.out.println("division is not possible");

}

public static void main(String[] args)

{

Child c=new Child();

c.andhra();

}

};

Case 2:-

child class creation is possible

class Parent

{

};

class Child extends Parent

{

};

child class creation is not possible getting

compilation error.

final class Parent

{

};

class Child extends Parent

{

};

Case 3:-

Reassignment is possible.

class Test

{

public static void main(String[] args)

{

int a=10; a=a+10;

System.out.println(a);

}

};

For the final variables reassignment is not

possible.

class Test

{

public static void main(String[] args)

{

final int a=10; a=a+10;

System.out.println(a);

}

};

Page 14: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

14

Note:-

Every method present inside a final class is always final by default but every variable

present inside the final class need not be final.

final class Test

{

int a=10;

void m1()

{

System.out.println("m1 method is final");

System.out.println(a+10);

}

public static void main(String[] args)

{

Test t=new Test();

t.m1();

}

}

Polymorphism is one of the OOPs features that allow us to perform a single action in different

ways. For example,

Let’s say we have a class Animal that has a method sound(). Since this is a generic class so we

can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a generic message.

As you can see that although we had the common action for all subclasses sound() but there were

different ways to do the same action. This is a perfect example of polymorphism (feature that

allows us to perform a single action in different ways). It would not make any sense to just call

the generic sound() method as each Animal has a different sound. Thus we can say that the

action this method performs is based on the type of object.

What is polymorphism in programming?

Polymorphism is the capability of a method to do different things based on the object that

it is acting upon. In other words, polymorphism allows you define one interface and have

multiple implementations. As we have seen in the above example that we have defined the

method sound() and have the multiple implementations of it in the different-2 sub classes.

Which sound() method will be called is determined at runtime so the example we gave above is

a runtime polymorphism example.

Page 15: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

15

Types of polymorphism

1. Method Overloading in Java – This is an example of compile time (or static polymorphism)

2. Method Overriding in Java – This is an example of runtime time (or dynamic polymorphism)

Static Polymorphism

Method Overloading is a feature that allows a class to have more than one method having

the same name, if their argument lists are different. It is similar to constructor overloading in

Java that allows a class to have more than one constructor having different argument lists.

Three ways to overload a method

In order to overload a method, the argument lists of the methods must differ in either of these:

1. Number of parameters.

For example: This is a valid case of overloading

add(int, int)

add(int, int, int)

2. Data type of parameters.

For example:

add(int, int)

add(int, float)

3. Sequence of Data type of parameters.

For example:

add(int, float)

add(float, int)

Invalid case of method overloading:

When I say argument list, I am not talking about return type of the method, for example if

two methods have same name, same parameters and have different return type, then this is not a

valid method overloading example. This will throw compilation error.

int add(int, int)

float add(int, int)

Page 16: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

16

Method overloading:-

Ex:-

class Test

{

void m1(char ch)

{

System.out.println(" char-arg constructor ");

}

void m1(int i)

{ Overloaded Methods

System.out.println("int-arg constructor ");

}

void m1(int i,int j)

{

System.out.println(i+"------"+j);

}

public static void main(String[] args)

{

Test t=new Test();

t.m1('a');

t.m1(10);

t.m1(10,20);

}

}

Method Overloading and Type Promotion

When a data type of smaller size is promoted to the data type of bigger size than this is called

type promotion, for example: byte data type can be promoted to short, a short data type can be

promoted to int, long, double etc.

What it has to do with method overloading?

Well, it is very important to understand type promotion else you will think that the program will

throw compilation error but in fact that program will run fine because of type promotion.

Lets take an example to see what I am talking here:

class Demo{

void disp(int a, double b){

System.out.println("Method A");

}

void disp(int a, double b, double c){

System.out.println("Method B");

}

public static void main(String args[]){

Page 17: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

17

Demo obj = new Demo();

/* I am passing float value as a second argument but

* it got promoted to the type double, because there

* wasn't any method having arg list as (int, float)

*/

obj.disp(100, 20.67f);

}

}

Dynamic Polymorphism:

Suppose a sub class overrides a particular method of the super class. Let’s say, in the program

we create an object of the subclass and assign it to the super class reference. Now, if we call the

overridden method on the super class reference then the sub class version of the method will be

called.

Have a look at the following example.

class Vehicle{

public void move(){

System.out.println(“Vehicles can move!!”);

}

}

class MotorBike extends Vehicle{

public void move(){

System.out.println(“MotorBike can move and accelerate too!!”);

}

}

class Test{

public static void main(String[] args){

Vehicle vh=new MotorBike();

vh.move(); // prints MotorBike can move and accelerate too!!

vh=new Vehicle();

vh.move(); // prints Vehicles can move!!

}

}

It should be noted that in the first call to move(), the reference type is Vehicle and the object

being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to

determine which object is actually being pointed to by the reference. In this case, the object is of

the class MotorBike. So, the move() method of MotorBike class will be called. In the second call

to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.

Page 18: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

18

Difference between method overloading and method overriding in java

There are many differences between method overloading and method overriding in java. A list of

differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the

readability of the program.

Method overriding is used to provide

the specific implementation of the

method that is already provided by its

super class.

2) Method overloading is performed within class. Method overriding occurs in two

classes that have IS-A (inheritance)

relationship.

3) In case of method overloading, parameter must be

different.

In case of method

overriding, parameter must be same.

4) Method overloading is the example of compile

time polymorphism.

Method overriding is the example

of run time polymorphism.

5) In java, method overloading can't be performed by

changing return type of the method only. Return

type can be same or different in method

overloading. But you must have to change the

parameter.

Return type must be same or

covariant in method overriding.

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can

have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to

the user.

Another way, it shows only essential things to the user and hides the internal details, for

example, sending SMS where you type the text and send the message. You don't know the

internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

Page 19: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

19

2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-

abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember

An abstract class must be declared with an abstract keyword.

It can have abstract and non-abstract methods.

It cannot be instantiated.

It can have constructors and static methods also.

It can have final methods which will force the subclass not to change the body of the

method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an

abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its

implementation is provided by the Honda class.

1. abstract class Bike{

2. abstract void run();

3. }

4. class Honda4 extends Bike{

5. void run(){System.out.println("running safely");}

6. public static void main(String args[]){

7. Bike obj = new Honda4();

8. obj.run();

9. }

10. }

running safely

Page 20: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

20

Understanding the real scenario of Abstract class

In this example, Shape is the abstract class, and its implementation is provided by the Rectangle

and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an

object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the

factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class

will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{

2. abstract void draw();

3. }

4. //In real scenario, implementation is provided by others i.e. unknown by end user

5. class Rectangle extends Shape{

6. void draw(){System.out.println("drawing rectangle");}

7. }

8. class Circle1 extends Shape{

9. void draw(){System.out.println("drawing circle");}

10. }

11. //In real scenario, method is called by programmer or user

12. class TestAbstraction1{

13. public static void main(String args[]){

14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getSh

ape() method

15. s.draw();

16. }

17. }

drawing circle

Interfaces

1. Interface is also one of the type of class it contains only abstract methods.

2. For the interfaces also .class files will be generated.

3. Each and every interface by default abstract hence it is not possible to create an object.

4. Interfaces not alternative for abstract class it is extension for abstract classes.

5. 100 % pure abstract class is called interface.

6. The Interface contains only abstract methods means unimplemented methods.

7. Interfaces giving the information about the functionalities it are not giving the information

about internal implementation.

Page 21: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

21

8. To provide implementation for abstract methods we have to take separate class that class we

can called it as implementation class for that interface.

9. Interface can be implemented by using implements keyword.

10. For the interfaces also the inheritance concept is applicable.

11. An interface can extend multiple interfaces but a class cannot extend multiple classes.

12. Extends and implements both keywords can be used in same line of code but extends should

be first keyword then implements.

13. An interface can be declare inside the class is called nested interface.

14. An interface can be declare inside the another interface is called nested interface.

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. A class that implements an interface must implement all the methods

declared in the interface.

Syntax:

1. interface <interface_name>{

2.

3. // declare constant fields

4. // declare methods that abstract

5. // by default.

6. }

Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is discussed later.

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.

In other words, Interface fields are public, static and final by default, and the methods are public

and abstract.

The relationship between classes and interfaces

Page 22: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

22

As shown in the figure given below, a class extends another class, an interface extends another

interface, but a class implements an interface.

Java Interface Example

In this example, the Printable interface has only one method, and its implementation is provided

in the A6 class.

1. interface printable{

2. void print();

3. }

4. class A6 implements printable{

5. public void print(){System.out.println("Hello");}

6.

7. public static void main(String args[]){

8. A6 obj = new A6();

9. obj.print();

10. }

11. }

Output:

Hello

Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided by

Rectangle and Circle classes. 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.

File: TestInterface1.java

1. //Interface declaration: by first user

2. interface Drawable{

3. void draw();

Page 23: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

23

4. }

5. //Implementation: by second user

6. class Rectangle implements Drawable{

7. public void draw(){System.out.println("drawing rectangle");}

8. }

9. class Circle implements Drawable{

10. public void draw(){System.out.println("drawing circle");}

11. }

12. //Using interface: by third user

13. class TestInterface1{

14. public static void main(String args[]){

15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawab

le()

16. d.draw();

17. }}

Output:

drawing circle

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

1. interface Bank{

2. float rateOfInterest();

3. }

4. class SBI implements Bank{

5. public float rateOfInterest(){return 9.15f;}

6. }

7. class PNB implements Bank{

8. public float rateOfInterest(){return 9.7f;}

9. }

10. class TestInterface2{

11. public static void main(String[] args){

12. Bank b=new SBI();

13. System.out.println("ROI: "+b.rateOfInterest());

14. }}

Output:

ROI: 9.15

Page 24: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

24

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known

as multiple inheritance.

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();

13. obj.print();

14. obj.show();

15. }

16. }

Output:Hello

Welcome

Q) Multiple inheritance is not supported through class in java, but it is possible by an interface,

why?

As we have explained in the inheritance chapter, 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. For

example:

Page 25: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

25

1. interface Printable{

2. void print();

3. }

4. interface Showable{

5. void print();

6. }

7.

8. class TestInterface3 implements Printable, Showable{

9. public void print(){System.out.println("Hello");}

10. public static void main(String args[]){

11. TestInterface3 obj = new TestInterface3();

12. obj.print();

13. }

14. }

Output:

Hello

As you can see in the above example, Printable and Showable interface have same methods but

its implementation is provided by class TestTnterface1, so there is no ambiguity.

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();

14. obj.show();

15. }

16. }

Output:

Hello

Welcome

Page 26: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

26

Java 8 Default Method in Interface

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

Let's see an example:

File: TestInterfaceDefault.java

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:

drawing rectangle

default method

Java 8 Static Method in Interface

Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1. interface Drawable{

2. void draw();

3. static int cube(int x){return x*x*x;}

4. }

5. class Rectangle implements Drawable{

6. public void draw(){System.out.println("drawing rectangle");}

7. }

8.

9. class TestInterfaceStatic{

10. public static void main(String args[]){

11. Drawable d=new Rectangle();

12. d.draw();

13. System.out.println(Drawable.cube(3));

14. }}

Output:

drawing rectangle

27

Page 27: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

27

Q) What is marker or tagged interface?

An interface which has no member is known as a marker or tagged interface, for example,

Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the

JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?

2. public interface Serializable{

3. }

Nested Interface in Java

Note: An interface can have another interface which is known as a nested interface. We will

learn it in detail in the nested classes chapter. For example:

1. interface printable{

2. void print();

3. interface MessagePrintable{

4. void msg();

5. }

6. }

Adaptor class:-

It is a intermediate class between the interface and user defined class. And it contains

empty implementation of interface methods.

Limitation of interface

interface it

{

void m1();

void m2();

;

;

void m100()

}

Class Test implements it

{

Must provide implementation of 100 methods

otherwise compiler raise compilation error

}

advantage of adaptor classes

interface it

{

void m1();

void m2();

;

;

void m100() } class Adaptor implements it

{

void m1(){}

void m2(){}

;

; void m100(){} }

class Test implements it

{

must provide the 100 methods implementation

Page 28: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

28

};

class Test extends Adaptor

{

provide the implementation of required

methods.

};

Differences between abstract class and interface

Abstract class Interface

1) Abstract class can have abstract and

non-abstract methods.

Interface can have only abstract methods. Since Java 8, it can

have default and static methods also.

2) Abstract class doesn't support multiple

inheritance.

Interface supports multiple inheritance.

3) Abstract class can have final, non-final,

static and non-static variables.

Interface has only static and final variables.

4) Abstract class can provide the

implementation of interface.

Interface can't provide the implementation of abstract class.

5) The abstract keyword is used to declare

abstract class.

The interface keyword is used to declare interface.

6) An abstract class can extend another

Java class and implement multiple Java

interfaces.

An interface can extend another Java interface only.

7) An abstract class can be extended using

keyword "extends".

An interface can be implemented using keyword "implements".

8) A Java abstract class can have class

members like private, protected, etc.

Members of a Java interface are public by default.

9)Example:

public abstract class Shape{

public abstract void draw();

}

Example:

public interface Drawable{

void draw();

}

Page 29: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

29

Abstract class and interface both are used to achieve abstraction where we can declare the

abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully

abstraction (100%).

Packages:-

A package as the name suggests is a pack(group) of classes, interfaces and other packages. In

java we use packages to organize our classes and interfaces. We have two types of packages in

Java: built-in packages and the packages we can create (also known as user defined package).

1) The package contains group of related classes and interfaces.

2) The package is an encapsulation mechanism it is binding the related classes and interfaces.

3) We can declare a package with the help of package keyword.

4) Package is nothing but physical directory structure and it is providing clear-cut separation

between the project modules.

5) Whenever we are dividing the project into the packages (modules) the reusability of the

project will be increased.

6) java.lang is predefined package which can be included without specifying it and it is top most

package in java.

In java we have several built-in packages, for example when we need user input, we import a

package like this:

import java.util.Scanner

Here:

→ java is a top level package

→ util is a sub package

→ and Scanner is a class which is present in the sub package util.

Advantages of using a package in Java

These are the reasons why you should use packages in Java:

Reusability: While developing a project in java, we often feel that there are few things

that we are writing again and again in our code. Using packages, you can create such

things in form of classes inside a package and whenever you need to perform that same

task, just import that package and use the class.

Better Organization: Again, in large java projects where we have several hundreds of

classes, it is always required to group the similar types of classes in a meaningful package

Page 30: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

30

name so that you can organize your project better and when you need something you can

quickly locate it and use it, which improves the efficiency.

Name Conflicts: We can define two classes with the same name in different packages so

to avoid name collision, we can use packages

Syntax:-

package package-name;

Ex: -package com.dss;

The packages are divided into two types

1) Predefined packages

2) User defined packages

Predefined packages:-

The java predefined packages are introduced by sun peoples these packages contains predefined

classes and interfaces.

Ex:-

java.lang

Java.io

Java.awt

Java.util

Java.net………………………..etc

Java.lang:-

The most commonly required classes and interfaces to write a sample program is encapsulated

into a separate package is called java.lang package.

`Ex:-

String(class)

StringBuffer(class)

Object(class)

Runnable(interface)

Cloneable(nterface)

Java.io package:-

The classes which are used to perform the input output operations that are present in the java.io

packages.

Ex:-

FileInputStream(class)

Page 31: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

31

FileOutputStream(class)

FileWriter(class)

FileReader(class)

User Defined Packages:

Example 1: Java packages

I have created a class Calculator inside a package name letmecalculate. To create a class

inside a package, declare the package name in the first statement in your program. A class can

have only one package declaration.

Calculator.java file created inside a package letmecalculate

package letmecalculate;

public class Calculator {

public int add(int a, int b){

return a+b;

}

public static void main(String args[]){

Calculator obj = new Calculator();

System.out.println(obj.add(10, 20));

}

}

Now let’s see how to use this package in another program.

import letmecalculate.Calculator;

public class Demo{

public static void main(String args[]){

Calculator obj = new Calculator();

System.out.println(obj.add(100, 200));

}

}

To use the class Calculator, I have imported the package letmecalculate. In the above program I

have imported the package as letmecalculate.Calculator, this only imports the Calculator class.

However if you have several classes inside package letmecalculate then you can import the

package like this, to use all the classes of this package.

Page 32: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

32

import letmecalculate.*;

Example 2: Creating a class inside package while importing another package

As we have seen that both package declaration and package import should be the first

statement in your java program. Let’s see what should be the order when we are creating a class

inside a package while importing another package.

//Declaring a package

package anotherpackage;

//importing a package

import letmecalculate.Calculator;

public class Example{

public static void main(String args[]){

Calculator obj = new Calculator();

System.out.println(obj.add(100, 200));

}

}

So the order in this case should be:

→ package declaration

→ package import

Example 3: Using fully qualified name while importing a class

You can use fully qualified name to avoid the import statement. Let’s see an example to

understand this:

Calculator.java

package letmecalculate;

public class Calculator {

public int add(int a, int b){

return a+b;

}

public static void main(String args[]){

Calculator obj = new Calculator();

System.out.println (obj.add(10, 20));

Page 33: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

33

}

}

Example.java

//Declaring a package

package anotherpackage;

public class Example{

public static void main(String args[]){

//Using fully qualified name instead of import

letmecalculate.Calculator obj =

new letmecalculate.Calculator();

System.out.println(obj.add(100, 200));

}

}

In the Example class, instead of importing the package, I have used the full qualified name such

as package_name.class_name to create the object of it. You may also want to read: static import

in Java

Sub packages in Java

A package inside another package is known as sub package. For example If I create a

package inside letmecalculate package then that will be called sub package.

Let’s say I have created another package inside letmecalculate and the sub package name

is multiply. So if I create a class in this subpackage it should have this package declaration in the

beginning:

package letmecalculate.multiply;

Multiplication.java

package letmecalculate.multiply;

public class Multiplication {

int product(int a, int b){

return a*b;

}

}

Page 34: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

34

Now if I need to use this Multiplication class I have to either import the package like this:

import letmecalculate.multiply;

or I can use fully qualified name like this:

letmecalculate.multiply.Multiplication obj =

new letmecalculate.multiply.Multiplication();

Points to remember:

1. Sometimes class name conflict may occur. For example: Let’s say we have two

packages abcpackage and xyzpackage and both the packages have a class with the same name,

let it be JavaExample.java. Now suppose a class import both these packages like this:

import abcpackage.*;

import xyzpackage.*;

This will throw compilation error. To avoid such errors you need to use the fully qualified name

method that I have shown above. For example

abcpackage.JavaExample obj = new abcpackage.JavaExample();

xyzpackage.JavaExample obj2 = new xyzpackage.JavaExample();

This way you can avoid the import package statements and avoid that name conflict error.

2. I have already discussed this above, let me mention it again here. If we create a class inside a

package while importing another package then the package declaration should be the first

statement, followed by package import. For example:

package abcpackage;

import xyzpackage.*;

3. A class can have only one package declaration but it can have more than one package import

statements. For example:

package abcpackage; //This should be one

import xyzpackage;

import anotherpackage;

import anything;

Page 35: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

35

4. The wild card import like package.* should be used carefully when working with sub

packages. For example: Let’s say: we have a package abc and inside that package we have

another package foo, now foo is a subpackage.

classes inside abc are: Example1, Example 2, Example 3

classes inside foo are: Demo1, Demo2

So if I import the package abc using wildcard like this:

import abc.*;

Then it will only import classes Example1, Example2 and Example3 but it will not import the

classes of sub package.

To import the classes of subpackage you need to import like this:

import abc.foo.*;

This will import Demo1 and Demo2 but it will not import the Example1, Example2 and

Example3.

So to import all the classes present in package and subpackage, we need to use two import

statements like this:

import abc.*;

import abc.foo.*;

Note:-

If the source file contains the package statement then we have to compile that program with the

help of fallowing statements.

D:\>javac -d . Test.java

Javac: java compiler

-d : telling the compiler that to create separate directory

. :- place the created directory in present working directory.

Test.java :- java source file

For example the source file contains the package structure is like this:-

Package com.sbi.bank.deposit;

Page 36: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

36

After compilation of the code the folder structure is as shown below.

Com

|

|------sbi

|

|-------bank

|

|----deposit

|

|-------- (number of .classes will be generated)

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,

or class. We can change the access level of fields, constructors, methods, and class by applying

the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be

accessed from outside the class.

2. Default: The access level of a default modifier is only within the package. It cannot be

accessed from outside the package. If you do not specify any access level, it will be the

default.

3. Protected: The access level of a protected modifier is within the package and outside the

package through child class. If you do not make the child class, it cannot be accessed

from outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed from

within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,

transient, etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access

Modifier

within class within package outside package

by subclass only

outside package

Private Y N N N

Default Y Y N N

Page 37: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

37

Protected Y Y Y N

Public Y Y Y Y

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data

member and private method. We are accessing these private members from outside the class, so

there is a compile-time error.

1. class A{

2. private int data=40;

3. private void msg(){System.out.println("Hello java");}

4. }

5.

6. public class Simple{

7. public static void main(String args[]){

8. A obj=new A();

9. System.out.println(obj.data);//Compile Time Error

10. obj.msg();//Compile Time Error

11. }

12. }

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from

outside the class. For example:

1. class A{

2. private A(){}//private constructor

3. void msg(){System.out.println("Hello java");}

4. }

5. public class Simple{

6. public static void main(String args[]){

7. A obj=new A();//Compile Time Error

8. }

9. }

Note: A class cannot be private or protected except nested class.

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is

accessible only within package. It cannot be accessed from outside the package. It provides more

accessibility than private. But, it is more restrictive than protected, and public.

Page 38: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

38

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class

from outside its package, since A class is not public, so it cannot be accessed from outside the

package.

1. //save by A.java

2. package pack;

3. class A{

4. void msg(){System.out.println("Hello");}

5. }

1. //save by B.java

2. package mypack;

3. import pack.*;

4. class B{

5. public static void main(String args[]){

6. A obj = new A();//Compile Time Error

7. obj.msg();//Compile Time Error

8. }

9. }

In the above example, the scope of class A and its method msg() is default so it cannot be

accessed from outside the package.

3) Protected

The protected access modifier is accessible within package and outside the package but through

inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It

can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack

package is public, so can be accessed from outside the package. But msg method of this package

is declared as protected, so it can be accessed from outside the class only through inheritance.

1. //save by A.java

2. package pack;

3. public class A{

4. protected void msg(){System.out.println("Hello");}

5. }

1. //save by B.java

2. package mypack;

3. import pack.*;

4.

5. class B extends A{

Page 39: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

39

6. public static void main(String args[]){

7. B obj = new B();

8. obj.msg();

9. }

10. }

Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other

modifiers.

Example of public access modifier

1. //save by A.java

2.

3. package pack;

4. public class A{

5. public void msg(){System.out.println("Hello");}

6. }

1. //save by B.java

2.

3. package mypack;

4. import pack.*;

5.

6. class B{

7. public static void main(String args[]){

8. A obj = new A();

9. obj.msg();

10. }

11. }

Output:Hello

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more

restrictive.

1. class A{

2. protected void msg(){System.out.println("Hello java");}

3. }

4.

5. public class Simple extends A{

6. void msg(){System.out.println("Hello java");}//C.T.Error

7. public static void main(String args[]){

8. Simple obj=new Simple();

Page 40: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

40

9. obj.msg();

10. }

11. }

The default modifier is more restrictive than protected. That is why, there is a compile-time

error.

Importance of PATH, CLASSPATH & JAVA_HOME Environment variables in Java

Environment

ENVIRONMENT VARIABLE

An Environment Variable stores a ‘list’ of path/location/directory (normally separated by a

comma or semi colon ) . These folders contain ‘something’ which is required by a Program,

depending upon the context. For example , PATH environment variable is used by the Operating

System to find the executable files of a particular command. Similarly CLASSPATH

environment variable is used by Java Virtual Machine [JVM] to locate the .class files.

PATH

When a user enters a particular command in Command Prompt[Windows] or Terminal

[Unix/Linux], the Operating System [OS] searches for the executable file of that command in

the current directory [ From where user enters the command ]. If it is not there, OS checks the

values stored in PATH environment variable . These values are nothing but a list of directories

with their absolute paths. OS checks for the executable files of that particular command one by

one in these directories and if it fails to find it in any of these directories, an error will be

displayed.

For example in Windows OS , if a ‘command’ is entered and it does not exist in any of the

directories defined in PATH variable, , below error will be thrown.

‘<command>’ is not recognized as an internal or external command, operable program or

batch file.

We need to use the command ‘javac’ for compiling a Java Program and the command ‘java’ to

run it. So now we know why the directory contains the executables of ‘javac’ and ‘java’ should

be there in the PATH environment variable.

After we installed Java in our machine [ Normally at C:\Program Files\java ], we will have the

‘Root Directory’ of Java created depending upon the version.

Eg : C:\Program Files\Java\jdk1.7.0_45 , if Java version is 1.7.0_45.

And the executable files of the commands like ‘java’ , ‘javac’ etc are inside the ‘bin’ folder

under the Java Root Directory .

That is C:\Program Files\Java\jdk1.7.0_45\bin.

Now if we need to ask the OS to run ‘javac’ or ‘java’, we need to first inform the OS where it is

available. So we need to add this folder path to the PATH Environment variable.

In Windows XP/Later, go to, My Computer ->Properties->Advanced system settings ->

Environment Variables and edit the PATH variable [Under System variable section] by adding

‘C:\Program Files\Java\jdk1.7.0_45\bin’ to it. After that from anywhere in command prompt,

you can run ‘javac’ or java . In Windows OS’s prior to XP, Autoexec.bat file is used to handle

these variables.

Page 41: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

41

JAVA_HOME

To do the above steps in a better way, we can use another Environment variable

‘JAVA_HOME‘ in which the Root Directory of Java will be added. We can define this under

System Variables section of the Environment Variable window mentioned above. Define

JAVA_HOME as new variable and add the Java Root Path to it as value.

JAVA_HOME C:\Program Files\Java\jdk1.7.0_45

Now on wards %JAVA_HOME% is C:\Program Files\Java\jdk1.7.0_45

Now we can edit PATH variable to add %JAVA_HOME%\bin to it.

In Linux/Unix, suppose java is installed at /home/myuser/Java. That is, Java Root Path

is ‘/home/myuser/Java/jdk1.7.0_45’ . We can define the Environment variables as below.

JAVA_HOME= /home/myuser/Java/jdk1.7.0_45

PATH = $PATH:$JAVA_HOME/bin

After that a user can run ‘javac’ and ‘java’ commands from anywhere on the console.

CLASSPATH

The ‘CLASSPATH’ environment variable is used by the JVM to locate the .class files . When

we run a java program using ‘java’ command, the JVM searches for the specified .class file in

all the directories defined in CLASSPATH Environment variable from first to last. By default,

the JVM will search for the specified class/classes in the current directory, where the command

is run. If not found, it will refer the CLASSPATH environment variable.

Suppose the project directory is C:\myuser\project and the java source and class files are

located at C:\myuser\project\source and C:\myuser\project\classes respectively.

Now we should add the path ‘ C:\myuser\project\classes’ to the CLASSPATH environment

variable .

If source file is ‘Test.java’, after compiling it using ‘javac’ , we will get the ‘Test.class’ file

[suppose it is generated in’classes’ directory]. Now when we run this program, [ using the

command ‘ java Test.class‘ ], JVM will search and find the ‘Test.class’ in

C:\myuser\project\classes and run. This .class file contains the generated byte code and the

JVM converts it the machine instructions to run it.

The CLASSPATH variable can contain the path to JAR files as well . That means, a JAR file

can be added to CLASSPATH just like a directory.

java.lang package.

java.lang package in java provides classes that are fundamental to the design of the Java

programming language. The most important classes are Object, which is the root of the class

hierarchy, and Class, instances of which represent classes at run time.

What is the Java lang package ?

The package java.lang contains classes and interfaces that are essential to the Java

programming language. This java.lang package contains Object, Thread, String etc. Object class

is the ultimate super class of all classes in Java. Thread class that controls each thread in a multi

threaded program. The classes in the java.lang package are so essential, the java.lang package is

Page 42: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

42

implicitly imported by every Java source file. In other words, you can refer to all of the classes

and interfaces in java.lang using their simple names.

Do I need to import the java.lang package ?

No, java.lang package is a default package in Java therefore, there is no need to import it

explicitly. i.e. without importing you can access the classes of java.lang package.

Where is Java Lang package ?

The packages that include the class libraries like java.lang.* and java.util.*, these live in the lib

directory under wherever your Java Runtime Environment (JRE) is installed.

Which of the classes are in the Java lang package ?

Wrapper Classes in Java

Frequently it is necessary to represent a value of primitive type as if it were an object. The

wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An

object of type Double, for example, contains a field whose type is double, representing that value

in such a way that a reference to it can be stored in a variable of reference type. These classes

also provide a number of methods for converting among primitive values, as well as supporting

such standard methods as equals and hashCode. All the wrapper classes are available

in java.lang package.

Wrapper classes in Java as follows.

1. Boolean : The Boolean class wraps a value of the primitive type boolean in an object.

2. Byte : The Byte class wraps a value of primitive type byte in an object.

3. Character : The Character class wraps a value of the primitive type char in an object.

4. Short : The Short class wraps a value of primitive type short in an object.

5. Integer : The Integer class wraps a value of the primitive type int in an object.

6. Float : The Float class wraps a value of primitive type float in an object.

7. Long : The Long class wraps a value of the primitive type long in an object.

8. Double : The Double class wraps a value of the primitive type double in an object.

Mathematical Operations Classes in Java

The class Math provides commonly used mathematical functions such as sine, cosine, and square

root. Mathematical classes in Java as follows.

1. Math : The class Math contains methods for performing basic numeric operations such

as the elementary exponential, logarithm, square root, and trigonometric functions.

2. StrictMath : The class StrictMath contains methods for performing basic numeric

operations such as the elementary exponential, logarithm, square root, and trigonometric

functions.

String Operations Classes in Java

The classes String, StringBuffer, and StringBuilder similarly provide commonly used operations

on character strings. String class in Java as follows.

1. String : The String class represents character strings.

2. StringBuffer : A thread-safe, mutable sequence of characters.

3. StringBuilder : A mutable sequence of characters.

Other java.lang package Classes

Page 43: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

43

1. Object : Class Object is the root of the class hierarchy.

2. Class : Instances of the class Class represent classes and interfaces in a running Java

application.

java.lang.Object Class

Object Class in Java

Java Object class is the root of the class hierarchy. Every class has Object as a super class. All

objects, including arrays, implement the methods of this class.

What is java.lang.Object in Java ?

The java.lang.Object is a class in Java . This is the root of the class hierarchy . Object class is

present in java.lang package . Every class in Java is directly or indirectly derived from the

java.lang.Object class . If a Class does not extend any other class then it is direct child class of

Object . the Object class methods are available to all Java classes . Hence Object class acts as a

root of inheritance hierarchy in any Java Program .

What is a class object in Java ?

An object is the instance of the class , which helps programmers to use variables and methods

from inside the class . A class is used to bind data as well as methods together as a single unit .

object acts as a variable of the class . Classes have logical existence. Objects have a physical

existence .

How do you create a class object in Java ?

In Java , the new keyword is used to create new objects .

1. Declaration − A variable declaration with a variable name with an object type .

2. Instantiation − The 'new' keyword is used to create the object .

3. Initialization − The 'new' keyword is followed by a call to a constructor .

What is object type in Java ?

The Object class is the parent class of all the classes in java by default . In other words, it is the

topmost class of Java . The Object class is beneficial if you want to refer any object whose type

you don't know . Notice that parent class reference variable can refer the child class object ,

known as up casting .

What are the common behaviors of all the objects in Java ?

The Object class provides some common behaviors to all the objects such as object can be

compared , object can be cloned , object can be notified etc .

What are the java.lang.Object class methods in Java ?

The java.lang.Object provides a number of methods that are common to all objects . The

toString() is the most common such method . Since the default toString() method only produces

the name of the class . java.lang.Object Class methods helps to perform the various operations

like clone objects , compare objects , get the class name of the object . Following are the List

of java.lang.Object Class Methods or functions .

Modifier and

Type Method Description

Page 44: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

44

Modifier and

Type Method Description

protected Object java.lang.Object.clone() Creates and returns a copy of this object .

boolean java.lang.Object.equals(Object obj) Indicates whether some other object is

"equal to" this one .

protected void java.lang.Object.finalize() Called by the garbage collector on an object

when garbage collection determines that

there are no more references to the object .

Class<?> java.lang.Object.getClass() Returns the runtime class of this Object .

int java.lang.Object.hashCode() Returns a hash code value for the object .

For every object , JVM generates a unique

number which is hashcode . It returns

distinct integers for distinct objects .

Override of hashCode() method needs to be

done such that for every object we generate

a unique number .

void java.lang.Object.notify() Wakes up a single thread that is waiting on

this object's monitor .

void java.lang.Object.notifyAll() Wakes up all threads that are waiting on this

object's monitor .

String java.lang.Object.toString() Returns a string representation of the object

. Whenever we try to print any Object

reference , then internally toString() method

is called .

void java.lang.Object.wait() Causes the current thread to wait until

another thread invokes the notify() method

or the notifyAll() method for this object .

void java.lang.Object.wait(long timeout) Causes the current thread to wait until either

another thread invokes the notify() method

or the notifyAll() method for this object , or

a specified amount of time has elapsed .

void java.lang.Object.wait(long timeout,

int nanos)

Causes the current thread to wait until

another thread invokes the notify() method

or the notifyAll() method for this object , or

some other thread interrupts the current

thread , or a certain amount of real time has

elapsed .

Page 45: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

45

public class ObjectExample2

{

public static void main(String args[])

{

//String CLASS DECLARATION

String s;

//CREATE INSTANCE FOR String CLASS

s = new String("Huda Tutorials");

//Java Object CLASS DECLARATION

Object obj;

//TYPECAST String CLASS INSTANCE TO

//Java Object CLASS INSTANCE

obj = (Object) s;

//Java Object CLASS OUTPUT

System.out.println("Object value : " + obj);

//IT RETURNS RUNTIME CLASS OF THIS OBJECT

//java.lang.String

System.out.println("Object Class : " + obj.getClass());

}

}

Java String

In Java, string is basically an object that represents sequence of char values. An array of

characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};

2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on string such as compare(),

concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

Page 46: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

46

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters. String, StringBuffer

and StringBuilder classes implement it. It means, we can create strings in java by using these

three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any

string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder

classes.

We will discuss immutable string later. Let's first understand what is String in Java and how to

create the String object.

How to create a string object?

There are two ways to create String object:

1. By string literal

2. By new keyword

String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Page 47: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

47

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string

already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist

in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";

2. String s2="Welcome";//It doesn't create a new instance

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the

literal "Welcome" will be placed in the string constant pool. The variable s will refer to the

object in a heap (non-pool).

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of

char values.

No. Method Description

1 char charAt(int index) returns char value for the particular

index

2 int length() returns string length

3 static String format(String format, Object...

args)

returns a formatted string.

4 static String format(Locale l, String format,

Object... args)

returns formatted string with given

locale.

5 String substring(int beginIndex) returns substring for given begin index.

6 String substring(int beginIndex, int endIndex) returns substring for given begin index

and end index.

7 boolean contains(CharSequence s) returns true or false after matching the

sequence of char value.

StringBuffer class:

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in

java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously.

So it is safe and will result in an order.

Page 48: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

48

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of

16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity

as length.

Important methods of StringBuffer class

Modifier and

Type

Method Description

public synchronized

StringBuffer

append(String s) is used to append the specified string with this string.

The append() method is overloaded like

append(char), append(boolean), append(int),

append(float), append(double) etc.

public synchronized

StringBuffer

insert(int offset,

String s)

is used to insert the specified string with this string at

the specified position. The insert() method is

overloaded like insert(int, char), insert(int, boolean),

insert(int, int), insert(int, float), insert(int, double)

etc.

public synchronized

StringBuffer

replace(int

startIndex, int

endIndex, String

str)

is used to replace the string from specified startIndex

and endIndex.

public synchronized

StringBuffer

delete(int

startIndex, int

endIndex)

is used to delete the string from specified startIndex

and endIndex.

public synchronized

StringBuffer

reverse() is used to reverse the string.

Exception Handling in Java

The Exception Handling in Java is one of the powerful mechanism to handle the runtime

errors so that normal flow of the application can be maintained.

Page 49: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

49

In this page, we will learn about Java exceptions, its type and the difference between checked

and unchecked exceptions.

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object

which is thrown at runtime.

What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,

IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.

An exception normally disrupts the normal flow of the application that is why we use exception

handling. Let's take a scenario:

1. statement 1;

2. statement 2;

3. statement 3;

4. statement 4;

5. statement 5;//exception occurs

6. statement 6;

7. statement 7;

8. statement 8;

9. statement 9;

10. statement 10;

Suppose there are 10 statements in your program and there occurs an exception at statement 5,

the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform

exception handling, the rest of the statement will be executed. That is why we use exception

handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by

two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

Page 50: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

50

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered

as the unchecked exception. According to Oracle, there are three types of exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are

known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are

checked at compile-time.

2) Unchecked Exception

Page 51: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

51

The classes which inherit RuntimeException are known as unchecked exceptions e.g.

ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked

exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The try

block must be followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which

means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed

whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It

specifies that there may occur an exception in the method. It is always used with method

signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to handle

the exception.

1. public class JavaExceptionExample{

2. public static void main(String args[]){

3. try{

4. //code that may raise exception

5. int data=100/0;

6. }catch(ArithmeticException e){System.out.println(e);}

7. //rest code of the program

8. System.out.println("rest of the code...");

9. }

10. }

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

Page 52: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

52

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a

NullPointerException.

1. String s=null;

2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have a string

variable that has characters, converting this variable into digit will occur

NumberFormatException.

1. String s="abc";

2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in

ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];

2. a[10]=50; //ArrayIndexOutOfBoundsException

Internal working of java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not handled,

JVM provides a default exception handler that performs the following tasks:

o Prints out exception description.

o Prints the stack trace (Hierarchy of methods where the exception occurred).

o Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is

maintained i.e. rest of the code is executed.

Page 53: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

53

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a

different exception handler. So, if you have to perform different tasks at the occurrence of

different exceptions, use java multi-catch block.

Points to remember

o At a time only one exception occurs and at a time only one catch block is executed.

o All catch blocks must be ordered from most specific to most general, i.e. catch for

ArithmeticException must come before catch for Exception.

Example 1

Let's see a simple example of java multi-catch block.

1. public class MultipleCatchBlock1 {

2.

3. public static void main(String[] args) {

4.

5. try{

6. int a[]=new int[5];

7. a[5]=30/0;

8. }

9. catch(ArithmeticException e)

10. {

11. System.out.println("Arithmetic Exception occurs");

12. }

13. catch(ArrayIndexOutOfBoundsException e)

14. {

15. System.out.println("ArrayIndexOutOfBounds Exception occurs");

16. }

17. catch(Exception e)

18. {

19. System.out.println("Parent Exception occurs");

20. }

21. System.out.println("rest of the code");

22. }

23. }

Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block

itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

1. ....

2. try

Page 54: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

54

3. {

4. statement 1;

5. statement 2;

6. try

7. {

8. statement 1;

9. statement 2;

10. }

11. catch(Exception e)

12. {

13. }

14. }

15. catch(Exception e)

16. {

17. }

18. ....

Java nested try example

Let's see a simple example of java nested try block.

1. class Excep6{

2. public static void main(String args[]){

3. try{

4. try{

5. System.out.println("going to divide");

6. int b =39/0;

7. }catch(ArithmeticException e){System.out.println(e);}

8.

9. try{

10. int a[]=new int[5];

11. a[5]=4;

12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

13.

14. System.out.println("other statement);

15. }catch(Exception e){System.out.println("handeled");}

16.

17. System.out.println("normal flow..");

18. }

19. }

Java finally block

Java finally block is a block that is used to execute important code such as closing connection,

stream etc.

Page 55: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

55

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally

block(if any).

Why use java finally

o Finally block in java can be used to put "cleanup" code such as closing a file, closing

connection etc.

Usage of Java finally

Let's see the different cases where java finally block can be used.

Let's see the java finally example where exception doesn't occur.

1. class TestFinallyBlock{

2. public static void main(String args[]){

Page 56: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

56

3. try{

4. int data=25/5;

5. System.out.println(data);

6. }

7. catch(NullPointerException e){System.out.println(e);}

8. finally{System.out.println("finally block is always executed");}

9. System.out.println("rest of the code...");

10. }

11. }

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw

keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

1. throw exception;

Let's see the example of throw IOException.

1. throw new IOException("sorry device error);

java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If

the age is less than 18, we are throwing the ArithmeticException otherwise print a message

welcome to vote.

1. public class TestThrow1{

2. static void validate(int age){

3. if(age<18)

4. throw new ArithmeticException("not valid");

5. else

6. System.out.println("welcome to vote");

7. }

8. public static void main(String args[]){

9. validate(13);

10. System.out.println("rest of the code...");

11. }

12. }

The Java throws keyword is used to declare an exception. It gives an information to the

programmer that there may occur an exception so it is better for the programmer to provide the

exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any

unchecked exception such as NullPointerException, it is programmers fault that he is not

performing check up before the code being used.

Syntax of java throws

Page 57: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

57

1. return_type method_name() throws exception_class_name{

2. //method code

3. }

Which exception should be declared

Ans) checked exception only, because:

o unchecked Exception: under your control so correct your code.

o error: beyond your control e.g. you are unable to do anything if there occurs

VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws example

Let's see the example of java throws clause which describes that checked exceptions can be

propagated by throws keyword.

1. import java.io.IOException;

2. class Testthrows1{

3. void m()throws IOException{

4. throw new IOException("device error");//checked exception

5. }

6. void n()throws IOException{

7. m();

8. }

9. void p(){

10. try{

11. n();

12. }catch(Exception e){System.out.println("exception handled");}

13. }

14. public static void main(String args[]){

15. Testthrows1 obj=new Testthrows1();

16. obj.p();

17. System.out.println("normal flow...");

18. }

19. }

Rule: If you are calling a method that declares an exception, you must either caught or

declare the exception.

Differences between throw and throws keywords

There are many differences between throw and throws keywords. A list of differences between

throw and throws are given below:

Page 58: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

58

No. throw throws

1) Java throw keyword is used to

explicitly throw an exception.

Java throws keyword is used to declare an exception.

2) Checked exception cannot be

propagated using throw only.

Checked exception can be propagated with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple

exceptions.

You can declare multiple exceptions e.g.

public void method()throws

IOException,SQLException.

Differences between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between

final, finally and finalize are given below:

No. final finally finalize

1) Final is used to apply restrictions on

class, method and variable. Final class

can't be inherited, final method can't be

overridden and final variable value can't

be changed.

Finally is used to place

important code, it will be

executed whether

exception is handled or

not.

Finalize is used to

perform clean up

processing just before

object is garbage

collected.

2) Final is a keyword. Finally is a block. Finalize is a method.

Java Custom/User defined Exception

If you are creating your own Exception that is known as custom exception or user-defined

exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

1. class InvalidAgeException extends Exception{

2. InvalidAgeException(String s){

3. super(s);

Page 59: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

59

4. }

5. }

1. class TestCustomException1{

2.

3. static void validate(int age)throws InvalidAgeException{

4. if(age<18)

5. throw new InvalidAgeException("not valid");

6. else

7. System.out.println("welcome to vote");

8. }

9.

10. public static void main(String args[]){

11. try{

12. validate(13);

13. }catch(Exception m){System.out.println("Exception occured: "+m);}

14.

15. System.out.println("rest of the code...");

16. }

17. }

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.

Advantage of Assertion:

It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:

There are two ways to use assertion. First way is:

1. assert expression;

and second way is:

1. assert expression1 : expression2;

Simple Example of Assertion in java:

1. import java.util.Scanner;

2.

3. class AssertionExample{

4. public static void main( String args[] ){

5.

6. Scanner scanner = new Scanner( System.in );

7. System.out.print("Enter ur age ");

Page 60: JAVA PROGRAMMING · JAVA PROGRAMMING UNIT-III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class. Interfaces, creating the packages, using

60

8.

9. int value = scanner.nextInt();

10. assert value>=18:" Not valid";

11.

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

13. }

14. }

15.