III Module
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.
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.
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.
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.
int a=50/0;//ArithmeticException
String s=null;
System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
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
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
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
}
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.
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
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 is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
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()); } } }
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]
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.
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
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
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);
}