0% found this document useful (0 votes)
2 views81 pages

JAVA Unit 3 2023 Complete - Student

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance, strings, and exception handling. It explains the types of inheritance, the use of the 'super' keyword, and the characteristics of strings in Java, including their immutability. Additionally, it covers practical examples and code snippets to illustrate these concepts.

Uploaded by

Ayush Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views81 pages

JAVA Unit 3 2023 Complete - Student

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance, strings, and exception handling. It explains the types of inheritance, the use of the 'super' keyword, and the characteristics of strings in Java, including their immutability. Additionally, it covers practical examples and code snippets to illustrate these concepts.

Uploaded by

Ayush Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

OBJECT ORIENTED PROGRAMMING USING JAVA

Dr. Varuna Gupta


School of Sciences
Christ University, Delhi NCR

MISSION VISION CORE VALUES


CHRIST is a nurturing ground for an individual’s holistic development to Excellence and Service Faith in God | Moral Uprightness
make effective contribution to the society in a dynamic environment Love of Fellow Beings
Social Responsibility | Pursuit of Excellence
Unit 3(Inheritance, Strings And Exception Handling)

Inheritance
Inheritance basic - member access and inheritance - constructors and inheritance - using super to call superclass
constructors - using super to access superclass members - creating a multilevel hierarchy - superclass references
and subclass objects - method overriding - using abstract classes -using final - the object class.

MISSION VISION CORE VALUES


CHRIST is a nurturing ground for an individual’s holistic development to Excellence and Service Faith in God | Moral Uprightness
make effective contribution to the society in a dynamic environment Love of Fellow Beings 2
Social Responsibility | Pursuit of Excellence
CHRIST
Deemed to be University

What is Inheritance?

Inheritance is a powerful feature of object-oriented programming. It is a


process of creating a new class from existing class.
The class from which we create a new class is called the base class(Super
class or Parent class)
The newly created class is known as Derived class also known as Sub Class or
Child Class.

3
Excellence and Service
CHRIST
Deemed to be University

Inheritance Relationship Feature A

Base Class
Feature B

Feature C
Derived Class
Feature A

Feature B

4
Excellence and Service
CHRIST
Deemed to be University

5
Excellence and Service
CHRIST
Deemed to be University

6
Excellence and Service
CHRIST
Deemed to be University

Defining child Class


•Whenever a child class is defined, we have to specify its relationship with the parent class using
extends keyword. The general form of specifying child class:

Class child_class_name extends base_class_name


{
------
------// members and member funtions of child
class
------
}

7
Excellence and Service
CHRIST
Deemed to be University

TYPES OF INHERITANCE
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance

Multiple and hybrid inheritance is not


there in java because of ambiguity
problem.

8
Excellence and Service
SINGLE INHERITANCE

Parent Class
A

B Child Class

One parent and one child class


9
MULTILEVEL INHERITANCE

A Grant Parent Class 1

B Parent class

C Child Class

10
HIERARCHICAL INHERITANCE

A parent Class

D1 D2 D3
child Class 1 child Class 2 child Class 3

One parent More child


11
● If I want to present a car then I need some property and methods related to the car.

Property Methods Property Methods

Price Setprice() , getprice() Price Setprice() , getprice()

Engine Setspeed() , getspeed() Engine Setspeed() , getspeed()

Colour Setcolor() , getcolor()


Colour Setcolor() , getcolor()
Capacity Setcapacity(), getcapacity()
Capacity Setcapacity(), getcapacity()
Fuel type Setfueltype(), getfueltype()
Fuel type Setfueltype(), getfueltype()
safeguard setsafeguard()

Alerts Setalerts()

12
● Now there are two classes one is car and another one is sport car. So we want to extend sport car class
to extract the features of car class.

Syntax : class subclass extends superclass


{
}

● Base class means superclass, derived class means sub class.


● In our example car is superclass and sports car is subclass.

13
PRACTICAL SESSION
OF
INHERITANCE
package inheritance;
Output:
class person{
void talk() talking...
{System.out.println("talking...");} earning...
}
class employee extends person{
void earn(){System.out.println("earning...");}
}

public static void main(String args[]){


employee e =new employee();
e.talk();
e.earn();
}}

15
Can we create a object of parent class also or it will give
a error message.

16
Answer is yes we can create a object of parent class also
package basicprogsjava;
class person// base class
{ Output:
void talk()
{System.out.println("talking...");} talking...
} talking...
class employee extends person{ earning...
void earn(){System.out.println("earning...");}

public static void main(String args[]){


person p=new person();
employee d=new employee();
p.talk();
d.talk();
d.earn();
}}

17
Multilevel Inheritance

package inheritance;

class person{
void talk()
{System.out.println("talking...");}
}
class employee extends person{
void earn(){System.out.println("earning...");}
}
class student extends employee{
void study(){System.out.println("studing...");}

public static void main(String args[]){


student d=new student();
d.talk();
d.earn();
d.study();
}}

18
Super Keyword
● The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to
access the superclass constructor. The most common use of the super keyword is to eliminate the
confusion between super classes and subclasses that have methods with the same name.

19
Use of Super class

● Super can be used with variable


● Super can be used with method
● Super can be used with constructor

20
super is used to refer immediate parent class instance variable.

● We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.

package inheritance;
class university1
{
String course="BCA";
}
class college1 extends university1
{
String course="BDA";
void printcourse()
{
System.out.println(course);
System.out.println(super.course);
}
}
class super1{
public static void main(String args[])
{
college1 d=new college1();
d.printcourse();
}}

21
super can be used to invoke parent class method

● The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as
parent class. In other words, it is used if method is overridden.

package inheritance;
class campus{
void course()
{System.out.println("BCA running");}
}
class christ extends campus{
void course(){System.out.println("BDA running");}
void subjects(){System.out.println("Object Oriented Programming using
java");}
void study(){
super.course();
course();
subjects();
}
}
class super2{
public static void main(String args[]){
christ obj=new christ();
obj.study();
}}

22
super is used to invoke parent class constructor.

● Do it by your own

23
Constructor in Inheritance

● Constructors cant be inherited by subclass.


● Sub class constructor invokes constructor of super class.
● Explicit call to the super class constructor from sub class’s constructor can
be made using super().
● You can write a sub class constructor that invokes the constructor of the
super class, either implicitly or by using the keyword super.

24
Scenarios

● Implicit constructors in superclass and subclass.


● Implicit constructor in subclass and explicit constructor in superclass.
● Implicit constructor in superclass and explicit constructor in subclass
● Explicit constructor in superclass and subclass.

25
Constructor overloading in inheritance
package inheritance;
class base
{
base()
{
System.out.println("super class data");
}
base(int x)
{
System.out.println("super class constructor overloaded=" + x);
}}
class derived extends base
{
derived()
{
System.out.println("sub class data");
}
derived(int x, int y)
{
super(x);
System.out.println("sub class constructor overloaded=" + y);
}}
public class constC
{
public static void main(String[] args)
{
derived obj = new derived(10,20);
}}

26
Why Constructors can’t be inherited

Whenever a class (child class) extends another class (parent class), the sub class inherits state and
behavior in the form of variables and methods from its super class but it does not inherit
constructor of super class

● Constructors are special and have same name as class name. So if constructors were inherited
in child class then child class would contain a parent class constructor which is against the
constraint that constructor should have same name as class name.
● A parent class constructor is not inherited in child class and this is why super() is added
automatically in child class constructor if there is no explicit call to super or this.

27
Run time Polymorphism

● Method overriding is an example of runtime polymorphism. In method overriding, a subclass


overrides a method with the same signature as that of in its superclass. During compile time,
the check is made on the reference type. However, in the runtime, JVM figures out the object
type and would run the method that belongs to that particular object.

● In the given example


university d = new college(); // university reference but college object

28
Run time Polymorphism

package inheritance;

class university {
int x=10;
public void BDA()
{ System.out.println("Base BDA class"); }
public void BCA()
{ System.out.println("BCA class"); }
}

class college extends university {

public void BDA()


{ System.out.println("Derived class funvtion overridded"); }
public void BBA()
{ System.out.println("BBA class"); }
}

public class overridg{


public static void main(String args[])
{
university d = new college(); // university reference but college object
System.out.println("Reference of Child Type :"+ d.x);
d.BDA();
d.BCA();
//d.BBA();
} }

29
● university d = new college();
● Object is related to university so we can access function BCA() easily but not BBA()

BDA() can be accessed because of overriding

● BBA() cant be accessed

30
Java Runtime Polymorphism with multilevel inheritance

● Try this

31
Method Overriding using abstract class

32
ABSTRACTION

● 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.

● There are two ways to achieve abstraction in java


1. Abstract class
2. Interface

33
Abstract Class

● We can’t create object of abstract class but we can create reference of abstract class.
● Abstract class contain at least one abstract method, it can have normal method also.
● Concreate class contain complete definition for all methods.
● like in the given diagram human have some property like breathing , thinking, eating that can be
inherited by female or male both , so there is no need to create a object of human
● 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).
Human

Female Male
34
35
package abstraction;
abstract class govtpolicy {
abstract void retfile();
abstract void paytax();
void guidelines()
{
System.out.println("follow guidelines");
}}
class business extends govtpolicy {
void product() {
System.out.println("buy my product");
}
void retfile()
{
System.out.println("return your file on time");
}
void paytax()
{
System.out.println("tax is compulsory");
}}
class abstraction1 {
public static void main(String args[]) {
govtpolicy s = new business();
business b = new business();
s.guidelines();
s.retfile();
s.paytax();
}}

36
Can We Override a Static and Final Method?

● No, the Methods that are declared as final and static cannot be Overridden or hidden. For this
reason, a method must be declared as final only when we’re sure that it is complete.
• It is noteworthy that abstract methods cannot be declared as final because they aren’t complete
and Overriding them is necessary.

37
final with Class and Method

● The class cannot be subclassed. Whenever we declare any class as final, it means
that we can’t extend that class or that class can’t be extended, or we can’t make a
subclass of that class.

● If a class is declared as final as by default all of the methods present in that class are
automatically final, but variables are not.

● The method cannot be overridden by a subclass. Whenever we declare any method as


final, then it means that we can’t override that method.
CHRIST
Deemed to be University
String
Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings
are immutable as well. Whenever a change to a String is made, an entirely new String is created.
The java.lang.String class is used to create a string object.
String class is a final class that cant be inherited

Syntax:

<String_Type> <string_variable> = "<sequence_of_string>";

There are two ways to create String object:


1.By string literal
2.By new keyword

Example:

1.char[] ch={‘S',’T',’U',’D',’E',’N',’T',’S'};
2.String s=new String(ch);
OR
String s=“STUDENTS";
39
Excellence and Service
CHRIST
Deemed to be University

string literal

If two or more strings have the same set of characters in the same sequence then they share
the same reference in memory

For example:

String str1 = “My name is Varuna”; str1


String str2 = “My name is Varuna”;
String str3 = “My name is” + “Varuna”;
My name is
str2 Varuna
All the string references str1, str2, str3 denote the same string object.

str3

40
Excellence and Service
CHRIST
Deemed to be University

New Operator

If two or more strings have the same set of characters in the same sequence then they share
the same reference in memory

For example:
My name is
String str1 = new String(“My name is Varuna”); str1
Varuna
String str2 = new String(“My name is Varuna”);

both the string references str1, str2 denote the different string object.
str2 My name is
Varuna

41
Excellence and Service
CHRIST
Deemed to be University

String is immutable
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.

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.

42
Excellence and Service
CHRIST
Deemed to be University

package stringfunc;

import java.io.*;
import java.lang.*;

class strfunc {
public static void main(String[] args) {
String mystr = "My Students";
System.out.println("String literal = " +mystr);

String mystr1 = new String("My dear Students");


System.out.println("String using new"
+ " = " + mystr1);
}
}

43
Excellence and Service
CHRIST
Deemed to be University

package stringfunc;

import java.io.*;
import java.lang.*;

class strfunc {
public static void main(String[] args) {
String mystr = "My Students";
String mystr1 = "My Students";
String mystr2 = new String(“My Students”);
System.out.println(”Result 1”+(mystr==mystr1));
System.out.println(“Result 2"+mystr.equals(mystr1));
System.out.println(”Result 3”+(mystr==mystr2));
System.out.println(“Result 4"+mystr.equals(mystr2));

}
}
44
Excellence and Service
CHRIST
Deemed to be University

In the above program we have created 3 objects of String class mystr , mystr1 and mystr2 . Mystr and mystr1 will be
created by string literals and mystr2 will be created by new keyword.
As we know using literals if we are creating String class objects with the same values then only one object will be created
and it will refer the same reference or address.

These two references (mystr and mystr1) are same , So,


System.out.println(”Result 1”+(mystr==mystr1));
Will return True as the result

System.out.println(“Result 2"+mystr.equals(mystr1));
It will also return true because equal() will check the values not references

System.out.println(”Result 3”+(mystr==mystr2));
It will return False as the result because mystr and mystr2 are there at different references not at the same.

System.out.println(“Result 4"+mystr.equals(mystr2));
It will return true as the result because equal() will check the values that are same.

45
Excellence and Service
CHRIST
Java string Methods
Deemed to be University

There are various methods of java String

UpperCase() and LowerCase()


IndexOf()
lastIndexOf()
Trim()
equals()
equalsIgnoreCase()
Split()
Length()
CompareTo()
Replace()
CharAt()
Isempty()
ValueOf()

46
Excellence and Service
CHRIST
Deemed to be University

Equals() and EqualsIgnoreCase()

package stringfunc; package stringfunc;

public class equalfun { public class equalfun {


public static void main(String args[]){ public static void main(String args[]){
String s1= new String("University"); String s1= new String("University");
String s2= new String("university"); String s2= new String("university");
if(s1.equals(s2)) if(s1.equalsIgnoreCase(s2))
System.out.println("Strings are same"); System.out.println("Strings are same");
else else
System.out.println("Strings are not same"); System.out.println("Strings are not same");
} }
} }

Strings are not same Strings are same

47
Excellence and Service
CHRIST
Deemed to be University

CompareTo() –

it will compare the Unicode value of character

48
Excellence and Service
CHRIST
Deemed to be University

CharAt()

package stringfunc;
public class charat1
{
public static void main(String ar[])
{
String s="Varuna";
System.out.println(s.charAt(0));
System.out.println(s.charAt(3));
}
}

49
Excellence and Service
CHRIST
Deemed to be University

Length()

package stringfunc;
public class charat1
{
public static void main(String ar[])
{
String s="Varuna";
System.out.println(s.length());

}
}

50
Excellence and Service
CHRIST
Deemed to be University

valueOf()

// Valueof() can convert all primitive datatype into string value and string value
into primitive data type expect char
package stringfunc;
public class valueof1 {
public static void main(String ar[])
{
int a=10; // conversion from Int to string
String s=String.valueOf(a);
System.out.println(s+10);
String str ="10"; // conversion from string to interger
int n2 = Integer.valueOf(str);
System.out.println(n2);
}
}

51
Excellence and Service
CHRIST
Deemed to be University

Trim()

Trim will remove the white space which appears before and after
the string

String s=" Varuna ";


String s2 = s.trim();
System.out.println(s2);
}
}

52
Excellence and Service
CHRIST
Deemed to be University

indexOf()

Searching from left to right

indexOf(int Ch)// to search a specific character in the given string


indexOf(int ch, int fromindex)// to search from the given number
indexOf(String str) //to search a specific sub string in the given string
indexOf(String ch, int fromindex)

Searching from right to left

lastIndexOf(int Ch)// to search a specific c


lastIndexOf(int ch, int fromindex)
lastIndexOf(String str) //to search a specific sub string in the given string
lasIndexOf(String ch, int fromindex)

53
Excellence and Service
CHRIST
Deemed to be University

indexOf() Searching from left to right


String s= new String ("Christ");
System.out.println(s);
int i = s.indexOf('s');
int i1 = s.indexOf('s',2);
int i2 = s.indexOf("ris");
System.out.println("output of indexof char" + i);
System.out.println("output of indexof char from" + i1);
System.out.println("output of indexof substring" + i2);
} }

Output:
Christ
output of indexof char=4
output of indexof char from=4
output of indexof substring=2

54
Excellence and Service
CHRIST
Deemed to be University

lastIndexOf() Searching from right to left


int i = s.lastIndexOf('s');
int i1 = s.lastIndexOf('s',2);
int i2 = s.lastIndexOf("ris");
System.out.println("output of lastindexof char" + i);
System.out.println("output of lastindexof char from" + i1);
System.out.println("output of lastindexof substring" + i2);
} }

Output:
Christ
output of lastindexof char=4
output of lastindexof char from=-1
output of lastindexof substring=2

55
Excellence and Service
CHRIST
Deemed to be University

Array of String

56
Excellence and Service
CHRIST
Deemed to be University

Control of Switch with String

57
Excellence and Service
CHRIST
Deemed to be University

Java Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the bundling of fields
and methods inside a single class.
It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data
hiding.

Note: People often consider encapsulation as data hiding, but that's not entirely true.
Encapsulation refers to the bundling of related fields and methods together. This can be used to achieve data hiding.
Encapsulation in itself is not data hiding.

58
Excellence and Service
CHRIST
Why Encapsulation
Deemed to be University

• In Java, encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy
to read.

• It helps to control the values of our data fields. For example


class student {
private int marks;

public void setMarks(int marks) {


if (marks >= 0) {
this. marks = marks;
} }}
Here, we are making the marks variable private and applying logic inside the setMarks() method. Now, marks cannot
be negative.
The getter and setter methods provide read-only or write-only access to our class fields. For example,
getmarks() // provides read-only access
setmarks() // provides write-only access

• We can also achieve data hiding using encapsulation. In the given example, if we change the id , name and price
variable into private, then the access to these fields is restricted.

59
Excellence and Service
CHRIST
Deemed to be University

Read-Only class
//A Java class which has only getter methods.
public class student{
private String university=“CHRIST";
//getter method for college
public String getuniversity(){
return university;
}
}

In the above example Now, you can't change the value of the university data member which is
“CHRIST".

s.setUniversity(“UPTU");//will render compile time error

60
Excellence and Service
CHRIST
Deemed to be University

Write-Only class
//A Java class which has only setter methods.
public class student{
//private data member
private String university;
//getter method for college
public void setuniversity(String university){
this. university = university;
}
}

Now, you can't get the value of the university, you can only change the value of university data member.

System.out.println(s.getuniversity());//Compile Time Error, because there is no such method


System.out.println(s.university);//Compile Time Error, because the university data member is private. So, it can't be ac
cessed from outside the class

61
Excellence and Service
CHRIST
Deemed to be University
Exception Handling

The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

Advantages of exception handling:

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

• Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the
code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is why we use exception handling
in Java.

62
Excellence and Service
CHRIST
Deemed to be University
Hierarchy of Java Exception classes

Checked
Checked
Checked

Unchecked
Unchecked
Unchecked
Unchecked

63
Excellence and Service
CHRIST
Deemed to be University

The throwable class provides a string variable that can be set by the subclasses to provide a detail message that provides
more information of the exception occurred.

All classes of throwables define a one parameter constructor that takes a string as the detail message

The class Throwable provides getMessage() function to retrieve an exception

64
Excellence and Service
CHRIST
Deemed to be University

Types of Java Exceptions

65
Excellence and Service
CHRIST
Deemed to be University

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time,
but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

66
Excellence and Service
CHRIST
Deemed to be University

Java Exception Keywords

Keyword Description

Try
The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally.
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 necessary 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 specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature

67
Excellence and Service
CHRIST
Deemed to be University

Four Ways
• Default throw and default catch(automatically run by java)
• Default throw and our catch
• Our throw and default catch
• Our throw an our catch

68
Excellence and Service
CHRIST
Deemed to be University

Unchecked Exception(at run time)

Arithmetic

Null Pointer

Index out of bound

Number format

69
Excellence and Service
CHRIST
Deemed to be University

Java try...catch block


The try-catch block is used to handle exceptions in Java

try {
// code
}
catch(Exception e) {
// code
}

Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block cannot be used without the try block.

70
Excellence and Service
CHRIST
Deemed to be University

Default throw and our catch

71
Excellence and Service
CHRIST
Deemed to be University

ArithmeticException
In the example, we are trying to divide a number by 0. Here, this code
class data{ generates an exception.
public static void main(String[] args) { To handle the exception, we have put the code, 5 / 0 inside the try block. Now
when an exception occurs, the rest of the code inside the try block is skipped.
The catch block catches the exception and statements inside the catch block is
try { executed.
If none of the statements in the try block generates an exception,
the catch block is skipped.
// code that generate exception
int divideByZero = 5 / 0;
// int divideByZero = x / y;(x and y can be entered from
keyboard)
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
System.out.println(“I am under catch block");
}
} 72
} Excellence and Service
CHRIST
Deemed to be University

package exceptionhandling;
public class morecatch {
public static void main(String[] args)
{
try
{
System.out.println(4/0);
System.out.println("in try block");
}
catch(NullPointerException e)
{System.out.println("Nullpointer exception:"+e.getMessage());
}
catch(ArithmeticException e)
{System.out.println("Arithmetic exception:" + e.getMessage()); }
System.out.println("last line");
}}

73
Excellence and Service
CHRIST
Deemed to be University

ArrayIndexOutOfBoundsException
public class prog3 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

74
Excellence and Service
CHRIST
Deemed to be University

NullPointer exception

75
Excellence and Service
CHRIST
Deemed to be University

Java try...finally block

We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an exception inside the try block
or not.

class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}

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

76
Excellence and Service
CHRIST
Deemed to be University

Java try...catch...finally block

In Java, we can also use the finally block after the try...catch block. For example,

77
Excellence and Service
CHRIST
Deemed to be University

Finally

package exceptionhandling;
public class morecatch {
public static void main(String[] args)
{
try
{
System.out.println(4/0);
System.out.println("in try block");
}
catch(NullPointerException e)
{System.out.println("Nullpointer
exception:"+e.getMessage());
}
catch(IndexOutOfBoundsException e)
{System.out.println("out of bound exception:" +
e.getMessage()); }
finally
{
System.out.println("last line");}
}}

78
Excellence and Service
CHRIST
Deemed to be University

Our throw and Default catch

Our throw and our catch

79
Excellence and Service
CHRIST
Deemed to be University

Throw and Throws

Definition:
The throw and throws is the concept of exception handling where the throw
keyword throw the exception explicitly from a method or a block of code whereas
the throws keyword is used in signature of the method.
Point of usage:
The throw keyword is used inside a function. It is used when it is required to throw an
Exception logically.
The throws keyword is used in the function signature. It is used when the function has
some statements that can lead to exceptions.
Exceptions Thrown”
The throw keyword is used to throw an exception explicitly. It can throw only one
exception at a time.
The throws keyword can be used to declare multiple exceptions, separated by a comma.
Whichever exception occurs, if matched with the declared ones, is thrown automatically
then.

80
Excellence and Service
CHRIST
Deemed to be University

Example of Throw
package exceptionhandling;
import java.io.*;
class TestThrow {
public static void main(String[] args)
{
int balance=50000;
int fees = 70000;
try
{
if(balance<fees)
throw new ArithmeticException("not enough balance in your account");
balance = balance-fees;
System.out.println("transaction completed" + balance);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic exception:" + e.getMessage());
}
System.out.println("It will be cont.., because this is my catch");
}
}

81
Excellence and Service

You might also like