Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

UNIT - IV

Yogendra Prasad P
Exception Handling

Yogendra Prasad P
Exception Handling
• In Java, an exception is an event that interrupts the
normal flow of the program.
• It is an object which is thrown at runtime.
• Exception Handling is a mechanism to handle
runtime and compile time errors.
• The core advantage of exception handling is to
maintain the normal flow of the application.

Yogendra Prasad P
Cont.
• An exception normally disrupts the normal flow of the
application that is why we use exception handling.
Example:
1.statement 1; //a=10
2.statement 2; //b=20
3.statement 3; //c=10/0
4.statement 4;
5.statement 5;//exception occurs
6.statement 6;

• The java.lang.Throwable class is the root class of Java


Exception hierarchy which is inherited by two
subclasses:
1. Exception
2. Error.
Yogendra Prasad P
Cont.
Hierarchy of Java Exception classes:

Yogendra Prasad P
Cont.
Types of Java Exceptions:
There are mainly three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Errors
Checked Exception:
• Checked exceptions are checked at compile time.
Example: IOException, SQLException etc.

Yogendra Prasad P
Cont.
Unchecked Exception:
• The classes that extends runtime exceptions are know as
unchecked exception.
• Unchecked exceptions are not checked at compile time
rather than they are checked at runtime.
Example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Errors:
• Error is unrecoverable, it is considered as unchecked
exception.
Example: OutOfMemoryError, VirtualMachineError etc.

Yogendra Prasad P
Cont.
Java Exception handling keywords:
There are 5 keywords in java to handling exceptions
1. Try
2. Catch
3. Finally
4. Throw
5. Throws

Yogendra Prasad P
Cont.
Try:
• The "try" keyword is used to specify a block where we
should place exception code.
• The try block must be followed by either catch or finally. It
means, we can't use try block alone.
Catch:
• The "catch" block is used to handle the exception.
• It must be used after try block only.
• We can use multiple catch block with a single try.

Yogendra Prasad P
Cont.
Finally:
• Finally keyword is used to create a block of code that
follows a try block.
• Finally block of code is always executed whether an
exception has occurred or not.
• Finally block can be used to put clean up code such as
closing a file, closing connections etc.
Throw:
• The "throw" keyword is used to throw an exception.
Yogendra Prasad P
Cont.
Throws:
• The "throws" keyword is used to declare exceptions.
• It doesn't throw an exception.
• It specifies that there may occur an exception in the
method.
• It is always used with method signature.

Yogendra Prasad P
Cont.
Built-in-Exceptions
• Built-in exceptions are the exceptions which are
available in Java libraries.
• These exceptions are suitable to explain certain
error situations.
• Below is the list of important built-in exceptions in
Java.
1. ArithmeticException: It is thrown when an
exceptional condition has occurred in an
arithmetic operation.
Yogendra Prasad P
Cont.
2. ArrayIndexOutOfBoundsException: It is thrown to
indicate that an array has been accessed with an
illegal index. The index is either negative or greater
than or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised
when we try to access a class whose definition is
not found.
4. FileNotFoundException: This Exception is raised
when a file is not accessible or does not open.

Yogendra Prasad P
Cont.
5. IOException: It is thrown when an input-output
operation failed or interrupted.
6. InterruptedException: It is thrown when a thread
is waiting , sleeping , or doing some processing ,
and it is interrupted.
7. NoSuchFieldException: It is thrown when a class
does not contain the field (or variable) specified.
8. NoSuchMethodException: It is thrown when
accessing a method which is not found.
Yogendra Prasad P
Cont.
9. NullPointerException: This exception is raised
when referring to the members of a null object.
Null represents nothing.
10. NumberFormatException: This exception is raised
when a method could not convert a string into a
numeric format.
11.StringIndexOutOfBoundsException: It is thrown by
String class methods to indicate that an index is
either negative or greater than the size of the
string.
Yogendra Prasad P
Cont.
User-Defined Exceptions
• Sometimes, the built-in exceptions in Java are not able
to describe a certain situation.
• In such cases, user can also create exceptions which
are called “user-defined Exceptions”.
Following steps are followed for the creation of user-
defined Exception:
• The user should create an exception class as a subclass
of Exception class. Since all the exceptions are
subclasses of Exception class, the user should also
make his class a subclass of it.
Yogendra Prasad P
Cont.
• This is done as:
class MyException extends Exception
• We can write a default constructor in its own exception class.
MyException()
{
}
• To raise exception of user-defined type, we need to create an
object to its exception class and throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;

Yogendra Prasad P
Multithreading

Yogendra Prasad P
Multithreading in java
• The java programming language allows us to create a
program that contains one or more parts that can run
simultaneously at the same time.
• This type of program is known as a multithreading
program.
• Each part of this program is called a thread.
• Every thread defines a separate path of execution in java.

Yogendra Prasad P
Cont.
• A thread is explained in different ways:
• A thread is a light weight process.
• A thread is a subpart of a process that can run individually.
• In java, multiple threads can run at a time, which enables
the java to write multitasking programs.
• The multithreading is a specialized form of multitasking.
• All modern operating systems support multitasking.

Yogendra Prasad P
Cont.
• There are two types of multitasking:
1. Process-based multitasking
2. Thread-based multitasking
Thread Life Cycle:
• In java, a thread goes through different states throughout its
execution.
• These stages are called thread life cycle states or phases.
• A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state.

Yogendra Prasad P
Cont.

Yogendra Prasad P
Cont.
New:
When a thread object is created using new, then the thread
is said to be in the New state. This state is also known as Born
state.
Example: Thread t1 = new Thread();
Runnable / Ready:
When a thread calls start( ) method, then the thread is said
to be in the Runnable state. This state is also known as a Ready
state.
Example: t1.start( );

Yogendra Prasad P
Cont.
Running:
When a thread calls run( ) method, then the thread is
said to be Running. The run( ) method of a thread called
automatically by the start( ) method.
Blocked / Waiting:
A thread in the Running state may move into the blocked
state due to various reasons like sleep( ) method called, wait( )
method called, suspend( ) method called, and join( ) method
called, etc.

Yogendra Prasad P
Cont.
Dead / Terminated:
• A thread in the Running state may move into the dead state
due to either its execution completed or the stop( ) method
called.
• The dead state is also known as the terminated state.

Yogendra Prasad P
Cont.
Creating threads in java:
• The java programming language provides two ways to create
threads:
 Using Thread class (by extending Thread class)
 Using Runnable interface (by implementing Runnable interface)

Extending Thread class:


• The java contains a built-in class Thread inside the java.lang
package.
• The Thread class contains all the methods that are related to the
threads.

Yogendra Prasad P
Cont.
Implementing Runnable interface:
• The java contains a built-in interface Runnable inside the
java.lang package.
• The Runnable interface implemented by the Thread class
that contains all the methods that are related to the
threads.

Yogendra Prasad P
Cont.
Thread class:
• The Thread class in java is a subclass of Object class and it
implements Runnable interface.
• The Thread class is available inside the java.lang package.
• The Thread class has the following syntax
class Thread extends Object implements Runnable
{
...
}

Yogendra Prasad P
Cont.
The Thread class has the following constructors:
• Thread( )
• Thread( String threadName )
• Thread( Runnable objectName )
• Thread( Runnable objectName, String threadName )

Yogendra Prasad P
Cont.
The Thread classs contains the following methods:
• run( ) • activeCount()
• start( ) • currentThread( )
• setName(String) • sleep( long )
• getName(String) • isAlive( )
• setPriority(int) • yield( )
• getPriority( ) • join( )
• getId( )
Yogendra Prasad P
Cont.
Java Thread Priority:
• In a java programming language, every thread has a
property called priority.
• Most of the scheduling algorithms use the thread priority to
schedule the execution sequence.
• In java, the thread priority range from 1 to 10.
• Priority 1 is considered as the lowest priority, and priority 10
is considered as the highest priority.

Yogendra Prasad P
Cont.
• The java programming language Thread class provides two
methods setPriority(int) and getPriority( ) to handle thread
priorities.
• The Thread class also contains three constants that are used
to set the thread priority
• MAX_PRIORITY: It has the value 10 and indicates highest priority.
• NORM_PRIORITY: It has the value 5 and indicates normal priority.
• MIN_PRIORITY: It has the value 1 and indicates lowest priority.

Yogendra Prasad P
Cont.
setPriority( ) method:
• The setPriority( ) method of Thread class used to set the priority
of a thread.
• It takes an integer range from 1 to 10 as an argument and returns
nothing (void).
Example:
threadObject.setPriority(4);
(or)
threadObject.setPriority(MAX_PRIORITY);

Yogendra Prasad P
Cont.
getPriority( ) method:
• The getPriority( ) method of Thread class used to access the
priority of a thread.
• It does not takes any argument and returns name of the
thread as String.
Example:
String threadName = threadObject.getPriority();

Yogendra Prasad P
Cont.
Java Thread Synchronization:
• The java programming language supports multithreading.
• The problem of shared resources occurs when two or more
threads get execute at the same time.
• In such a situation, we need some way to ensure that the
shared resource will be accessed by only one thread at a
time, and this is performed by using the concept called
synchronization.

Yogendra Prasad P
Cont.
• The synchronization is the process of allowing only one
thread to access a shared resource at a time.
• In java, the synchronization is achieved using the following
concepts
• Mutual Exclusion
• Inter thread communication

Yogendra Prasad P
Cont.
Mutual Exclusion:
• Using the mutual exclusion process, we keep threads from
interfering with one another while they accessing the
shared resource.
• In java, mutual exclusion is achieved using the following
concepts
• Synchronized method
• Synchronized block

Yogendra Prasad P
Cont.
Synchronized method:
• When a method created using a synchronized keyword, it allows
only one object to access it at a time.
• When an object calls a synchronized method, it put a lock on that
method so that other objects or thread that are trying to call the
same method must wait, until the lock is released.
• Once the lock is released on the shared resource, one of the
threads among the waiting threads will be allocated to the
shared resource.

Yogendra Prasad P
Cont.

Yogendra Prasad P
Cont.
Synchronized block:
• The synchronized block is used when we want to synchronize
only a specific sequence of lines in a method.
• For example, let's consider a method with 20 lines of code where
we want to synchronize only a sequence of 5 lines code, we use
the synchronized block.
Syntax:
synchronized(object)
{
...
block code
...
}
Yogendra Prasad P
Cont.
Inter-thread communication:
• Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each
other.
• Cooperation (Inter-thread communication) is a mechanism
in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same
critical section to be executed.

Yogendra Prasad P
Cont.
• It is implemented by following methods of Object class:
1. wait()
2. notify()
3. notifyAll()
wait() method:
• It causes current thread to release the lock and wait until
either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of
time has elapsed.
Yogendra Prasad P
Cont.
• The current thread must own this object's monitor, so it
must be called from the synchronized method only
otherwise it will throw exception.
notify() method:
• It wakes up one single thread that called wait() on the same
object.
• It should be noted that calling notify() does not actually give
up a lock on a resource.
Syntax: public final void notify()

Yogendra Prasad P
Cont.
notifyAll() method:
It wakes up all the threads that called wait() on the same
object.
Syntax: public final void notifyAll()

Yogendra Prasad P
Collection Framework

Yogendra Prasad P
Collections in Java
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of objects.
• Java Collections can achieve all the operations that we
perform on a data such as searching, sorting, insertion,
manipulation, and deletion.
• Java Collection means a single unit of objects (i.e., a group).

Yogendra Prasad P
Cont.
Java Collection framework provide:
Interfaces:
• Set, List, Queue, Deque.
Classes:
• ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet.

Yogendra Prasad P
Framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
Collection framework:
• The Collection framework represents a unified architecture
for storing and manipulating a group of objects. It has:
1. Interfaces
2. Classes
Yogendra Prasad P
Hierarchy of Collection Framework
• The java.util package contains all the classes and interfaces for the
Collection framework.

Yogendra Prasad P
ArrayList Class
• Java ArrayList class uses a dynamic array for storing the elements.
• It is like an array, but there is no size limit.
• We can add or remove elements anytime.
• So, it is much more flexible than the traditional array.
• It is found in the java.util package.
• The ArrayList in Java can have the duplicate elements also.

Yogendra Prasad P
Cont.
• It implements the List interface so we can use all the methods of List
interface here.
• It inherits the AbstractList class and implements List interface.
• Java ArrayList allows random access because array works at the index
basis.

Yogendra Prasad P
Cont.
Example:
Create an ArrayList object called cars that will store strings:

import java.util.ArrayList;
// import the ArrayList class
ArrayList<String> cars = new ArrayList<String>();
// Create an ArrayList object

Yogendra Prasad P
Cont.
Add Items:
• The ArrayList class has many useful methods.
• For example, to add elements to the ArrayList, use the add() method.
Access an Item:
• To access an element in the ArrayList, use the get() method and refer
to the index number.
Example: cars.get(0);
Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Yogendra Prasad P
Cont.
Change an Item:
• To modify an element, use the set() method and refer to the index
number.
Example: cars.set(0, “Suzuki");
Remove an Item:
• To remove an element, use the remove() method and refer to the
index number.
Example: cars.remove(0);

Yogendra Prasad P
Cont.
Remove all Item:
• To remove all the elements in the ArrayList, use the clear() method.
Example: cars.clear();
ArrayList Size:
• To find out how many elements an ArrayList have, use the size()
method.
Example: cars.size()
System.out.println(cars.size());

Yogendra Prasad P
Cont.
Loop Through an ArrayList:
• Loop through the elements of an ArrayList with a for loop, and use
the size() method to specify how many times the loop should run.
• We can also loop through an ArrayList with the for-each loop.
Other Types:
• Elements in an ArrayList are actually objects.
• In the examples above, we created elements (objects) of type
"String".

Yogendra Prasad P
Cont.
• To use other types, such as int, you must specify an equivalent
wrapper class: Integer.
Sort an ArrayList:
• Another useful class in the java.util package is the Collections class,
which include the sort() method for sorting lists alphabetically or
numerically.

Yogendra Prasad P
LinkedList Class
• Java LinkedList class uses a doubly linked list to store the elements.
• It provides a linked-list data structure.
• The LinkedList class is almost identical to the ArrayList
• It inherits the AbstractList class and implements List and Deque
interfaces.
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.

Yogendra Prasad P
Cont.

• Java LinkedList class is non synchronized.


• In Java LinkedList class, manipulation is fast
because no shifting needs to occur.
• Java LinkedList class can be used as a list,
stack or queue.

Yogendra Prasad P
Cont.
LinkedList Methods:

Method Description
addFirst() Adds an item to the beginning of the list.

addLast() Add an item to the end of the list

removeFirst() Remove an item from the beginning of the list.

removeLast() Remove an item from the end of the list

getFirst() Get the item at the beginning of the list

getLast() Get the item at the end of the list

Yogendra Prasad P
HashSet Class
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order. Here, elements are
inserted on the basis of their hash code.
• HashSet is the best approach for search operations.

Yogendra Prasad P
Cont.
Difference between List and Set:
A list can contain duplicate elements whereas
Set contains unique elements only.
Hierarchy of HashSet class:
The HashSet class extends AbstractSet class
which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in
hierarchical order.

Yogendra Prasad P
Cont.
• HashSet is found in the java.util package.
Example:
import java.util.HashSet; // Import the HashSet class
HashSet<String> cars = new HashSet<String>();
//Creating a HashSet object called cars that will store strings

Yogendra Prasad P
Cont.
Add Items:
• The HashSet class has many useful methods.
• For example, to add items to it, use the add() method.
Check If an Item Exists:
• To check whether an item exists in a HashSet, use the contains()
method.
Remove an Item:
• To remove an item, use the remove() method.
• To remove all items, use the clear() method.
Yogendra Prasad P
Cont.
HashSet Size:
• To find out how many items there are, use the size() method.
Loop Through a HashSet:
• We can use the looping statements in this class.
Other Types:
• To use other types, such as int, we must specify an equivalent
wrapper class: Integer.
• For other primitive types, use: Boolean for boolean, Character for
char, Double for double, etc.
Yogendra Prasad P

You might also like