0% found this document useful (0 votes)
12 views

22CS202 Java Unit-2

RMKEC FILE FOR JAVA PROGRAMMING

Uploaded by

samsundar793
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

22CS202 Java Unit-2

RMKEC FILE FOR JAVA PROGRAMMING

Uploaded by

samsundar793
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 125

22CS202

JAVA PROGRAMMING

UNIT II
UNIT 2 - INHERITANCE
• Inheritance can be defined as the process of acquiring
all the properties and behaviors of one class to
another

• Acquiring the properties and behavior of child class


from the parent class

• Inheritance represents the IS-A relationship, also Figure 2.1 Instance for Inheritance

known as parent-child relationship which is illustrated


in Figure 2.1
Advantages of Inheritance in Java
• For Method Overriding (so runtime polymorphism can be achieved)
• For Code Reusability

Syntax:
class subClass extends superClass
{
//methods and fields
}

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a

derived class, extended class, or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the

features. It is also called a base class or a parent class.


CSS
Types of Inheritance in Java

• Single Inheritance

• Hierarchical Inheritance

• Multilevel Inheritance

• Hybrid Inheritance

Multiple Inheritance is not supported in Java.

Types of Inheritance
Types of Inheritance and Syntax
class Mango extends Fruit
Single Inheritance {
 Process of extending single subclass from single String name = “Mango";
void printName()
super class.
{
System.out.println("Name is: " + name);
}
}
class SingleDemo
{
Example:
public static void main(String args[])
class Fruit
{
{
Mango m1 = new Mango();
String taste = “Sweet";
m1.printTaste();
void printTaste() m1.printName();
{ }
OUTPUT
System.out.println(“Taste is: " + taste); }
Taste is: Sweet
}
Name is: Mango
}
class Mango extends Fruit
Hierarchical Inheritance
{
 Process of extending more than one subclasses from String name = “Mango";

single super class. void printName()


{
System.out.println("Name is: " + name);
}
}
class Apple extends Fruit
Example: {
class Fruit String name = “Apple";
{ void printName()
String taste = “Sweet"; {
void printTaste() System.out.println("Name is: " + name);
{ }
System.out.println(“Taste is: " + taste); }
}
}
Hierarchical Inheritance

class HierarchicalDemo
{
public static void main(String args[])
{ OUTPUT
Taste is: Sweet
Mango m1 = new Mango();
Name is: Mango
m1.printTaste();
Taste is: Sweet
m1.printName(); Name is: Apple
Apple a1 = new Apple();
a1.printTaste();
a1.printName();
}
}
class Mango extends Fruit
Multilevel Inheritance
{
 Process of extending subclass from another sub String name = “Mango";

class void printName()


{
System.out.println("Name is: " + name);
}
}
class Malgova extends Mango
{
Example: int weight = 2;
class Fruit
void printWeight()
{
{
String taste = “Sweet";
System.out.println(“Weight is: " +
void printTaste()
weight);
{
}
System.out.println(“Taste is: " + taste);
}
}
}
Multilevel Inheritance

class MultilevelDemo
{
public static void main(String args[])
{ OUTPUT
Taste is: Sweet
Malgova m1 = new Malgova();
Name is: Mango
m1.printTaste();
Weight is: 2
m1.printName();
m1.printWeight();
}
}
class mango extends fruit
Hybrid Inheritance
{
 Process of extending new classes by combining String name = “Mango";

more than one forms of inheritance. Figure void printName()


{
illustrates Hybrid Inheritance which combines
System.out.println("Name is: " + name);
Multilevel and Hierarchical Inheritances. }
}
class papaya extends fruit
{
Example:
String name = “Papaya";
class fruit
void printName()
{
{
String taste = “Sweet";
System.out.println("Name is: " + name);
void printTaste()
}
{
System.out.println(“Taste is: " + taste); }

}
}
class HybridDemo
Hybrid Inheritance {
public static void main(String args[])
class PapayawithoutSeed extends papaya {
{ mango m1 = new mango();
int weight = 5; m1.printTaste();
void printWeight() m1.printName();
{ PapayawithoutSeed a1 = new
System.out.println(“Weight is: " + PapayawithoutSeed();
weight); a1.printTaste();
} a1.printName();
} a1.printWeight(); OUTPUT
Taste is: Sweet
}
Name is: Mango
}
Taste is: Sweet
Name is: Papaya
Weight is: 5
Member Access and Inheritance class B extends A
(Private) {
int total;
void sum()
 Although a subclass includes all of the members of its
{
superclass, it cannot access those members of the System.out.println("Accessing Protected
superclass that have been declared as private. member of Super class");
total=i+j; // Error, J is not accessible here
EXAMPLE
}
class A }
{ class PrivateAccessDemo
int i; //default access {
public static void main(String args[])
private int j; //private to A
{
void setij(int x,int y) B subob = new B();
{ subob.setij(10,20);
subob.sum();
i=x; j=y;
System.out.println("Total :
} "+subob.total);
OUTPUT
} }
Error
}
Member Access and Inheritance
(Protected)

 The methods or data members declared as protected EXAMPLE


are accessible within same package or sub classes in class A
different package. {
int i;
private int j;
void setij(int x,int y)
{
i=x; j=y;
}
}
class B extends A
{
Member Access and int total;
void sum()
Inheritance (Protected) {
System.out.println("Accessing Protected
member of Super class");
total=i+j;
}
}
class PrivateAccessDemo
{
public static void main(String args[])
{
B subob = new B();
subob.setij(10,20);
subob.sum();
OUTPUT System.out.println("Total :
Accessing Protected member of Super class "+subob.total);
Total : 30 }
}
METHOD OVERRIDING

Overriden Method

Overriding Method
METHOD OVERRIDING
• If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

• In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

• Method overriding is used to provide the specific implementation of a method which is already
provided by its super class.

• Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding

• The method must have the same name as in the parent class.

• The method must have the same parameter as in the parent class.

• There must be an IS-A relationship (inheritance).


Example: System.out.println("Sum of "+a+" and "+b+" is "+s);
import java.util.Scanner; }
class Maths }
{ class Test
public void add() {
{ public static void main(String arg[])
System.out.println(“Performs Addition”);
{
}
Arithmetic ob=new Arithmetic();
}
ob.add();
class Arithmetic extends Maths
{ }
public void add() }
{ Output:
Scanner kb = new Scanner(System.in);
System.out.println("Enter 2 inputs"); Enter 2 inputs
int a = kb.nextInt(); 10 10
int b = kb.nextInt(); Sum of 10 and 10 is 20
int s = a + b;
SUPER
• Super Keyword refers to Super Class Objects.
super.method_name()
refers to the method of the
parent class.

super.variable_name
Uses of Super refers to the variable in
the parent class.

super() invokes the


constructor of the
parent class.
1) super.methodname() invokes the method of the parent class
Example 1: When the Parent Class Methods overrides the Child
class Test
class Method without ‘super’
{
class ABC
{ public static void main(String args[])
void disp() {
{
XYZ obj = new XYZ();
System.out.println("Parent Class method");
obj.show();
}
} }
class XYZ extends ABC }
{
Output :
void disp()
Child Class method
{
System.out.println("Child Class method");
} • The subclass XYZ overrides the disp() method that
void show()
is present in superclass ABC and hence subclass
{
disp() method is called.
disp();
} • If we want to call the disp() method of the Parent
Example 2: Using super keyword to access the super class
class Test
method
{
class ABC
{ public static void main(String args[])
void disp()
{
{
System.out.println("Parent Class method");
XYZ obj = new XYZ();
}
} obj.show();
class XYZ extends ABC
{ }
void disp()
}
{
System.out.println("Child Class method");
}
void show() Output :
{
super.disp( ); Parent Class method
disp();
} Child Class method
2) super.variablename invokes a variable of the parent class

• When we have the same variable name in both super class and subclass,
super.variablename is used to access the super class variable.
Example 1: Example 2:
class A
class A {
{
int val=10;
int val=10;
}
}
class B extends A
class B extends A
{
{
int val=20;
int val=20;
void disp() void disp()

{ {
System.out.println("Value is : "+val); System.out.println("Value is : "+super.val);
} }
} }
class Test class Test
{
{
public static void main(String args[])
public static void main(String args[])
{
{
B b = new B();
B b = new B();
b.disp();
b.disp();
}
} }
}
Output : Output :
3) super() invokes the constructor of the parent class
• Subclass constructor can use super() for invoking the super class constructor explicitly
Syntax
subclassname()
{
super();
// sub-class constructor statements
}
Conditions to use super() in constructor
• super() should be the first statement in subclass constructor
• Must be used only in the subclass constructor
• The parameters in the super call must match the order and type of variables declared
in the super class constructor.
Example :
class A
{
A()
{
System.out.println("Base Class default Constructor");
}
}
class B extends A
{
B()
{
super();
System.out.println("Derived Class default Constructor");
}
class Test
{
public static void main(String args[]) Output:
{
B b = new B(); // invoking sub-class constructor Base Class default Constructor
}
Derived Class default Constructor
}
ABSTRACT METHODS
AND
ABSTRACT CLASSES
ABSTRACT CLASSES
Data abstraction is the process of hiding the implementation details and

showing only essential information/ functionality to the user.

There are two ways to achieve abstraction in java


• Abstract classes
• Interfaces
The abstract keyword is a non-access modifier, used for classes and methods.
ABSTRACT CLASSES
• A class which is declared with the abstract keyword is known as an abstract class.
• An abstract class can have both abstract methods (methods without implementation)
and non-abstract methods (method with implementation).
• An abstract class must have atleast one abstract method.
Abstract Method:

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

• Abstract method can only be used in an abstract class


Example of abstract method

abstract void area();


ABSTRACT CLASSES
Syntax for Abstract class
abstract class Shape

//attributes and methods

abstract void area();


}
Rules for Abstract Class
1. An abstract class must be declared with an abstract keyword.

2. It can have abstract and non-abstract methods.

3. It cannot be instantiated. (object cannot be created)

4. It can have constructors and static methods also.

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

6. The subclasses of abstract class must provide implementations to all the


abstract methods unless the subclass is also an abstract class.
Example for Abstract Class: class Circle extends Shape //subclass 3
{
int circlearea;
abstract class Shape
void Area() //Overrides the abstract method Area() of the super class
{
{
int a=3,b=4;
abstract void Area();
circlearea=(int) (3.14*a*a);
} System.out.println(“Area of circle is:“+circlearea);
}
class Rectangle extends shape //subclass 1 }
{ class Demo
int rectarea; {
void Area() //Overrides the abstract method Area() of the super class public static void main(String[] args)
{ {
Rectangle r=new Rectangle(); OUTPUT:
rectarea=a*b;
System.out.println(“Area of rectangle is:“ +rectarea); r.Area(); Area of rectangle is: 12

} Triangle t=new Triangle(); Area of triangle is: 6


} t.Area(); Area of circle is: 28
Circle c=new Circle();
class Triangle extends Shape //subclass 2 c.Area();
{ }
int triarea; }
void Area() //Overrides the abstract method Area() of the super class
{ • In Java, it is mandatory to override abstract methods of the superclass in the
triarea=(int) (0.5*a*b);
subclass. It is because the subclass inherits abstract methods of the superclass.
System.out.println(“Area of triangle is:“ +triarea);
• Since the subclass includes abstract methods, we need to override them.
}
Abstract Class vs. Concrete Class
Polymorphism
• Java is an object oriented programming language that supports the concept of polymorphism.

• Polymorphism is the concept of one entity providing multiple implementations or behaviors.

• Thus, polymorphism is the ability of an object to make more than one form.
Run Time Polymorphism
• Run-time polymorphism refers to behavior(method) that is resolved when your Java class is run by the
JVM.

• Method overriding by the sub-class is an example of run-time polymorphism.

• Method overriding allows child classes to provide their own implementation of a method also defined in the
parent class.

• An overridden method is called through the reference variable of a superclass. This process is
called as up casting.

• The JVM decides which version of the method to call based on the object through which the method is
invoked.

Up casting
Example for Run Time Polymorphism: class Circle extends Shape //subclass 3
{
abstract class Shape int circlearea;
{ void Area() //Overrides the abstract method Area() of the super
int a=3,b=4; class
abstract void Area(); {
} circlearea=(int) (3.14*a*a);
System.out.println(“Area of circle is:“+circlearea);
class Rectangle extends shape //subclass 1
}
{
int rectarea; }
void Area() //Overrides the abstract method Area() of the super class class Demo
{ {
OUTPUT:
rectarea=a*b; public static void main(String[] args)
Area of rectangle is: 12
System.out.println(“Area of rectangle is:“ +rectarea); {
} Area of triangle is: 6

} Shape s=new Rectangle(); Area of circle is: 28

s.Area();
class Triangle extends Shape //subclass 2
{ Shape s=new Triangle();
int triarea;
void Area() //Overrides the abstract method Area() of the super class s.Area();
{ Shape s=new Circle();
triarea=(int) (0.5*a*b);
System.out.println(“Area of triangle is:“ +triarea); s.Area();
} }
FINAL KEYWORD IN JAVA
FINAL KEYWORD IN JAVA

Final keyword can be used along with variables, methods and


classes.
1) final variable
2) final method
3) final class
final Variable
A final variable is a variable whose value cannot be changed at anytime once assigned, it remains as a constant
forever.

Example: Output :
public class Travel
Exception in thread "main" java.lang.Error:
{
Unresolved compilation problem:
final int SPEED=60;
void increaseSpeed()
The final field Travel.SPEED cannot be assigned.

{
SPEED=70;
} The above code will give you Compile time
public static void main(String args[])
error, as we are trying to change the value of a
{
final variable ‘SPEED’.
Travel t=new Travel();
t.increaseSpeed();
}
final method
When a method is declared as final, it is called as final method.
A final method cannot be overridden.

class Demo
Example:
{
class Parent public static void main(String args[])
{
{
Child c = new Child();
final void disp() c.disp();
}
{
}
System.out.println("disp() method of parent class");
Output : We will get the below error as we are overriding
}
the disp() method of the Parent class.
}
class Child extends Parent
Exception in thread "main" java.lang.VerifyError: class
{
com.javainterviewpoint.Child overrides final method disp.()
void disp()
at java.lang.ClassLoader.defineClass1(Native Method)
{
at java.lang.ClassLoader.defineClass(Unknown Source)
System.out.println("disp() method of child class");
at java.security.SecureClassLoader.defineClass(Unknown
}
Source)
}
final class
When a class is declared as final, it cannot be extended.
Final classes prevent Inheritance. If you try, it gives a compile time error.

Example: class MainClass


final class myFinalClass {
{ public static void main(String arg[])
void myMethod() {
{ myFinalClass fc = new subClass();
System.out.println("We are in the final class we just fc.myMethod();
created"); }
}
}
}
Output :
class subClass extends myFinalClass
error: cannot inherit from final myFinalClass
{
void myMethod()
{
System.out.println("We are in the subclass");
}
PACKAGES
•Collection of classes, methods, interfaces
• Container for classes
• A Package can be defined as a grouping of related types classes, interfaces,
enumerations and annotations providing access protection and name space
management
• Packages are stored in a hierarchical manner
• Types
○ Java API Packages (Built-In packages)
○ User Defined Packages
Java API PACKAGES
USER DEFINED PACKAGES
• Step 1: Creating Package with necessary classes, methods and
interface definitions

• Step2: Importing classes and Methods in java source program


Example 1
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
Example 1
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
String name = “Good Morning";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Example 2 Calculator
Demo.java
import calculator.*;
class Demo
{
public static void main(String[] args)
{
ArithmeticOperations obj=new ArithmeticOperations();
int sum=obj.add(10,5);
int diff=obj.sub(10,5);
System.out.println("Sum is: "+sum);
System.out.println("Difference is: "+diff);
}
}

Example 2: Calculator
ArithmeticOperations.java
package calculator;
public class ArithmeticOperations
{
public int add(int x, int y)
{
int z=x+y;
return z;
}
public int sub(int x, int y)
{
int z=x-y;
return z;
}
}
Advantages of Packages

• Preventing naming conflicts

• Making searching/locating and usage of classes, interfaces,


enumerations and annotations easier

• Providing controlled access

• Packages can be considered as data encapsulation (or data-hiding)


INTERFACES
• An interface in Java is a blueprint of a class.
• It has static constants and abstract methods.
• Mechanism to achieve abstraction and multiple inheritance.
• Declared by using the interface keyword.
• Provides total abstraction - all the methods in interface are
declared with empty body and are public and all fields are public,
static and final by default.
• A class that implement interface must implement all the methods
declared in the interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
• Interface fields are public, static and final by default, and
methods are public and abstract.
• Java compiler adds these to the interface.
Interface Compilation
Relation between Class and Interface

A class extends another class, an interface extends another


interface but a class implements an interface.
Extending class and interface
Example 1:

interface Bank {
float rateOfInterest();
}

class SBI implements Bank {


@Override
public float rateOfInterest() {
return 9.15f;
}
}
class ICICI implements Bank {
@Override
public float rateOfInterest() {
return 9.7f;
}
}
public class JavaApplication4 {
public static void main(String[] args) {
Bank b = new SBI(); Output
System.out.println("ROI: " + b.rateOfInterest()); ROI: 9.15

}
}
Example 2:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{

A6 obj = new A6(); obj.print(); Output:

Hello
}
}
Example 3:
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}
}
Output:
drawing circle
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces it is known as multiple inheritance.
Example 1:
interface Printable
{
void print();
}
interface Showable
{
void show();
}

class A7 implements Printable,Showable


{
public void print()
{
System.out.println("Hello");
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Interface inheritance
A class implements interface but one interface extends another interface .
Example 2:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Nested Interface in Java
An interface can have another interface i.e. known as nested interface.

Example
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}
Key points to remember about interfaces:

1. We can’t instantiate an interface in java. That means we cannot


create the object of an interface
2. Interface provides full abstraction as none of its methods have body.
On the other hand abstract class provides partial abstraction as it can
have abstract and concrete(methods with body) methods both.
3. “implements” keyword is used by classes to implement an interface.
4. While providing implementation in class of any method of an
interface, it needs to be mentioned as public.
5. Class that implements any interface must implement all the methods of that interface,
else the class should be declared abstract.
6. Interface cannot be declared as private, protected or transient.
7. All the interface methods are by default abstract and public.
8. Variables declared in interface are public, static and final by default.
interface Try
{
int a=10; public int a=10;
public static final int a=10; final int a=10;
static int a=0;
}
All of the above statements are identical.
9. Interface variables must be initialized at the time of declaration otherwise
compiler will throw an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is
not initialized at the time of declaration.
10. Inside any implementation class, you cannot change the variables
declared in interface because by default, they are public, static and final. Here
we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got
compilation error as the variable x is public static final by default and final variables
can not be re-initialized. class Sample implements Try
{
public static void main(String args[])
{
x=20; //compile time error
}
}
11. An interface can extend any interface but cannot implement it. Class implements
interface and interface extends interface.
12. A class can implement any number of interfaces.
13. If there are two or more same methods in two interfaces and a class implements both interfaces,
implementation of the method once is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
14. A class cannot implement two interfaces that have methods with same name but different return type.
interface A
{
public void aaa()
}
interface B
{
public int aaa();
}
class Central implements A,B
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String args[])
{
}
}

15. Variable names conflicts can be resolved by interface name.

interface A

int x=10;

}
interface B

int x=100;

class Hello implements A,B

public static void Main(String args[])

System.out.println(x);

System.out.println(A.x);

System.out.println(B.x);

}
Advantages of interface in java:
▪Without bothering about the implementation part, we can achieve the security of Implementation.
▪ In java, multiple inheritance is not allowed, however you can use interface to make use of it as you can implement
more than one interface.
Difference between Abstract Class and Interface
Static Methods in a Interface
• static methods contain the complete definition of the function.
• Since the definition is complete and the method is static, these methods cannot be overridden or changed
in the implementation class.
• Keyword used is static.
Example:
interface NewInterface
{
static void hello() // static method
{
System.out.println("Hello, New Static Method Here");
}

// Public and abstract method of Interface


void overrideMethod(String str);
}
// Implementation Class
public class InterfaceDemo implements NewInterface {

public static void main(String[] args)


{
InterfaceDemo interfaceDemo = new InterfaceDemo();

// Calling the static method of interface


NewInterface.hello();

// Calling the abstract method of interface


interfaceDemo.overrideMethod("Hello, Override Method here");
}

// Implementing interface method

@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}

Output:
Hello, New Static Method Here Hello, Override Method here
• A simple static method is defined and declared in an interface which
is being called in the main() method of the Implementation Class
InterfaceDemo.

• Unlike the default method, the static method hello() defined in the
interface NewInterface, cannot be overridden in implementing the
class.
LAB Exercise - Design a Java interface for Stack ADT and develop two
different classes that implements this interface, one using array and the
other using linked list.
import java.io.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
}
}
catch(IOException e)
{
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}
}
public void display()
{
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(int i=0; i<=top; i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
class Link
{
public int data;
public Link nextLink;
public Link(int d)
{
data= d;
nextLink=null;
}
public void printLink()
{
System.out.print(" --> "+data);
}
}
class Stack_List implements Mystack
{
private Link first;
public Stack_List()
{
first = null;
}
public boolean isEmpty()
{
return first == null;
}
public void push()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
Link link = new Link(ele);
link.nextLink = first;
first = link;
}
catch(IOException e)
{
System.err.println(e);
}
}
public Link delete()
{
Link temp = first;
try
{
first = first.nextLink;
}
catch(NullPointerException e)
{
throw e;
}
return temp;
}
public void pop()
{
try
{
Link deletedLink = delete();
System.out.println("Popped: "+deletedLink.data);
}
catch(NullPointerException e)
{
throw e;
}
public void display()
{
if(first==null)
System.out.println("Stack is empty");
else
{
Link currentLink = first;
System.out.print("Elements are: ");
while(currentLink != null)
{
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
}
class StackADT
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
System.exit(0);
}
}
while(ch<5);
System.out.println("Implementation of Stack using Linked List");
Stack_List stk1=new Stack_List();
ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk1.push();
break;
case 2:
try
{
stk1.pop();
}
catch(NullPointerException e)
{
System.out.println("Stack underflown");
}
break;
case 3:
stk1.display();
break;
default:
System.exit(0);

}
}
while(ch<5);
}
}
OUTPUT
Implementation of Stack using Array
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
1
Enter the element
10
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
1
Enter the element
15
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
1
Enter the element
25
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
3
Elements are: 10 <-- 15 <-- 25 <--
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
5
Implementation of Stack using Linked List
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
15
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
20
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: --> 20 --> 15 --> 10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped: 20
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: --> 15 --> 10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
4
Topics
 Introduction  Example: Multiple Catch Statement
 Types of Errors  Nested try Statements
 Exceptions Java Exception Hierarchy
 Exception Handling Fundamentals  Finally Block
 Common JAVA Exceptions  Example with finally block
 Uncaught Exceptions  Using throw Keyword
 Syntax of Exception Handling Code  Example
 Example: Divide by Zero without Exception  Java’s Built-in Exceptions
Handling
 Example: Handling Arithmetic Exception
Types of Errors
Errors
may broadly be classified into two categories. They are
 Compile – Time errors
All syntax errors will be detected and displayed by the JAVA compiler and
therefore these errors are known as compile – time errors. Most of the compile –
time errors are due to typing mistakes. The most common error are.
 Missing semicolons
 Missing brackets in classes and methods
 Misspellings of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments / initializations
 use of = in place of == operator
 And so on.
Types of Errors
Errors may broadly be classified into two categories. They are

 Run – Time errors


After compilation process is completed, the program has to be tested for
various inputs. If the program produce wrong results due to wrong logic or
may terminate due to errors. Such errors are called Run – Time errors. Most
common run – time errors are.
 Diving an integer by 0.
 Accessing an element that is out of bounds of an array.
 Attempting to use a negative size for an array.
 Trying to store a value of an incompatible types.
 Converting invalid String to a number
 Accessing a character that is out of bounds of a String.
 And many more.
When such errors are encountered, java typically generates an error message
and aborts the program
Exception Handling
 The purpose of Exception Handling mechanism is to provide a means to
detect and report an “Exception Circumstance” so that appropriate action can
be taken. Exception Handling performs the following tasks

 Find the problem (HIT the exception).


 Inform that an error has occurred (THROW the exception).
 Receive the error information (CATCH the exception).
 Take corrective actions (HANDLE the exception).

 The exception handling code basically consists of two segments. One to


detect error and to throw exceptions and the other to catch exception and to
take appropriate actions.
Exceptions
 An Exception is a condition that is caused by a run – time error in the
program.

 When JAVA interpreter encounters an error, it creates an Exception object


and throws it.

 if the exception object is not caught and handled properly, the interpreter
will display an error message and will terminate the program.

 if the programmer want the program to continue with execution of the


remaining code, then the programmer should try to catch the exception
object thrown by the error condition and then display an appropriate
message for taking corrective actions. This task is known as Exception
Handling.
Common Java Exceptions
The programmer always be on the lookout for places in the program where exception
could be generated. Some common exceptions that we must watch out for catching are
listed.
Exception Type Cause of Exception
ArithmeticException Caused by math errors such as division by zero

ArrayIndexOutOfBoundException Caused by bad array indexes

Caused when a program tries to store the wrong


ArrayStoreException type of data in an array
FileNotFoundException Caused by an attempt to access a nonexistent file
NullPointerException Caused by referencing a null object
Caused when a conversion between strings and
NumberFormatException numbers fails
StackOverFlowException Caused when the system runs out of stack space.
Uncaught Exceptions
In Java, an uncaught exception refers to an exception that is thrown during the execution of
a Java program, but is not caught and handled by an appropriate exception handler. When
an exception is thrown in Java and it is not caught, the Java runtime system terminates the
program and displays an error message, which typically includes a stack trace that shows
the sequence of method calls that led to the uncaught exception.
Uncaught exceptions can occur for various reasons, such as:
• Coding errors: These can include null pointer dereferences, array index out of bounds,
arithmetic overflows, and other programming mistakes that violate the syntax or
semantics of Java code.
• Runtime errors: These can occur during the execution of Java code, such as file I/O
errors, network connection failures, or database errors.
• Environmental issues: These can include issues related to the Java Virtual Machine
(JVM) or the operating system, such as insufficient memory, unavailable system resources,
or incompatible Java versions.
Example
import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
Output
Syntax of Exception Handling
The basic concepts of exception handling are throwing an exception
and catching it. This is illustrated in figure as shown.
Exception
try block object creato
r
Statement that causes
an exception
Throws exce
ption
object

Exception
catch block handler
Statement that handles
the exception
Types of Errors
Errors may broadly be classified into two categories. They are
 Compile – Time errors
All syntax errors will be detected and displayed by the JAVA compiler and
therefore these errors are known as compile – time errors. Most of the
compile – time errors are due to typing mistakes. The most common error
are.
 Missing semicolons
 Missing brackets in classes and methods
 Misspellings of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments / initializations
 use of = in place of == operator
 And so on.
Types of Errors
Errors may broadly be classified into two categories. They are
 Run – Time errors
After compilation process is completed, the program has to be tested for
various inputs. If the program produce wrong results due to wrong logic or
may terminate due to errors. Such errors are called Run – Time errors.
Most common run – time errors are.
 Diving an integer by 0.
 Accessing an element that is out of bounds of an array.
 Attempting to use a negative size for an array.
 Trying to store a value of an incompatible types.
 Converting invalid String to a number
 Accessing a character that is out of bounds of a String.
 And many more.
When such errors are encountered, java typically generates an error
message and aborts the program
Exceptions
 An Exception is a condition that is caused by a run – time error in the
program.

 When JAVA interpreter encounters an error, it creates an Exception object


and throws it.

 if the exception object is not caught and handled properly, the interpreter
will display an error message and will terminate the program.

 if the programmer want the program to continue with execution of the


remaining code, then the programmer should try to catch the exception
object thrown by the error condition and then display an appropriate message
for taking corrective actions. This task is known as Exception Handling.
Exception Handling
 The purpose of Exception Handling mechanism is to provide a means to detect and
report an “Exception Circumstance” so that appropriate action can be taken. Exception
Handling performs the following tasks

 Find the problem (HIT the exception).


 Inform that an error has occurred (THROW the exception).
 Receive the error information (CATCH the exception).
 Take corrective actions (HANDLE the exception).

 The exception handling code basically consists of two segments. One to detect error
and to throw exceptions and the other to catch exception and to take appropriate
actions.
Common Java Exceptions
The programmer always be on the lookout for places in the program where exception could
be generated. Some common exceptions that we must watch out for catching are listed.
Exception Type Cause of Exception
ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundExc
Caused by bad array indexes
eption
Caused when a program tries to store the wrong type
ArrayStoreException
of data in an array
FileNotFoundException Caused by an attempt to access a nonexistent file
NullPointerException Caused by referencing a null object
Caused when a conversion between strings and
NumberFormatException
numbers fails
StackOverFlowException Caused when the system runs out of stack space.
Syntax of Exception Handling
The basic concepts of exception handling are throwing an exception and
catching it. This is illustrated in figure as shown.
Exception
try block object creato
r
Statement that causes
an exception
Throws exce
ption
object

Exception
catch block handler
Statement that handles
the exception
Syntax of Exception Handling
 Java uses the keyword try to preface a block of code that is likely to cause an error
condition throw an exception.

 A catch block defined by the keyword catch, catches the exception thrown by the try
block and handles it appropriately.

 The catch block is added immediately after the try block.


 the try block can have one or more
statements that could generate an
try block{ exception, the remaining statements in the
statement;
}catch(Exceptiontype ex){ block are skipped and execution jumps to
statement; the catch block.
}

 The catch block too can have one or


more statements that are necessary to
process the exception.
Example: Divide by Zero without
Exception
Example: Divide by Zero without
Exception
Output:
Example: Handling Arithmetic
Exception
public class ArithmeticException
{
void divide(int a, int b)
{
// performing divison and storing th result
int res = a / b;
System.out.println("Division process has been done successfully.");
System.out.println("Result came after division is: " + res);
}
public static void main(String argvs[])
{
// creating an object of the class ArithmeticException
ArithmeticException obj = new ArithmeticException();
obj.divide(1, 0);
}
}
Example: Handling Arithmetic
Exception
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


at ArithmeticException.divide(ArithmeticException.java:6)
at ArithmeticException.main(ArithmeticException.java:16)
Statements
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code"); } }
OUTPUT
NESTED TRY STATEMENTS
• In Java, using a try block inside another try block is permitted. It is called as
nested try block. Every statement that we enter a statement in try block, context
of that exception is pushed onto the stack.

• For example, the inner try block can be used to handle


ArrayIndexOutOfBoundsException while the outer try block can handle the
ArithemeticException (division by zero
SYNTAX
NESTED TRY PROGRAM
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
} //inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4; }
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e);
} System.out.println("other statement"); } //catch block of outer try block
catch(Exception e) {
System.out.println("handled the exception (outer catch)"); }
System.out.println("normal flow.."); } }
OUTPUT
Java Exception Hierarchy
 Exception classes inherit directly or indirectly from class Exception, forming an
inheritance hierarchy.

 Can extend this hierarchy with your own exception classes.

Figure shows a small portion of the inheritance hierarchy for class Throwable
(a subclass of Object), which is the superclass of class Exception.

 Only Throwable objects can be used with the exception-handling mechanism.

 Class Throwable has two subclasses: Exception and Error.


Java Exception Hierarchy
Finally Block

 The finally block always executes when the try block exits. This ensures that the
finally block is executed even if an unexpected exception occurs. But finally is useful
for more than just exception handling.
 it allows the programmer to avoid having cleanup code accidentally bypassed by a
return, continue, or break. Putting cleanup code in a finally block is always a good
practice, even when no exceptions are anticipated.
 The finally block is used for resource de-allocation.
 Placed after the last catch block.
Example: With Finally Block

Output:
Throwing Our own Exceptions

 The uses can do by using the keyword throw as follows

throw new Throwable_subClass;

 Example:
throw new ArithmeticException();
throw new NumberFormatException();
Example using Throw
THANK YOU

You might also like