Java Unit 2
Java Unit 2
By Neha Gulati
OVERVIEW
Exception Handling : Java Library :
String handling (only main
Exception Class
functions)
Built in checked and unchecked
String Buffer class
exceptions
Elementary concepts of
User defined exceptions
Input/Output :byte and character
Use of try, catch, throw, throws, finally streams
Multi threaded programming: System.in and Sysem.out
Print and println
Overview
Comparison with multiprocessing Reading from a file and writing in a
file.
Thread class and runnable interface
Life cycle
Creation of single and multiple threads
Overview of Synchronization
EXCEPTION HANDLING IN JAVA
INTRODUCTION
There are two types of error available in java:
Compile time errors
Runtime errors
Compile time errors: all syntax error will be detected and displayed
by java compiler and therefore these errors are know as compile
time errors. Whenever the complier displays an error , it will not
create the .class file. It is therefore necessary that we have to fix the
errors before we can successfully compile and run the program.
Java exception handling is managed via five keywords: try, catch, throw,
throws, and finally.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ... finally {
// block of code to be executed before try block ends
}
ADVANTAGE OF EXCEPTION HANDLING
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
that is why we use exception handling.
Let's take a scenario:
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will
not be executed. If we perform exception handling, the rest of the statement will
be executed. That is why we use exception handling in Java.
HIERARCHY OF JAVA EXCEPTION CLASSES
The java.lang.Throwable class is the root class of Java Exception
hierarchy which is inherited by two subclasses: Exception and Error.
A hierarchy of Java Exception classes are given below:
TYPES OF JAVA EXCEPTIONS
There are mainly two types of exceptions: checked and unchecked.
Here, an error is considered as the unchecked exception. According
to Oracle, there are three types of exceptions:
Checked Exception
Unchecked Exception
Error
DIFFERENCE BETWEEN CHECKED AND UNCHECKED
EXCEPTIONS
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.
Unchecked Exception
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application
is maintained i.e. rest of the code is executed.
JAVA CATCH MULTIPLE EXCEPTIONS
Java Multi catch block
If you have to perform different tasks at the occurrence of different
Exceptions, use java multi catch block.
Let's see a simple example of java multi-catch block.
CONTD…
Rule: At a time only one Exception is occured and at a time only
one catch block is executed.
Rule: All catch blocks must be ordered from most specific to most
general i.e. catch for ArithmeticException must come before catch
for Exception
JAVA NESTED TRY BLOCK
The try block within a try block is known as nested try block in java.
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error.
In such cases, exception handlers have to be nested.
JAVA NESTED TRY EXAMPLE
JAVA FINALLY BLOCK
Java finally block is a block that is used to execute important code such
as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
CONTD…
Java throw example
What is a thread?
Threads are sometimes called lightweight processes. Both processes
and threads provide an execution environment, but creating a new
thread requires fewer resources than creating a new process.
Threads exist within a process — every process has at least one.
Threads share the process's resources, including memory and open
files. This makes for efficient, but potentially problematic,
communication.
CONTD…
A thread is similar to a program that has a single flow of control. it has
beginning a body and end. it is called single threaded programs.
Java supports for multithreaded programs.
One main and many other thread. Main thread is designed to create and start
other threads. Once initiated by main thread , child threads run concurrently
and share the resources jointly.
The ability of language to support multithreads is referred to as concurrency.
Threads in java is available in java.lang package
Thread class:
Thread class provide constructors and methods to create and
perform operations on a thread. Thread class extends Object class
and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
COMMONLY USED METHODS OF THREAD CLASS:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of
milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently
executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
CONTD…
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended
thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or
user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been
interrupted.
public static boolean interrupted(): tests if the current thread has
been interrupted.
CONTD…
Runnable interface:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
Runnable interface have only one method named run().public void
run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created
thread. It performs following tasks:A new thread starts(with new
callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method
will run.
JAVA THREAD EXAMPLE BY EXTENDING THREAD CLASS
An application can subclass Thread, This subclass should override
the run method of class Thread. An instance of the subclass can then
be allocated and started.
Syntax:
class MyThread extends Thread
{
//Body of class
}
JAVA THREAD EXAMPLE BY IMPLEMENTING RUNNABLE
INTERFACE
Note: If you are not extending the Thread class,your class object would not be
treated as a thread object.
So you need to explicitly create Thread class object.
CONTD…
Which method is preferable and why?
The approach we are using will depend on what the class we are
creating requires. If it requires to extend another class, then we have
no choice but to implement the Runnable interface, since java
classes can not have two super classes.
CREATING MULTIPLE THREADS
Your
program can
spawn as
many threads
as it needs.
For example,
the following
program
creates three
child
threads:
CONTD…
Possible Output:
[Hi! I am a
[Hi! I am a
child thread]
child thread]
[Hi! I am a
child thread]
Main thread exiting
Here, we have one main thread and 3 child threads working upon the
same object o of class A. Hence, their output comes out be
intermixed. Whenever multiple threads work upon a single object, it
leads to inconsistency in the state of that object. To solve this, we
have synchronization in java which will be discussed in the coming
sections.
ANOTHER APPROACH TO CREATE MULTIPLE THREADS
CONTD…
The output from this program is shown here:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
THE JOIN() METHOD
The join() method waits for a thread to die. In other words, it causes
the currently running threads to stop executing until the thread it
joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws
InterruptedException
EXAMPLE-
DAEMON THREAD IN JAVA
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.
There are many java daemon threads running automatically e.g. gc,
finalizer etc.
}
Here, object is a reference to the object being synchronized. A
synchronized block ensures that a call to a method that is a member
of object occurs only after the current thread has successfully
entered object’s monitor.
OUTPUT
DEADLOCK IN JAVA
Deadlock in java is a part of multithreading.
Deadlock can occur in a situation when a thread is waiting for an
object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.
EXAMPLE OF DEADLOCK
public class TestThread {
try { Thread.sleep(10); }
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
catch (InterruptedException e) {}
System.out.println("Thread 1:
public static void main(String args[]) { Waiting for lock 2...");
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
synchronized (Lock2) {
T2.start(); System.out.println("Thread 1:
} Holding lock 1 & 2...");
}
private static class ThreadDemo1 extends Thread {
public void run() {
}
synchronized (Lock1) { }
System.out.println("Thread 1: Holding lock }
1...");
private static class ThreadDemo2 extends
Thread {
CONTD…
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
NOTE- The program will hang forever because neither of the
threads in position to proceed and waiting for each other to release
the lock, so you can come out of the program by pressing CTRL+C.
SOLUTION OF DEADLOCK
public class TestThread {
try { Thread.sleep(10); }
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
catch (InterruptedException e) {}
System.out.println("Thread 1:
public static void main(String args[]) { Waiting for lock 2...");
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
synchronized (Lock2) {
T2.start(); System.out.println("Thread 1:
} Holding lock 1 & 2...");
}
private static class ThreadDemo1 extends Thread {
public void run() {
}
synchronized (Lock1) { }
System.out.println("Thread 1: Holding lock }
1...");
private static class ThreadDemo2 extends
Thread {
CONTD…
public void run() {
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
ANOTHER EXAMPLE OF DEADLOCK IN JAVA
OUTPUT
INTER-THREAD COMMUNICATION IN JAVA
Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which
a thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
wait()
notify()
notifyAll()
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.
wait( ) tells the calling thread to give up the monitor and go to sleep
until some other thread enters the same monitor and calls notify( ).
NOTIFY() METHOD
notify( ) wakes up the first thread that called wait( ) on the same
object.
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() METHOD
notifyAll( ) wakes up all the threads that called wait( ) on the same
object. The highest priority thread will run first.
Syntax:
public final void notifyAll()
UNDERSTANDING THE PROCESS OF INTER-THREAD
COMMUNICATION
50
Geek
Output:
Enter an integer
Enter a String
You have entered:- 50 and name as
LET US TRY THE SAME USING BUFFER CLASS AND SAME
INPUT
50
Geek
Output:
Enter an integer
Enter a String
you have entered:- 50 and name as Geek
CONTD…
In Scanner class if we call nextLine() method after any one of the
seven nextXXX() method then the nextLine() doesn’t not read
values from console and cursor will not come into console it will
skip that step. The nextXXX() methods are nextInt(), nextFloat(),
nextByte(), nextShort(), nextDouble(), nextLong(), next().
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a
reference to the pooled instance is returned. If the string doesn't
exist in the pool, a new string instance is created and placed in the
pool.
For example:
CONTD..
In such case, JVM will create a new string object in normal (non-
pool) heap memory, and the literal "Welcome" will be placed in the
string constant pool. The variable s will refer to the object in a heap
(non-pool).
JAVA STRING EXAMPLE
OUTPUT:
STRING CLASS
The String class is defined in the java.lang package and hence is
implicitly available to all the programs in Java.
The String class is declared as final, which means that it cannot be
subclassed.
Java implements “Strings” as objects of type string. A string is a
sequence of characters. Unlike most of the other languages, Java
treats a string as a single value rather than as an array of characters.
String is an immutable class in Java. An immutable class is simply a
class whose instances cannot be modified. All information in an
instance is initialized when the instance is created and the
information can not be modified.
You can still perform all type of string operations, the difference is
that each time you need an altered version of an existing string, a
new string object is created that contains the modifications. The
original string is left unchanged.
Whenever any operation is performed on a String object, a new
String object will be created while the original contents of the object
will remain unchanged.
However, at any time, a variable declared as a String reference can
be changed to point to some other String object.
WHY STRING OBJECTS ARE IMMUTABLE?
Requirement of String Pool: String pool (String intern pool) is a
special storage area in Method Area. When a string is created and if
the string already exists in the pool, the reference of the existing
string will be returned, instead of creating a new object and
returning its reference.The following code will create only one
string object in the heap.
String string1 = "abcd"; String string2 = "abcd"; If string is not
immutable, changing the string with one reference will lead to the
wrong value for the other references.
CONTD…
Caching Hashcode: The hashcode of string is frequently used in
Java. For example, in a HashMap. Being immutable guarantees that
hashcode will always the same, so that it can be cashed without
worrying the changes.That means, there is no need to calculate
hashcode every time it is used. This is more efficient.
Immutable objects are naturally thread-safe: Because immutable
objects can not be changed, they can be shared among multiple
threads freely. This eliminate the requirements of doing
synchronization.
CONSTRUCTOR IN STRING CLASS
-- String s = new String()
Calling a default constructor with no parameters as shown above
can create an empty string with no characters in it.
Char ars[] = {‘a’,’b’,’c’};
-- String s = new String (chars[]);
String initialized with characters, we need to pass in an array of char
to the constructor.
Char ars[] = {‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’i’};
-- String s = new String (chars[], int startindex,int numchars);
String object initialized with string, we need to pass string in it.
-- String s= new String (“This is new string”);
String object initialized with another string object, we need to pass
string in it.
-- String s1= new String (s);
-- String s = new String (byte ASCII[]);
-- String s = new String (byte ASCII[], int startindex, int numchars);
STRING FUNCTIONS:
String length:
The length of a string is the number of characters that it contains. To
obtain this value, call the length( ) method, shown here.
int length( )
The following fragment prints “3”, since there are three characters
in the string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
String StringBuffer
String class is immutable. StringBuffer class is mutable.