Unit 4
Unit 4
BCA133A
BCA DEPT.
UNIT-4
REKHA KUSHWAHA
ASSISTANT PROFESSOR
JECRC UNIVERSITY
Import
java.util.*;
UNIT-4
• Packages and Interfaces: Introduction of packages, finding packages and class path, access
protection, importing packages, interfaces and their types.
• Exception handling: Exception handling fundamentals, Exception types, uncaught exceptions, use
of try and catch, multiple catch clause, nested try statements, use of throw statement, javas built in
exceptions, chained exceptions, use of exceptions.
• Multithreaded programming: The java thread model, thread priorities, synchronization,
messaging, thread class and the run able interface, main thread, creating a thread, thread priorities,
synchronization methods, inter thread communication, deadlock, suspending, resuming, and
stopping threads, modern way to suspend, resume and stopping the threads and use of multithread.
Import java.util.*;
Import java.util.Scanner;
Import java.awt.*; GUI
JAVA PACKAGE Import javax.
Import java.lang.*;
• 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.
NC;= abc
Pack1=abc
Pack1=abc
Import java.util.*;
Import java.awt.*;
CONT.. Import java.lang.*;
Error run time error
Scanne
r
EXCEPTION HANDLING IN JAVA Compiler;= Syntax (type)
Int a=10,b=0,c; c=a/b;
scanner
Run time := Semantic (meaning) logic
• 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.
Try{c=a/0;} if try T Age<18 Try{divide zero}
Catch() Than votting Catch(arithmetic exception);
{
JAVA EXCEPTION KEYWORDS
out(cant divide by
zero)
}
Finally{} • Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try
block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch
block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is
handled or not.
throw The "throw" keyword is used to throw / raise an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method signature.
JAVA TRY-CATCH BLOCK
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
CONT..
catch(ArrayIndexOutOfBoundsException e)
public class MultipleCatchBlock1 {
{
public static void main(String[] args) {
System.out.println("ArrayIndexOutOfBounds E
try{ xception occurs");
int a[]=new int[5]; }
a[5]=30/0; catch(Exception e)
} {
catch(ArithmeticException e) System.out.println("Parent Exception occurs");
{ }
System.out.println("Arithmetic Exception oc System.out.println("rest of the code");
curs"); }
} }
JAVA FINALLY BLOCK
• Java finally block is a block used to execute important code such as closing the connection, etc.
• Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs or
not.
• The finally block follows the try-catch block.
Why use Java finally block?
• finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
• The important statements to be printed can be placed in the finally block.
CASE 1: WHEN AN EXCEPTION DOES NOT OCCUR
LET'S SEE THE BELOW EXAMPLE WHERE THE JAVA PROGRAM DOES NOT THROW ANY EXCEPTION, AND THE FINALLY BLOCK
IS EXECUTED AFTER THE TRY BLOCK .
class TestFinallyBlock { //
public static void main(String args[]){ executed regardless of exception occurred or not
try{
//below code do not throw any exception
finally {
int data=25/5; System.out.println("finally block is always exec
uted");
System.out.println(data);
}
}
//catch won't be executed
catch(NullPointerException e){ System.out.println("rest of phe code...");
System.out.println(e); }
} }
CASE 2: WHEN AN EXCEPTION OCCURR BUT NOT HANDLED BY THE CATCH BLOCK
LET'S SEE THE THE FILLOWING EXAMPLE. HERE, THE CODE THROWS AN EXCEPTION HOWEVER THE CATCH BLOCK CANNOT HANDLE IT. DESPITE THIS, THE FINALLY BLOCK IS
EXECUTED AFTER THE TRY BLOCK AND THEN THE PROGRAM TERMINATES ABNORMALLY.
public class TestFinallyBlock1{ //
public static void main(String args[]){ executes regardless of exception occured or
try { not
System.out.println("Inside the try block");
finally {
//below code throws divide by zero exception
System.out.println("finally block is al
int data=25/0;
ways executed");
System.out.println(data);
} }
//cannot handle Arithmetic type exception System.out.println("rest of the code...");
//can only accept Null Pointer type exception
catch(NullPointerException e){
}
System.out.println(e);
}
}
CASE 3: WHEN AN EXCEPTION OCCURS AND IS HANDLED BY THE CATCH BLOCK
LET'S SEE THE FOLLOWING EXAMPLE WHERE THE JAVA CODE THROWS AN EXCEPTION AND THE CATCH BLOCK
HANDLES THE EXCEPTION. LATER THE FINALLY BLOCK IS EXECUTED AFTER THE TRY-CATCH BLOCK.
FURTHER, THE REST OF THE CODE IS ALSO EXECUTED NORMALLY.
public class TestFinallyBlock2{
public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
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.
SYNTAX
public class TestThrow1 {
void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
EXAMPLE
public class TestThrow {
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
} }
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
}
EXAMPLE
public class TestThrows {
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 {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
} }
EXAMPLE
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
} }
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
} }
DIFFERENCE BETWEEN THROW AND THROWS IN
JAVA
• The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.
• There are many differences between throw
• and throws
• keywords. A list of differences between throw and throws are given below:
CONT…
2. Type of exception Using throw keyword, we Using throws keyword, we can declare both checked and unchecked
can only propagate unchecked exception exceptions. However, the throws keyword can be used to propagate
i.e., the checked exception cannot be checked exceptions only.
propagated using throw only.
3. Syntax The throw keyword is followed by an instance of Exception to be The throws keyword is followed by class
thrown. names of Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the method signature.
5. Internal implementation We are allowed to throw only one exception at a time i.e. we cannot We can declare multiple exceptions using
throw multiple exceptions. throws keyword that can be thrown by the
method. For example, main() throws
IOException, SQLException.
INTRODUCTION TO JAVA THREADS
• Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an
independent path of execution within a program. Many threads can run concurrently within a program.
Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can
have many threads, and these threads can run concurrently, either asynchronously or synchronously.
• Multithreading has several advantages over Multiprocessing such as;
• Threads are lightweight compared to processes
• Threads share the same address space and therefore can share both data and code
• Context switching between threads is usually less expensive than between processes
• Cost of thread intercommunication is relatively low that that of process intercommunication
• Threads allow different tasks to be performed concurrently.
Class mythread extends Thread
Main()
• A thread in Java can be created in the following two ways: {
Thread obj=new Thread(new
• Extending java.lang.Thread class child());
Obj.start();
• In this case, a thread is created by a new class that extends the Thread class,
creating an instance of that class. The run() method includes the functionality
that is supposed to be implemented by the Thread.
• Below is an example to create a thread by extending java.lang.Thread class.
class mythread extends Thread
{ EXAMPLE
public void run()
}
Here, start() is used to create a
new thread and to make it
public class file1 runnable. The new thread begins
{ inside the void run() method.
obj1.start();
}
IMPLEMENTING RUNNABLE INTERFACE
• This is the easy method to create a thread among the two. In this case, a class is created
to implement the runnable interface and then the run() method.
• The code for executing the Thread should always be written inside the run() method.
• Here's a code to make you understand it.
LIFECYCLE OF A THREAD IN JAVA
• The Life Cycle of a Thread in Java refers to the state transformations of a thread
that begins with its birth and ends with its death. When a thread instance is
generated and executed by calling the start() method of the Thread class, the
thread enters the runnable state. When the sleep() or wait() methods of the
Thread class are called, the thread enters a non-runnable mode.
• Thread returns from non-runnable state to runnable state and starts statement
execution. The thread dies when it exits the run() process. In Java, these thread
state transformations are referred to as the Thread life cycle.
THERE ARE BASICALLY 4 STAGES IN THE LIFE
CYCLE OF A THREAD, AS GIVEN BELOW:
1.New
2.Runnable
3.Running
4.Blocked (Non-runnable state)
5.Dead
THREAD CYCLE
CPU allocate
CONT..
• New State
• As we use the Thread class to construct a thread entity, the thread is born and is defined as being in the New state. That is,
when a thread is created, it enters a new state, but the start() method on the instance has not yet been invoked.
• Runnable State
• A thread in the runnable state is prepared to execute the code. When a new thread's start() function is called, it enters a
runnable state.
• In the runnable environment, the thread is ready for execution and is awaiting the processor's availability (CPU time). That is, the
thread has entered the queue (line) of threads waiting for execution.
• Running State
• Running implies that the processor (CPU) has assigned a time slot to the thread for execution. When a thread from the runnable
state is chosen for execution by the thread scheduler, it joins the running state.
• In the running state, the processor allots time to the thread for execution and runs its run procedure. This is the state in which
the thread directly executes its operations. Only from the runnable state will a thread enter the running state.
CONT..
• Blocked State
• When the thread is alive, i.e., the thread class object persists, but it cannot be
selected for execution by the scheduler. It is now inactive.
• Dead State
• When a thread's run() function ends the execution of sentences, it automatically
dies or enters the dead state. That is, when a thread exits the run() process, it is
terminated or killed. When the stop() function is invoked, a thread will also go
dead.
JAVA THREAD PRIORITIES
The number of services assigned to a given thread is referred to as its priority. Any thread generated in the JVM is given a
priority. The priority scale runs from 1 to 10.
• 1 is known as the lowest priority.
• 5 is known as standard priority.
• 10 represents the highest level of priority.
The main thread's priority is set to 5 by default, and each child thread will have the same priority as its parent thread. We
have the ability to adjust the priority of any thread, whether it is the main thread or a user-defined thread. It is advised to
adjust the priority using the Thread class's constants, which are as follows:
1.Thread.MIN_PRIORITY;
2.Thread.NORM_PRIORITY;
3.Thread.MAX_PRIORITY;
EXAMPLE