0% found this document useful (0 votes)
3 views17 pages

III Module

The document provides an overview of Exception Handling in Java, explaining the types of exceptions (checked, unchecked, and errors) and the keywords used in exception handling (try, catch, finally, throw, and throws). It also covers multithreading concepts, including thread creation, thread states, thread scheduling, and synchronization. Additionally, the document touches on Java Enums, Wrapper Classes, Autoboxing, Unboxing, Java Annotations, and Collections.
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)
3 views17 pages

III Module

The document provides an overview of Exception Handling in Java, explaining the types of exceptions (checked, unchecked, and errors) and the keywords used in exception handling (try, catch, finally, throw, and throws). It also covers multithreading concepts, including thread creation, thread states, thread scheduling, and synchronization. Additionally, the document touches on Java Enums, Wrapper Classes, Autoboxing, Unboxing, Java Annotations, and Collections.
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/ 17

III Module

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.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition, an exception is an event that disrupts the
normal flow of the program

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


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

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception
• Checked Exception
• Unchecked Exception
• Error
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. Examples IOException
FileNotFoundException, ClassNotFoundException, SQLException

Unchecked Exceptions: Unchecked exceptions are called run-time exceptions because these
exceptions are checked at run-time by the compiler. Examples ArithmeticException,
NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException

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

Java Exception Keywords


the exception handling mechanism uses five keywords namely try, catch, finally, throw, and throws.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception.

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.


Common Scenarios of Java Exceptions

int a=50/0;//ArithmeticException

String s=null;
System.out.println(s.length());//NullPointerException

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

The try : is used to define a block of code that will be tests the occurence of an exception.
The catch : is used to define a block of code that handles the exception occured in the respective
try block.

Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Example
public class Test {
public static void main(String[] args) {
try {
int data=50/0; //may throw exception }
//handling the exception
catch(ArithmeticException e) {
System.out.println(e); }
System.out.println("rest of the code"); } }

Out put

java.lang.ArithmeticException: / by zero
rest of the code

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.
Example
public class Test {

public static void main(String[] args) {


try{
int a[]=new int[5];
a[5]=30/0; }
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs"); }
System.out.println("rest of the code"); } }
Out put
Arithmetic Exception occurs
rest of the code

Java Nested try block


try block inside another try block is permitted. It is called as nested try block.

public class Test{


public static void main(String args[]){
try{
try{
System.out.println("going to divide by 0");
int b =39/0; }
catch(ArithmeticException e) {
System.out.println(e); }
System.out.println("other statement"); }
catch(Exception e) {
System.out.println("handled the exception (outer catch)"); }
System.out.println("normal flow.."); } }
Out put
going to divide by 0
java.lang.ArithmeticException: / by zero
other statement
normal flow..

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

Why use Java finally block?


finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.
Example
class Test {
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data); }
catch(NullPointerException e){
System.out.println(e); }
finally {
System.out.println("finally block is always executed"); }
System.out.println("rest of the code..."); } }
Out put
5
finally block is always executed
rest of the code..

The throw keyword


The throw statement allows you to create a custom error.
Syntax
throw new exception_class("error message");
Example
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old."); }
else {
System.out.println("Access granted - You are old enough!"); } }
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...) }. }

throws: with the help of the throws keyword, we can provide information to the caller of the
method about the exception.

Syntax
return_type method_name() throws exception_class_name{
//method code
}

Example
class Test {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(10000);
System.out.println("Hello”);} }
Out put
Hello

Multithreading: Multithreading in Java is a process of executing multiple threads simultaneously.

Multitasking:Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
1)Process-based Multitasking (Multiprocessing)
• Executing multiple tasks simultaneously where each task is a separate independent Process
• Each process allocates a separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
• Executing multiple tasks simultaneously where each task is a separate independent part of the
same program
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

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( );
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.
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.
How to create a thread in Java
There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
extending Thread class
follow the step given below.
Step-1: create a class that extends Thread class.
Step-2: Override the run( ) method with the code
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.

Example
class Mythread extends Thread {
public void run(){
for(int i=0;i<3;i++)
System.out.println("child thread");}}
class Test {
public static void main(String args[]){
Mythread t1=new Mythread();
t1.start();
for(int i=0;i<3;i++)
System.out.println("main thread");}}
Output:
child thread
main thread
implementing Runnable interface
follow the step given below.
To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Step-2: Override the run( ) method with the code
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the Thread
class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step
Example
class Multi implements Runnable{
public void run(){
for(int i=0;i<3;i++)
System.out.println("child thread"); } }
class Test {
public static void main(String args[]){
Multi m1=new Multi();
Thread t1 =new Thread(m1);
t1.start();
for(int i=0;i<3;i++)
System.out.println("main thread");}}

Output:
child thread
main thread
Thread Scheduler in Java
• A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java.
• However, if there is more than one thread in the runnable state, the thread scheduler to pick one
of the threads and ignore the other ones.
• There are some criteria that decide which thread will execute first. There are two factors for
scheduling a thread i.e. Priority and Time of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means that
thread has got a better chance of getting picked up by the thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority
cannot be the factor to pick a thread from these two threads. In such a case, arrival time of thread is
considered by the thread scheduler. A thread that arrived first gets the preference over the other
threads.

thread priorities:
• Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). 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, and they
are listed below.
• 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.

setPriority( ) method: 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);

getPriority( ) method: used to access the priority of a thread. It does not takes anyargument and
returns name of the thread as String.
Example
String threadName = threadObject.getPriority();
Example
class SampleThread extends Thread{
public void run() {
System.out.println("Current Thread: " + Thread.currentThread().getName());}}
public class Test {
public static void main(String[] args) {
SampleThread t1 = new SampleThread();
SampleThread t2 = new SampleThread();
t1.setName("first");
t2.setName("second");
t1.setPriority(4);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();}}
Out put
Current Thread: second
Current Thread: first

Synchronization : is the capability to control the access of multiple threads to any shared resource.

class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=3;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t; }
public void run(){
t.printTable(5); } }
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; }
public void run(){
t.printTable(10); } }
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start(); } }
Out put
5
10
15
10
20
30
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the
method.
• Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such
cases, we can use synchronized block.
Syntax
synchronized (object reference expression) {
//code block
}

Inter-thread Communication: Inter-thread communication is all about allowing synchronized


threads to communicate with each other.
It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
wait()
The wait() method 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.
notify()
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs
at the discretion of the implementation.
Syntax:
public final void notify()
notifyAll()
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

ThreadGroup: Java provides a convenient way to group multiple threads in a single object. In such
a way, we can suspend, resume or interrupt a group of threads by a single method call.
Example
Thread.currentThread().getThreadGroup().getName()

Daemon Thread : Daemon thread in Java is a service provider thread that provides services to the
user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.

Example
public class DaemonThread extends Thread{
public void run( ){
for(int I=0;i<3;i++){
System.out.println("daemon thread work");
try{
thread.sleep(200); }
catch( InterruptedException e){ } } }
class Test {
public static void main(String[] args){
DaemonThread t1=new TestDaemonThread();//creating thread
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
System.out.println(“end of main thread"); } }

Out put
daemon thread work
user thread work

Java Enums :The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , According to the Java naming conventions, we should
have all constants in capital letters. So, we have enum constants in capital letters.

Defining Java Enum


enum Season { WINTER, SPRING, SUMMER, FALL }

Example
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER }
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}}
Out put
WINTER
SPRING
SUMMER

Java Wrapper Classes


Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

Primitive Data Type. Wrapper Class


byte. Byte
short. Short
int. Integer
long. Long
float. Float
double. Double
boolean Boolean
char. Character

Autoboxing and Unboxing: The automatic conversion of primitive data types into its equivalent
Wrapper type is known as boxing and opposite operation is known as unboxing.
Autoboxing
Example
Integer I =10;
Compiler replace with this code
Integer I = Integer.valueof(10);

Unboxing:
Example
Integer I = new Integer(10);
int i= I;
Compiler replace with this code
int I=I.intValue();

Java Annotations Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can be used by java
compiler and JVM.

@Override @Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.
Collections in Java :Collection is an interface which can be used to represent a group of individual
objects as a single entity.
Collections: is an utility class present in java.util. package to define several utility methods (like
Sorting, Searching...) for Collection objects.

List Interface : List is child interface of Collection.


If we want to represent a group of individual objects as a single entity where duplicates are allowed
and insertion order preserved then we should go for List.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :

List <data-type> list1= new ArrayList();


List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized.

import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }

Adding an element at the specific position : al.add(1, "Gaurav");


Adding second list elements to the first list : al.addAll(al2);
Adding an element at the first position : al.addFirst("Lokesh");
Adding an element at the last position :al.addLast(“Harsh");

Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.

import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.

Example
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }

Out put
Ayush
Garvit
Amit
Ashish
Garima

set interface
• It is the child interface of Collection.
• If we want to represent a group of individual objects as a single entity where duplicates are not
allowed and insertion order not preserved then we should go for Set.

SortedSet:
• It is the child interface of Set.
• If we want to represent a group of individual objects as a single entity where duplicates are not
allowed but all objects should be inserted according to some sorting orde then we should go for
SortedSet.
NavigableSet:
It is the child interface of SortedSet if defines several methods for navigation purposes.

Example
import java.util.*;
public class setExample{
public static void main(String[] args) {
Set<String> data = new LinkedHashSet<String>();
data.add("Ashish");
data.add("Ayush");
data.add("Garima");
System.out.println(data); } }
Out put
[Ashish , Ayush ,Garima]

Operations on the Set Interface


On the Set, we can perform all the basic mathematical operations like intersection, union and
difference.
Example
set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2, 83, 45, 3, 12, 55].

Intersection: The intersection operation returns all those elements which are present in both the set.
The intersection of set1 and set2 will be [33, 45, 55].

Union: The union operation returns all the elements of set1 and set2 in a single set, and that set can
either be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83].
Difference: The difference operation deletes the values from the set which are present in another
set. The difference of the set1 and set2 will be [66, 34, 22, 77].

Queue :
• It is child interface of Collection.
• If we want to represent a group of individual objects prior to processing then we should go for
Queue.
Example
Before sending a mail all mail id's we have to store somewhere and in which order we saved in the
same order mail's should be delivered (First in First out) for this requirement Queue concept is the
best choice.

Java Map Interface


• Map is not the child interface of Collection.
• If we want to represent a group of individual objects as key value pairs then should go for Map.
• Both key and value are objects, duplicated keys are not allowed but values can be duplicated

SortedMap:
• It is the child interface of map.
• If we want to represent a group of key value pairs according to some sorting order of keys then
we should go for SortedMap

NavigableMap:
It is the child interface of sorted map, it defines several utility methods for navigation purpose.
import java.util.*;
public class Test {
public static void main(String[] args) {
Map map=new HashMap();
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue()); } } }

Out put

1 Amit
5 Rahul
2 Jai
6 Amit

Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the
code stable by detecting the bugs at compile time.
Advantage of Java Generics
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
Arrays:
String [ ] s= new String [10];
s[0]= “Amit”;
s[1]=new Integer(10);// CE

Collection
ArrayList l =new ArrayList();
l.add(“Amit”);
l.add(new Integer(10));

Retrieval
String name1=(String)l.get(0);
String name2=(String)l.get(1);// CE

With Generics, it is required to specify the type of object we need to store.


List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error

2) Type casting is not required: There is no need to typecast the object.

Arrays:
String [ ] s= new String [10];
s[0]= “Amit”;

Retrieval
String name=s[0];

Collection
ArrayList l =new ArrayList();
l.add(“Amit”);

Retrieval
String name1=l.get(0);//CE

List<Integer> l = new ArrayList<Integer>();


l.add(10);

Retrieval
String name=l.get[0];

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
Generic class
Like the generic class, we can create a generic method that can accept any type of arguments.

1.4v
class AL {
add(Obj o)
Object.get(int Integer)
}
1.5v
class AL<T> {
add(T t);
T.get(int Integer);
}
AL <String> l = new AL<String )();
Compiler replace with this code
class AL <String>
{
add(string s);
String get(int integer);
}

You might also like