0% found this document useful (0 votes)
5 views129 pages

OOP Concepts in Java: Classes & Methods

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including the definition of classes and objects, access modifiers, method declaration, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism. It explains key features such as method overloading, constructors, and the importance of encapsulation in data protection. Additionally, it discusses how objects communicate through message passing and the significance of constructors in initializing objects.

Uploaded by

avani6047
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)
5 views129 pages

OOP Concepts in Java: Classes & Methods

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including the definition of classes and objects, access modifiers, method declaration, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism. It explains key features such as method overloading, constructors, and the importance of encapsulation in data protection. Additionally, it discusses how objects communicate through message passing and the significance of constructors in initializing objects.

Uploaded by

avani6047
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

UNIT 2

Class and Object Concepts:


Concepts of OOP, Defining a class, creating
objects from class, adding attributes and
methods to the class, using constructors,
Passing values to the functions – pass by value,
pass by reference, Function overloading.
Modifiers – public, private, protected, default,
static, final, Concept of package, Introduction to
Exception Handling

By Ms. Neha Gakhar


[Link]@[Link]

By Ms. Neha Gakhar


➢ Object Oriented Programming (OOPs) Concept in Java
• As the name suggests, Object-Oriented Programming or
OOPs refers to languages that use objects in programming,
they use objects as a primary source to implement what is
to happen in the code.
• Objects are seen by the viewer or user, performing tasks
assigned by you.
• Object-oriented programming aims to implement real-
world entities like inheritance, hiding, polymorphism etc. in
programming.
• The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the
code can access this data except that function.
• Let us discuss prerequisites by polishing concepts of
method declaration and message passing. Starting off with
the method declaration, it consists of six components:

By Ms. Neha Gakhar


➢ Access Modifier: Defines the access type of the method i.e. from where it
can be accessed in your application. In Java, there are 4 types of access
specifiers:
– public: Accessible in all classes in your application.
– protected: Accessible within the package in which it is defined and in
its subclass(es) (including subclasses declared outside the package).
– private: Accessible only within the class in which it is defined.
– default (declared/defined without using any modifier): Accessible within the
same class and package within which its class is defined.
• The return type: The data type of the value returned by the method or void
if it does not return a value.
• Method Name: The rules for field names apply to method names as well,
but the convention is a little different.
• Parameter list: Comma-separated list of the input parameters that are
defined, preceded by their data type, within the enclosed parentheses. If
there are no parameters, you must use empty parentheses ().
• Exception list: The exceptions you expect the method to throw. You can
specify these exception(s).
• Method body: It is the block of code, enclosed between braces, that you
need to execute to perform your intended operations.
By Ms. Neha Gakhar
➢Message Passing:
• Objects communicate with one another by
sending and receiving information to each other.
• A message for an object is a request for
execution of a procedure and therefore will
invoke a function in the receiving object that
generates the desired results.
• Message passing involves specifying the name of
the object, the name of the function and the
information to be sent.

By Ms. Neha Gakhar


• Now that we have covered the basic
prerequisites, we will move on to the 4 pillars
of OOPs which are as follows.
• But, let us start by learning about the different
characteristics of an Object-Oriented
Programming Language

By Ms. Neha Gakhar


➢OOPS concepts are as follows:
• Class
• Object
• Method and method passing
• Pillars of OOPs
– Abstraction
– Encapsulation
– Inheritance
– Polymorphism
• Compile-time polymorphism
• Runtime polymorphism

By Ms. Neha Gakhar


• A class is a user-defined blueprint or prototype from which objects are
created.
• It represents the set of properties or methods that are common to all
objects of one type.
• Using classes, you can create multiple objects with the same behavior
instead of writing their code multiple times.
• This includes classes for objects occurring more than once in your code. In
general, class declarations can include these components in order:
❑ Modifiers: A class can be public or have default access
❑ Class name: The class name should begin with the initial letter capitalized
by convention.
❑ Superclass (if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
❑ Interfaces (if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
❑ Body: The class body is surrounded by braces, { }.

By Ms. Neha Gakhar


➢ An object is a basic unit of Object-Oriented
Programming that represents real-life entities.
➢ A typical Java program creates many objects,
which as you know, interact by invoking methods.
The objects are what perform your code, they are
the part of your code visible to the viewer/user.
➢ An object mainly consists of:
• State: It is represented by the attributes of an
object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an
object. It also reflects the response of an object
to other objects.
• Identity: It is a unique name given to an object
By Ms. Neha Gakhar
that enables it to interact with other objects.
➢ Method:
• A method is a collection of statements that
perform some specific task and return the result
to the caller.
• A method can perform some specific task without
returning anything.
• Methods allow us to reuse the code without
retyping it, which is why they are considered time
savers.
• In Java, every method must be part of some class,
which is different from languages like C, C++, and
Python.
By Ms. Neha Gakhar
➢ Pillar 1: Abstraction
• Data Abstraction is the property by virtue of which only
the essential details are displayed to the user.
• The trivial or non-essential units are not displayed to
the user.
• Ex: A car is viewed as a car rather than its individual
components.
• Data Abstraction may also be defined as the process of
identifying only the required characteristics of an
object, ignoring the irrelevant details.
• The properties and behaviors of an object differentiate
it from other objects of similar type and also help in
classifying/grouping the object.

By Ms. Neha Gakhar


• Consider a real-life example of a man driving a
car. The man only knows that pressing the
accelerators will increase the car speed or
applying brakes will stop the car, but he does not
know how on pressing the accelerator, the speed
is actually increasing.
• He does not know about the inner mechanism of
the car or the implementation of the
accelerators, brakes etc. in the car.
• This is what abstraction is.
• In Java, abstraction is achieved
by interfaces and abstract classes. We can
achieve 100% abstraction using interfaces.

By Ms. Neha Gakhar


➢ Pillar 2: Encapsulation
• It is defined as the wrapping up of data under a single unit.
It is the mechanism that binds together the code and the
data it manipulates.
• Another way to think about encapsulation is that it is a
protective shield that prevents the data from being
accessed by the code outside this shield.
• Technically, in encapsulation, the variables or the data in a
class is hidden from any other class and can be accessed
only through any member function of the class in which
they are declared.
• In encapsulation, the data in a class is hidden from other
classes, which is similar to what data-hiding does. So, the
terms “encapsulation” and “data-hiding” are used
interchangeably.
• Encapsulation can be achieved by declaring all the variables
in a class as private and writing public methods in the class
to set and get the values of the variables.
By Ms. Neha Gakhar
➢ Pillar 3: Inheritance
• Inheritance is an important pillar of OOP (Object Oriented
Programming). It is the mechanism in Java by which one
class is allowed to inherit the features (fields and methods)
of another class.
• Let us discuss some frequently used important
terminologies:
• Superclass: The class whose features are inherited is known
as superclass (also known as base or parent class).
• Subclass: The class that inherits the other class is known as
subclass (also known as derived or extended or child class).
The subclass can add its own fields and methods in addition
to the superclass fields and methods.
• Reusability: Inheritance supports the concept of
“reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that
we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods of
the existing class. By Ms. Neha Gakhar
➢Pillar 4: Polymorphism
• It refers to the ability of object-oriented
programming languages to differentiate
between entities with the same name
efficiently.
• This is done by Java with the help of the
signature and declaration of these entities.

By Ms. Neha Gakhar


• Note: Polymorphism in Java is mainly of 2
types:
• Overloading
• Overriding

By Ms. Neha Gakhar


➢ Polymorphism in Java
• The word polymorphism means having many forms. In
simple words, we can define polymorphism as the ability of
a message to be displayed in more than one form.
• Real-life Illustration: Polymorphism
• A person at the same time can have different
characteristics. Like a man at the same time is a father, a
husband, an employee.
• So the same person possesses different behavior in
different situations. This is called polymorphism.
• Polymorphism is considered one of the important features
of Object-Oriented Programming.
• Polymorphism allows us to perform a single action in
different ways. In other words, polymorphism allows you to
define one interface and have multiple implementations.

By Ms. Neha Gakhar


• The word “poly” means many and “morphs” means forms,
So it means many forms.
➢ Types of polymorphism
• In Java polymorphism is mainly divided into two types:
1. Compile-time Polymorphism
2. Runtime Polymorphism
• Type 1: Compile-time polymorphism
• It is also known as static polymorphism. This type of
polymorphism is achieved by function overloading or
operator overloading.
• Note: But Java doesn’t support the Operator Overloading.

By Ms. Neha Gakhar


By Ms. Neha Gakhar
➢Method Overloading:
• When there are multiple functions with the
same name but different parameters then
these functions are said to be overloaded.
• Functions can be overloaded by change in the
number of arguments or/and a change in the
type of arguments.

By Ms. Neha Gakhar


In Java, two or more methods may have the
same name if they differ in parameters
(different number of parameters, different
types of parameters, or both). These methods
are called overloaded methods and this
feature is called method overloading. For
example:

Note: The return types of the above methods


are not the same. It is because method
overloading is not associated with return
types. Overloaded methods may have the
same or different return types, but they must
differ in parameters.
By Ms. Neha Gakhar
Why method overloading?
Suppose, you have to perform the addition of given numbers
but there can be any number of arguments
(let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods
sum2num(int, int) and sum3num(int, int, int) for two and
three parameters respectively.
However, other programmers, as well as you in the future may get
confused as the behavior of both methods
are the same but they differ by name.
The better way to accomplish this task is by overloading methods.
And, depending upon the
argument passed, one of the overloaded methods is called.
This helps to increase the readability of the program
By Ms. Neha Gakhar
• How to perform method overloading in Java?
• Here are different ways to perform method
overloading:

By Ms. Neha Gakhar


1. Overloading by changing the
number of parameters

By Ms. Neha Gakhar


By Ms. Neha Gakhar
2. Method Overloading by changing
the data type of parameters

By Ms. Neha Gakhar


By Ms. Neha Gakhar
• Important Points
• Two or more methods can have the same name
inside the same class if they accept different
arguments. This feature is known as method
overloading.
• Method overloading is achieved by either:
– changing the number of arguments.
– or changing the data type of arguments.
• It is not method overloading if we only change
the return type of methods. There must be
differences in the number of parameters.
By Ms. Neha Gakhar
➢ Constructors in Java
• Types of constructors
– Default Constructor
– Parameterized Constructor
• In Java, a constructor is a block of codes similar to the
method. It is called when an instance of the class is
created. At the time of calling constructor, memory for
the object is allocated in the memory.
• It is a special type of method which is used to initialize
the object.
• Every time an object is created using the new()
keyword, at least one constructor is called.
• It calls a default constructor if there is no constructor
available in the class. In such case, Java compiler
provides a default constructor by default.

By Ms. Neha Gakhar


• There are two types of constructors in Java: no-
arg constructor, and parameterized constructor.
• Note: It is called constructor because it
constructs the values at the time of object
creation. It is not necessary to write a constructor
for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
• Rules for creating Java constructor
• There are two rules defined for the constructor.
• Constructor name must be the same as its class
name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static,
final, and synchronized
By Ms. Neha Gakhar
➢Types of Java constructors
• There are two types of constructors in Java:
❑Default constructor (no-arg constructor)
❑Parameterized constructor

By Ms. Neha Gakhar


➢Java Default Constructor
• A constructor is called "Default Constructor"
when it doesn't have any parameter.
• Syntax of default constructor:
• <class_name>(){}

By Ms. Neha Gakhar


• Example of default constructor
• In this example, we are creating the no-arg constructor in the Bike class.
It will be invoked at the time of object creation.
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
[Link]("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
By Ms. Neha Gakhar
• Rule: If there is no constructor in a class,
compiler automatically creates a default
constructor.

By Ms. Neha Gakhar


By Ms. Neha Gakhar
Q) What is the purpose of a default constructor?
• The default constructor is used to provide the
default values to the object like 0, null, etc.,
depending on the type.

By Ms. Neha Gakhar


Example of default constructor that displays the default values
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
[Link]();
[Link]();
}
}
0 null 0 null By Ms. Neha Gakhar
• Explanation:In the above class,you are not
creating any constructor so compiler provides
you a default constructor. Here 0 and null
values are provided by default constructor.

By Ms. Neha Gakhar


➢Java Parameterized Constructor
• A constructor which has a specific number of
parameters is called a parameterized
constructor.
❑Why use the parameterized constructor?
• The parameterized constructor is used to
provide different values to distinct objects.
However, you can provide the same values
also.

By Ms. Neha Gakhar


• Example of parameterized constructor
• In this example, we have created the
constructor of Student class that have two
parameters.
• We can have any number of parameters in
the constructor.

By Ms. Neha Gakhar


//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}
111 Karan 222 Aryan

By Ms. Neha Gakhar


➢ Constructor Overloading in Java
• In Java, a constructor is just like a method but
without return type. It can also be overloaded
like Java methods.
• Constructor overloading in Java is a technique of
having more than one constructor with different
parameter lists.
• They are arranged in a way that each constructor
performs a different task.
• They are differentiated by the compiler by the
number of parameters in the list and their types.

By Ms. Neha Gakhar


Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}

111 Karan 0 222 Aryan 25


By Ms. Neha Gakhar
➢Difference between constructor and method
in Java
• There are many differences between
constructors and methods. They are given
below.

By Ms. Neha Gakhar


By Ms. Neha Gakhar
By Ms. Neha Gakhar
➢ Java static keyword
• The static keyword in Java is used for memory
management mainly.
• We can apply static keyword with variables,
methods, blocks and nested classes.
• The static keyword belongs to the class than an
instance of the class.
❑The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested class

By Ms. Neha Gakhar


1) Java static variable
• If you declare any variable as static, it is
known as a static variable.
• The static variable can be used to refer to the
common property of all objects (which is not
unique for each object), for example, the
company name of employees, college name of
students, etc.
• The static variable gets memory only once in
the class area at the time of class loading.

By Ms. Neha Gakhar


➢Advantages of static variable
• It makes your program memory efficient (i.e.,
it saves memory).
• Understanding the problem without static
variable
class Student{
int rollno;
String name;
String college="ITS";
}

By Ms. Neha Gakhar


• Suppose there are 500 students in my college,
now all instance data members will get
memory each time when the object is created.
• All students have its unique rollno and name,
so instance data member is good in such case.
• Here, "college" refers to the common
property of all objects.
• If we make it static, this field will get the
memory only once.
• Java static property is shared to all objects.

By Ms. Neha Gakhar


Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){[Link](rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//[Link]="BBDIT";
[Link]();
By Ms. Neha Gakhar
[Link]();
By Ms. Neha Gakhar
2) Java static method
• If you apply static keyword with any method,
it is known as static method.
• A static method belongs to the class rather
than the object of a class.
• A static method can be invoked without the
need for creating an instance of a class.
• A static method can access static data
member and can change the value of it.

By Ms. Neha Gakhar


//Java Program to get the cube of a given number using the static
method

class Calculate
{
static int cube(int x)
{
return x*x*x;
}

public static void main(String args[])


{
int result=[Link](5);
[Link](result);
}
}

By Ms. Neha Gakhar


3) Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.
• Example of static block
class A2
{
static
{
[Link]("static block is invoked");
}
public static void main(String args[])
{
[Link]("Hello main");
}
}
Output: static block is invoked
Hello main

By Ms. Neha Gakhar


➢ Final Keyword In Java
• The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
Final can be:
❑ variable
❑ method
❑ class
• The final keyword can be applied with the variables, a
final variable that have no value it is called blank final
variable or uninitialized final variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be
initialized in the static block only.

By Ms. Neha Gakhar


1) Java final variable
• If you make any variable as final, you cannot
change the value of final variable(It will be
constant).
❑Example of final variable
• There is a final variable speedlimit, we are
going to change the value of this variable, but
It can't be changed because final variable once
assigned a value can never be changed

By Ms. Neha Gakhar


class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
[Link]();
}
}
//end of class
Output:Compile Time Error
By Ms. Neha Gakhar
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike
{
final void run(){[Link]("running");
}
}

class Honda extends Bike


{
void run()
{
[Link]("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
[Link]();
}
} By Ms. Neha Gakhar
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda= new Honda();
[Link]();
}
}
Output compile time error
By Ms. Neha Gakhar
➢Java Package
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two
form, built-in package and user-defined
package.
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.

By Ms. Neha Gakhar


➢Advantage of Java Package
1) Java package is used to categorize the classes
and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

By Ms. Neha Gakhar


By Ms. Neha Gakhar
➢ Simple example of java package
• The package keyword is used to create a package
in java.
//save as [Link]
package mypack;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}
By Ms. Neha Gakhar
➢How to access package from another
package?
• There are three ways to access the package
from outside the package.
• import package.*;
• import [Link];
• fully qualified name.

By Ms. Neha Gakhar


➢ 1) Using packagename.*
• If you use package.* then all the classes and interfaces of
this package will be accessible but not subpackages.
• The import keyword is used to make the classes and
interface of another package accessible to the current
package.
• Example of package that import the packagename.*
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
By Ms. Neha Gakhar
//save by [Link]
package mypack;
import pack.*;

class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:Hello
By Ms. Neha Gakhar
2) Using [Link]
• If you import [Link] then only declared class
of this package will be accessible.
• Example of package by import [Link]
//save by [Link]

package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}

By Ms. Neha Gakhar


//save by [Link]
package mypack;
import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:Hello

By Ms. Neha Gakhar


3) Using fully qualified name
• If you use fully qualified name then only
declared class of this package will be
accessible.
• Now there is no need to import.
• But you need to use fully qualified name every
time when you are accessing the class or
interface.

By Ms. Neha Gakhar


• It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.
• Example of package by import fully qualified name
//save by [Link]
package pack;
public class A
{
public void msg(){[Link]("Hello");
}
}

//save by [Link]
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:Hello

By Ms. Neha Gakhar


➢this keyword in Java
• There can be a lot of usage of Java this
keyword.
• In Java, this is a reference variable that refers
to the current object.

By Ms. Neha Gakhar


➢Usage of Java this keyword
• this can be used to refer current class instance
variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class
constructor.

By Ms. Neha Gakhar


1) this: to refer current class instance variable
• The this keyword can be used to refer current
class instance variable.
• If there is ambiguity between the instance
variables and parameters, this keyword
resolves the problem of ambiguity.

By Ms. Neha Gakhar


Understanding the problem without this keyword
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee);
}
} By Ms. Neha Gakhar
class TestThis1
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}
}
Output:
0 null 0.0
0 null 0.0

By Ms. Neha Gakhar


• In the above example, parameters (formal
arguments) and instance variables are same.
So, we are using this keyword to distinguish
local variable and instance variable.

By Ms. Neha Gakhar


Solution of the above problem by this keyword
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee);
}
}

By Ms. Neha Gakhar


class TestThis2
{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0
By Ms. Neha Gakhar
• If local variables(formal arguments) and
instance variables are different, there is no
need to use this

By Ms. Neha Gakhar


2) this: to invoke current class method
• You may invoke the method of the current
class by using the this keyword.
• If you don't use the this keyword, compiler
automatically adds this keyword while
invoking the method. Let's see the example

By Ms. Neha Gakhar


By Ms. Neha Gakhar
class A
{
void m()
{
[Link]("hello m");
}
void n()
{
[Link]("hello n");
//m();//same as this.m()
this.m();
}
}
class B
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
hello n hello m By Ms. Neha Gakhar
3) this() : to invoke current class constructor
• The this() constructor call can be used to
invoke the current class constructor.
• It is used to reuse the constructor
• In other words, it is used for constructor
chaining.

By Ms. Neha Gakhar


Calling default constructor from parameterized
constructor:
class A
{
A()
{
[Link]("hello a");
}
A(int x)
{
this();
[Link](x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}
}
Output:
hello a 10
By Ms. Neha Gakhar
• Exception Handling in Java
• 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.

By Ms. Neha Gakhar


➢ What is Exception in Java?
• 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.

By Ms. Neha Gakhar


➢ 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
need to handle exceptions. Let's consider a scenario:
• statement 1;
• statement 2;
• statement 3;
• statement 4;
• statement 5;//exception occurs
• statement 6;
• statement 7;
• statement 8;
• statement 9;
• statement 10;

By Ms. Neha Gakhar


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

By Ms. Neha Gakhar


➢Hierarchy of Java Exception classes
• The [Link] class is the root class
of Java Exception hierarchy inherited by two
subclasses: Exception and Error.

By Ms. Neha Gakhar


The hierarchy of Java Exception classes is given below:

By Ms. Neha Gakhar


➢Types of Java Exceptions
• There are mainly two types of exceptions:
checked and unchecked.
• An error is considered as the unchecked
exception.
• However, according to Oracle, there are three
types of exceptions namely:
❑Checked Exception
❑Unchecked Exception
❑Error

By Ms. Neha Gakhar


➢ Difference between Checked and Unchecked
Exceptions
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. By Ms. Neha Gakhar
➢Java Exception Keywords
• Java provides five keywords that are used to
handle the exception.

By Ms. Neha Gakhar


The following table describes each.

By Ms. Neha Gakhar


➢ Java Exception Handling Example
• Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
[Link]
public class JavaExceptionExample{
public static void main(String args[]){
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
finally
{
[Link](“finally block will always excecute");
}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero rest of the code...

By Ms. Neha Gakhar


➢ Java throw Exception
• In Java, exceptions allows us to write good quality codes
where the errors are checked at the compile time instead
of runtime and we can create custom exceptions making
the code recovery and debugging easier.
• Java throw keyword
• The Java throw keyword is used to throw an exception
explicitly.
• We specify the exception object which is to be thrown. The
Exception has some message with it that provides the error
description. These exceptions may be related to user
inputs, server, etc.
• We can throw either checked or unchecked exceptions in
Java by throw keyword. It is mainly used to throw a custom
exception. We will discuss custom exceptions later in this
section.

By Ms. Neha Gakhar


• We can also define our own set of conditions
and throw an exception explicitly using throw
keyword. For example, we can throw
ArithmeticException if we divide a number by
another number. Here, we just need to set the
condition and throw exception using throw
keyword.
• The syntax of the Java throw keyword is given
below.
• throw Instance i.e.,

By Ms. Neha Gakhar


• throw new exception_class("error message");

• Let's see the example of throw IOException.


• throw new IOException("sorry device error");

• Where the Instance must be of type


Throwable or subclass of Throwable. For
example, Exception is the sub class of
Throwable and the user-defined exceptions
usually extend the Exception class.

By Ms. Neha Gakhar


Java throw Example
[Link]
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calcula
te square");
}
else {
[Link]("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
[Link](-3);
[Link]("Rest of the code..");
}
} By Ms. Neha Gakhar
By Ms. Neha Gakhar
➢ Java throws keyword
• 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 the normal
flow of the program 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
checking the code before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}

By Ms. Neha Gakhar


Java throws Example
[Link]
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
public static void main(String[] args)
{
TestThrows obj = new TestThrows();
try
{
[Link]([Link](45, 0));
}
catch (ArithmeticException e)
{
[Link]("\nNumber cannot be divided by 0");
}
[Link]("Rest of the code..");
}
}
By Ms. Neha Gakhar
By Ms. Neha Gakhar
Java throw and throws Example
[Link]
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
[Link]("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
[Link]("caught in main() method");
}
}
}

By Ms. Neha Gakhar


By Ms. Neha Gakhar
By Ms. Neha Gakhar
➢ Java Catch Multiple Exceptions
• 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
• At a time only one exception occurs and at a time
only one catch block is executed.
• All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before catch for
Exception.

By Ms. Neha Gakhar


public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
By Ms. Neha Gakhar
• Arithmetic Exception occurs
• rest of the code

By Ms. Neha Gakhar


➢ Java Nested try block
• 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).
• 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.

By Ms. Neha Gakhar


Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
By Ms. Neha Gakhar
}
By Ms. Neha Gakhar
By Ms. Neha Gakhar
• Why use custom exceptions?
• Java exceptions cover almost all the general type of
exceptions that may occur in the programming.
However, we sometimes need to create custom
exceptions.
• Following are few of the reasons to use custom
exceptions:
• To catch and provide specific treatment to a subset of
existing Java exceptions.
• Business logic exceptions: These are the exceptions
related to business logic and workflow. It is useful for
the application users or the developers to understand
the exact problem.
• In order to create custom exception, we need to
extend Exception class that belongs to [Link]
package.

By Ms. Neha Gakhar


• Let's see a simple example of Java custom
exception. In the following code, constructor
of InvalidAgeException takes a string as an
argument.
• This string is passed to constructor of parent
class Exception using the super() method.
• Also the constructor of Exception class can be
called without using a parameter and calling
super() method is not mandatory.

By Ms. Neha Gakhar


// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else {
[Link]("welcome to vote");
}
} By Ms. Neha Gakhar
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
[Link]("Caught the exception");

// printing the message from InvalidAgeException object


[Link]("Exception occured: " + ex);
}

[Link]("rest of the code...");


}
} By Ms. Neha Gakhar
➢Call by Value and Call by Reference in Java
• There is only call by value in java, not call by
reference. If we call a method passing a value,
it is known as call by value. The changes being
done in the called method, is not affected in
the calling [Link] of call by value in
java
• In case of call by value original value is not
changed. Let's take a simple example:

By Ms. Neha Gakhar


class Operation{
int data=50;

void change(int data){


data=data+100;//changes will be in the local variable only
}

public static void main(String args[]){


Operation op=new Operation();

[Link]("before change "+[Link]);


[Link](500);
[Link]("after change "+[Link]);

}
}
Output:before change 50 after change 50

By Ms. Neha Gakhar


• Another Example of call by value in java
• In case of call by reference original value is
changed if we made changes in the called
method. If we pass object in place of any
primitive value, original value will be changed.
In this example we are passing object as a
value. Let's take a simple example:

By Ms. Neha Gakhar


class Operation2{
int data=50;

void change(Operation2 op){


[Link]=[Link]+100;//changes will be in the instance variable
}

public static void main(String args[]){


Operation2 op=new Operation2();

[Link]("before change "+[Link]);


[Link](op);//passing object
[Link]("after change "+[Link]);

}
}
Output:before change 50 after change 150

By Ms. Neha Gakhar


By Ms. Neha Gakhar
By Ms. Neha Gakhar
By Ms. Neha Gakhar
By Ms. Neha Gakhar
By Ms. Neha Gakhar
By Ms. Neha Gakhar
By Ms. Neha Gakhar
By Ms. Neha Gakhar

You might also like