JAVA Unit III Notes
JAVA Unit III Notes
Error:
● Error is a situation which prevents the normal execution of our program.
● There are generally three type of errors:-
1. Syntax Error:-Syntax error refers to the grammatical error while writing a code or
program.
Common example are:-
a. Missing Semicolons
b. Improperly Matching (,[,{
c. Incorrect Format In Selection And Loop Statement
2. Runtime Error :-They occurs when a program with no Syntax error asks the computer
to do something that the computer is unable to do. These errors occur in the run mode
of a program.
Common examples are:-
a. Trying To Divide By A Variable That Contains Zero
b. Trying To Open A File That Doesn't Exist
3. Logical Error:-Logical errors occur when there is something wrong in the logic of a
program.
Common examples are:-
a. Multiply When You Should Be Dividing
b. Adding When You Should Be Subtracting
c. Displaying a Wrong Message
Exception:
● An Exception is an unwanted event that interrupts the normal flow of the
program.
● Exceptions may or may not occur in the program.
● When an exception occurs program execution gets terminated. In this case we get
a system generated error message.
● When a Java interpreter finds the error, such as divide by zero, the interpreter
creates an exception object and throws it to inform that exception has occurred.
● The good thing about the exceptions is that they can be handled in Java.
● By handling the exceptions we can provide a meaningful message to the user
about the issue rather than a system generated message.
● There can be several reasons that can cause a program to throw an exception.
● For example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by user, divide by zero etc.
● Library exception classes Built-in exception classes
1. Checked Exceptions:
These are exceptions that the compiler forces the programmer to handle during compilation. If not handled,
the program won’t compile.
Common Examples:
IOException (from java.io library) – occurs during input/output operations.
SQLException (from java.sql library) – occurs during database interactions.
Handling: Must be managed using try-catch blocks or declared using the throws keyword in the
method signature.
Example:
import java.io.*;
public class Example {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("file.txt"));
System.out.println(br.readLine());
}
}
2. Unchecked Exceptions:
These exceptions occur at runtime, and the compiler doesn’t require explicit handling. They usually result
from programming errors like logic mistakes or incorrect data.
Common Examples:
NullPointerException (from java.lang library) – occurs when accessing an object with a
null reference.
ArithmeticException (from java.lang library) – occurs during illegal arithmetic operations,
like division by zero.
Handling: Optional; can be handled with try-catch but often avoided through better code validation.
Example:
public class Example {
public static void main(String[] args) {
int num = 10 / 0; // Causes ArithmeticException
System.out.println(num);
}
}
Exception Handling:
● This message is not user friendly so a user will not be able to understand.
● So by using the Exception handling mechanism, we handle an Exception and then
print a user friendly warning message to the user
● The basic idea of exception handling mechanism is to find the exception, Throws
the exception, Catch the exception and handle the exception.
● There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
Suppose there are 6 statements in your program and there occurs an exception
at statement 4, rest of the code will not be executed i.e. statement 5 to 6 will not
run. If we perform exception handling, the rest of the statement will be executed.
That is why we use exception handling in java.
1. try – The statements which cause the exception are given in the try block. The
try block contains a set of statements where an exception can occur. If an
exception occurs then an exception object is created and it is thrown. Syntax of
try block is given below:
While writing a program, if you think that certain statements in a program can
throw an exception, enclosed them in try block and handles that exception
2. catch – The statements which handle the exception are given in the catch block.
try
{ //statements that may cause an exception
}
This block catches the exception which is generated by the try block and handles
it. This block must write after the try block. A single try block can have several
catch blocks. When an exception occurs in a try block, the corresponding catch
block that handles that particular exception executes. Syntax of catch block:
3. throw – System generated exceptions are automatically thrown by the Java
runtime system. To manually throw an exception, the ‘throw’ keyword is used.
The throw keyword in Java is used to explicitly throw an exception from a method
try {
//statements that may cause an exception
}
catch
{// Statements which handles the exception
or any block of code.
}
throw ExceptionObject;
4. throws - throws is a keyword in Java which is used to indicate that this method
might throw one of the listed type exceptions. Below is the general form of a
method which includes a throws clause:
returntype method_name(parameters) throws
exception_list {
//method body
}
5. finally – finally is a keyword in Java. Finally, the block is always executed
whether an exception is handled or not. We can write the final block after the try
block or catch block. Finally, the block is optional.
try
{
//statements that may cause an exception
} catch
{
// Statements which handles the exception
} finally
{
//Statements to be executed
}
■ Example:
class ExceptionDemo
{
public static void main(String args[])
{
intx,y,a=10,b=5,c=5;
try
{
System.out.println("try block execution begin");
x=a/(b-c);
System.out.println("try block execution end");
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero error is occurred");
}
finally
{
System.out.println("Statements always executed");
}
y=a/(b+c);
System.out.println("Y="+y);
}
}
● Output
try block execution begin
Divide by zero error is occurred
Statements always executed
Y=1
■ A single try block can have several catch blocks. When an exception occurs in the try
block, then the corresponding catch block which handles that particular exception is
executed.
■ Below syntax is used to write the multiple catch block:
■ Example:
class ExceptionDemo
{
public static void main(String args[])
{
int x,y,a=10,b=5,c=5;
try
{
System.out.println("try block execution begin");
x=a/(b-c);
System.out.println("try block execution end");
}
catch(NullPointerException e)
{
System.out.println("NullPointer exception is occurred");
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic exception is occurred");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException is occurred");
}
y=a/(b+c);
System.out.println("Y="+y);
}
}
■ Output
try block execution begin
Arithmetic exception is occurred
Y=1
● throw keyword in Java:
■ System generated exceptions are automatically thrown by the Java runtime system.
To manually throw an exception, the ‘throw’ keyword is used.
■ The throw keyword in Java is used to explicitly throw an exception from a method
or any block of code.
■ Syntax of throw keyword is given below
throw ExceptionObject;
■ Example:
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException by
using throw keyword otherwise print a message ‘You are eligible for voting’.
Output
class ThrowDemo
{ void validate(int age)
{
if(age<18)
{
throw new ArithmeticException("Not valid Age
for voting");
}
else
{
System.out.println("You are eligible for
voting");
}
}
public static void main(String args[])
{
ThrowDemo d1=new
ThrowDemo(); d1.validate(16);
}
}
Exception in thread "main" java.lang.ArithmeticException: Not valid Age
for voting at ThrowDemo.validate(Testtrycatch1.java:8) at
ThrowDemo.main(Testtrycatch1.java:18)
■ throws is a keyword in Java which is used to indicate that this method might throw
one of the listed type exceptions.
■ Below is the general form of a method which includes a throws clause:
returntype method_name(parameters) throws exception_list
{
//method body
}
■ The throws do the same thing that try-catch does but there are some cases where you
would prefer throws instead of try-catch. For example: Let’s say we have a method
myMethod() that has statements that can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch as shown below:
void myMethod()
{
try
{
// Statements that might throw an exception
}
catch (ArithmeticException e)
{
// Exception handling statements
}
catch (NullPointerException e)
{
// Exception handling statements
}
}
■ But suppose you have several such methods that can cause exceptions, in that case it
would be difficult to write these try-catch for each method. The code will become
unnecessarily long and will be less-readable.
■ One way to overcome this problem is by using throws keyword: declare the
exceptions in the method using throws and handle the exceptions where you are
calling this method by using trycatch.
void myMethod()throws ArithmeticException,
NullPointerException {
// Statements that might throw an exception }
Example
class ThrowsDemo
{
void myMethod(int num)throws ArithmeticException, NullPointerException
{
if(num==1)
throw new ArithmeticException("ArithmeticException Occurred");
else
throw new NullPointerException("NullPointerException Occurred");
}
public static void main(String args[])
{
try
{
ThrowsDemo obj=new ThrowsDemo();
obj.myMethod(1);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
java.lang.ArithmeticException: ArithmeticException Occurred
Multithreading Multiprocessing
3) Threads share the same address space Each process allocates separate memory space
4) Cost of communication between the Cost of communication between the process is high
thread is low
8) It saves processor time and memory. It does not save processor time and memory.
Life Cycle of a Thread
• A thread goes through various stages in its life cycle. The life cycle of the thread in
java is controlled by JVM.
• The following diagram shows the complete life cycle of a thread.
1) Newborn state:
• When a thread object is created, the thread is born then called as thread is in
Newborn state.
• A new thread begins its life cycle in this state.
• When thread is in Newborn state then you can pass to the Running state by
invoking start() method or kill it by using stop() method.
2) Runnable state:
• The thread is in a runnable state after invocation of the start() method.
• The Runnable state of thread means that the thread is ready for the execution
and waiting for the availability of the processor.
• The threads which are ready for the execution are managed in the queue.
• The same priority threads are processed on the basis of First-come- First-
Serve.
3) Running state:
• The Running state means that the processor has given it’s time to thread for
their execution When thread is executing, its state is changed to Running.
• A thread can change state to Runnable, Dead or Blocked from running state
depending on time slicing, thread completion of run() method or waiting for
some resources.
4) Blocked state:
5) Dead state:
• The thread will move to the dead state after completion of its execution. It
means thread is in terminated or dead state when its run() method exits.
• Also Thread can be explicitly moved to the dead state by invoking stop()
method.
• Thread()
• Thread(String name) Thread(Runnable r)
• Thread(Runnable r, String name)
Following steps are required to create the thread inJava by using Thread class:
I. Declare the class by extending the Thread class.
t1.start();
Example:
//*****************************************************************************
************ class ThreadX extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(“From ThreadX:i=”+i);
}
}
}
//*****************************************************************************
*********** class ThreadY extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(“From ThreadY:j=”+j);
}
}
}
//*****************************************************************************
************ class ThreadDemo
{
public static void main(String args[])
{
ThreadX t1=new
ThreadX(); ThreadY
t2=new ThreadY();
t1.start(); t2.start();
}
}
t1.start();
Example:
//******************************************************************************
*********** class RunnableX implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(“From RunnableX:i=”+i);
}
}
}
//******************************************************************************
********** class RunnableY implements Runnable
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(“From RunnableY:j=”+j);
}
}
}
//******************************************************************************
*********** class RunnableDemo
{
public static void main(String args[])
{
RunnableX r1=new
RunnableX(); RunnableY
r2=new RunnableY();
Thread t1=new
Thread(r1); Thread
t2=new Thread(r2);
t1.start(); t2.start();
}
}
Important points between Thread Class vs. Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class
because Java doesn’t support multiple inheritance. But, if we implement the
Runnable interface, our class can extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class
because it provides some inbuilt methods like yield(), interrupt() etc. that are
not available in Runnable interface.
Thread priority:
ThreadName.setPriority(int number);
Where, number is an integer value which is between 1 to 10.
NORM_PRIORITY
MAX_PRIORITY
Example:
//*****************************************************************************************
class ThreadX extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(“From ThreadX:i=”+i);
}
}
}
//****************************************************************************************
class ThreadY extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println(“From ThreadY:j=”+j);
}
}
}
//****************************************************************************************
class ThreadZ extends Thread
{
public void run()
{
for(int K=1;K<=5;K++)
{
System.out.println(“From ThreadZ:K=”+K);
}
}
}
//*****************************************************************************************
class ThreadDemo
{
public static void main(String args[])
{
ThreadX t1=new
ThreadX(); ThreadY t2=new
ThreadY(); ThreadZ t2=new
ThreadZ();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start(); t2.start(); t3.start();
}
}