JAVA PROGRAAMING (314317)- NOTES (UNIT-3)
JAVA PROGRAAMING (314317)- NOTES (UNIT-3)
Errors are usually caused by serious problems that are outside the control of the
program, such as running out of memory or a system crash. Errors are represented by
the Error class and its subclasses. Some common examples of errors in Java include:
OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs out
of memory.
StackOverflowError: Thrown when the call stack overflows due to too many
method invocations.
NoClassDefFoundError: Thrown when a required class cannot be found.
Since errors are generally caused by problems that cannot be recovered from,
it’s usually not appropriate for a program to catch errors. Instead, the best course of
action is usually to log the error and exit the program.
Exceptions are used to handle errors that can be recovered from within the
program. Exceptions are represented by the Exception class and its subclasses. Some
common examples of exceptions in Java include:
NullPointerException: Thrown when a null reference is accessed.
IllegalArgumentException: Thrown when an illegal argument is passed to a
method.
IOException: Thrown when an I/O operation fails.
Exceptions are the conditions that occur at runtime and may cause the
termination of the program. But they are recoverable using try, catch and throw
keywords. Exceptions are divided into two categories:
Checked exceptions
Checked exceptions are also known as compile-time exceptions as these
exceptions are checked by the compiler during the compilation process to
confirm whether the exception is handled by the programmer or not. If
not, then the system displays a compilation error.
For
example, SQLException, IOException, InvocationTargetException, a
nd ClassNotFoundException.
Unchecked exceptions
The unchecked exceptions are those exceptions that occur during the
execution of the program. Hence they are also referred to as Runtime
exceptions. These exceptions are generally ignored during the
compilation process. They are not checked while compiling the program.
For example, programming bugs like logical errors, and using incorrect
APIs
Checked exceptions like IOException known to the compiler at compile time
while unchecked exceptions like ArrayIndexOutOfBoundException known to the
compiler at runtime. It is mostly caused by the program written by the programmer.
Errors Exceptions
The try block includes the code that might generate an exception.
The catch block includes the code that is executed when there occurs an
exception inside the try block.
class TryDemo {
public static void main(String[] args) { ArithmeticException
try { => / by zero
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => "
+e.getMessage());
}
}}
try...finally block
We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an exception
class Main {
public static void main(String[] args) { Finally block is always
try { executed
int divideByZero = 5 / 0; Exception in thread "main"
} java.lang.ArithmeticException:
finally { / by zero at
System.out.println("Finally block is always Main.main(Main.java:4)
executed");
}
}
}
try...catch...finally block
we can also use the finally block after the try...catch block.
import java.io.*;
class ListOfNumbers { Entering try statement
private int[] list = {5, 6, 8, 9, 2}; Exception => Index 5 out of
public void writeList() { bounds for length 5
PrintWriter out = null; Closing PrintWriter
try {
System.out.println("Entering try statement");
out = new PrintWriter(new
FileWriter("OutputFile.txt"));
for (int i = 0; i < 7; i++)
{ out.println("Value at: " + i + " = " +
list[i]); }
}
catch (Exception e)
{ System.out.println("Exception => " +
e.getMessage()); }
finally {
if (out != null)
{ System.out.println("Closing
PrintWriter");
out.close();
}
else
{ System.out.println("PrintWriter not
open"); }
} }}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
}catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); }
System.out.println("other statement");
//catch block of outer try block
import java.io.*;
class Main { java.io.FileNotFoundException:
public static void findFile() throws IOException { test.txt (No such file or
File newFile=new File("test.txt"); directory)
FileInputStream stream=new
FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e) {
System.out.println(e); }
}
}
Throwing multiple exceptions
import java.io.*;
class Main {
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
// code that may produce NullPointerException
………
// code that may produce IOException
………
// code that may produce InvalidClassException
………
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1)
{ System.out.println(e1.getMessage()); } catch(InvalidClassException e2)
{ System.out.println(e2.getMessage()); }
}
class Main {
public static void divideByZero() { Exception in thread "main"
throw new ArithmeticException("Trying to java.lang.ArithmeticException:
divide by 0"); Trying to divide by 0
} at
public static void main(String[] args) Main.divideByZero(Main.java:3)
{ divideByZero(); } at Main.main(Main.java:7)
} exit status 1
Throwing checked exception File not found
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
findFile();
System.out.println("Rest of code in try
block");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
5. BUILT-IN EXCEPTIONS
The Java programming language has several built-in exception class that
support exception handling. All the built-in exception classes in Java were defined a
package java.lang.
S.
No. Checked Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a
particular class and the specified class cannot be found in the
classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been
called to clone an object, but that the object's class does not
implement the Cloneable interface.
3 InstantiationException
It is thrown when an application tries to create an instance of a class
using the newInstance method in class Class , but the specified class
object cannot be instantiated because it is an interface or is an
abstract class.
4 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is
interrupted.
S.
No. Checked Exception Class with Description
5 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime
that it had at compile time, a NoSuchMethodException occurs during
reflection when we try to access a method that does not exist.
In order to execute the thread, the start() method is used. start() is called on
the object of the MyThread class. It automatically calls the run() method.
A thread is a path of execution in a program that enters any one of the following
five states during its life cycle. The five states are as follows:
1. New
When we create a thread object using Thread class, thread is born and is
known to be in Newborn state. That is, when a thread is born, it enters into
new state but the start() method has not been called yet on the instance.
Thread object exists but it cannot execute any statement because it is not
an execution of thread. Only start() method can be called on a new thread;
otherwise, an IllegalThreadStateException will be thrown.
2. Runnable
Runnable state means a thread is ready for execution. When the start()
method is called on a new thread, thread enters into a runnable state.
In runnable state, thread is ready for execution and is waiting for
availability of the processor (CPU time).
If all threads have equal priority, CPU allocates time slots for thread
execution on the basis of first-come, first-serve manner. The process of
allocating time to threads is known as time slicing.
3. Running
Running means Processor (CPU) has allocated time slot to thread for its
execution. When thread scheduler selects a thread from the runnable state
for execution, it goes into running state.
In running state, processor gives its time to the thread for execution and
executes its run method. This is the state where thread performs its actual
functions. A thread can come into running state only from runnable state.
4. Blocked (Non-runnable state)
A thread is considered to be in the blocked state when it is suspended,
sleeping, or waiting for some time in order to satisfy some condition.
5. Dead
A thread dies or moves into dead state automatically when its run() method
completes the execution of statements. That is, a thread is terminated or
dead when a thread comes out of run() method. A thread can also be dead
when the stop() method is called.
11. THREAD EXCEPTIONS
When we call a sleep() method in a Java program, it must be enclosed in
try block and followed by catch block.
This is because sleep() method throws an exception named
InterruptedException that should be caught. If we fail to catch this exception,
the program will not compile.
For example, a thread that is in a sleeping state cannot deal with the
resume() method because a sleeping thread cannot accept instructions. The
same thing is true for the suspend() method when it is used on a blocked
thread.
12. THREAD PRIORITY & METHODS
A thread's priority is an integer in the range 1 to 10.
The larger the integer, the higher the priority.
The thread scheduler uses this integer from each thread to determine which
one should be allowed to execute.
Minimum priority
Normal priority
Maximum priority
13. SYNCHRONIZATIONS
Synchronization in java is the capability to control the access of multiple threads
to any shared resource.
In the Multithreading concept, multiple threads try to access the shared
resources at a time to produce inconsistent results.
The synchronization is necessary for reliable communication between threads.
Synchronization helps in preventing thread interference.
Synchronization helps to prevent concurrency problems.
Synchronization is classified into two types
Process Synchronization
The process is nothing but a program under execution. It runs
independently isolated from another process. The resources like memory and
CPU time, etc. are allocated to the process by the operation System.
Thread Synchronization
Thread synchronization is two types, they are:
1. Mutual Exclusive:
A Mutex or Mutual Exclusive helps only one thread to access the
shared resources. It won’t allow the accessing of shared resources at a
time. It can be achieved in the following ways.
1. Synchronized Method
If we use the Synchronized keywords in any method then
that method is Synchronized Method.
It is used to lock an object for any shared resources.
The object gets the lock when the synchronized method is called.
The lock won’t be released until the thread completes its function.
CLASS POWER{
THREAD.SLEEP(500);
}CATCH(EXCEPTION E){SYSTEM.OUT.PRINTLN(E); }
}
}
}
CLASS THREAD1 EXTENDS THREAD{
POWER P;
POWER P;
THREAD2(POWER P) { THIS.P=P; }
PUBLIC VOID RUN() { P.PRINTPOWER(8); }
}
PUBLIC CLASS SYNCHRONIZATION_EXAMPLE2 {
PUBLIC STATIC VOID MAIN(STRING ARGS[]){
P1.START();
P2.START();
}
}
2. Synchronized block
Suppose you don’t want to synchronize the entire method, you want to
synchronize few lines of code in the method, then a synchronized block helps to
synchronize those few lines of code. It will take the object as a parameter. It
will work the same as Synchronized Method. In the case of synchronized
method lock accessed is on the method but in the case of synchronized block
lock accessed is on the object.
CLASS POWER{
VOID PRINTPOWER(INT N){
SYNCHRONIZED(THIS){
INT TEMP = 1;
FOR(INT I=1;I<=5;I++){
}CATCH(EXCEPTION E){SYSTEM.OUT.PRINTLN(E);}
}
}
}
} CLASS THREAD1 EXTENDS THREAD{
POWER P;
THREAD1(POWER P){ THIS.P=P; }
PUBLIC VOID RUN(){ P.PRINTPOWER(5); }
P2.START();
}
}
Static Synchronization
In java, every object has a single lock (monitor) associated with it. The
thread which is entering into synchronized method or synchronized block will get
that lock, all other threads which are remaining to use the shared resources
have to wait for the completion of the first thread and release of the lock.
Suppose in the case of where we have more than one object, in this case,
two separate threads will acquire the locks and enter into a synchronized block
or synchronized method with a separate lock for each object at the same time.
To avoid this, we will use static synchronization.
In this, we will place synchronized keywords before the static method. In
static synchronization, lock access is on the class not on object and Method.
15. DEADLOCK
Deadlock in java is a programming situation where two or more threads
are blocked forever. Java deadlock situation arises with at least two threads and
two or more resources.
Deadlock describes a situation where two or more threads are blocked
forever, waiting for each other. Deadlock occurs when multiple threads need the
same locks but obtain them in different order.
A Java multithreaded program may suffer from the deadlock condition
because the synchronized keyword causes the executing thread to block while
waiting for the lock, or monitor, associated with the specified object.
public class TestThread
{
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();