You are on page 1of 208

UNIT-II

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.

Run time errors/Exceptions: sometimes a program may compile


successfully creating a .class file but may not run properly. We call
it exception. an exception is a condition that is caused by run time
error in the program. When a java interpreter encounters an error
such as dividing by zero, it creates an exception object and throw it..
CONTD…
 The term exception denotes an exceptional event. It can be defined
as an abnormal event that occurs during program execution and
disrupts the normal flow of instructions.
 Error handling becomes a necessity when you develop an
application the need to take care of unexpected situations. The
unexpected situations that may occur program execution are:
- Running out of memory
- Resources allocation errors.
- Inability in network connectivity
- Problems in network connectivity
 “The Java programming language uses exceptions to handle errors
and other exceptional events. “
WHAT IS EXCEPTION HANDLING?
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

 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

 Checked Exception : The classes which directly inherit Throwable


class except RuntimeException and Error are known as checked
exceptions e.g. IOException, SQLException etc. Checked
exceptions are checked at compile-time.
 Unchecked Exception : The classes which inherit
RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time, but they are checked at runtime.
 Error : Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
JAVA EXCEPTION KEYWORDS
 There are 5 keywords which are used in handling exceptions in Java.

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.

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 important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't


throw an exception. It specifies that there may occur an exception
in the method. It is always used with method signature.
JAVA EXCEPTION HANDLING EXAMPLE

Unchecked Exception

In the above example, 100/0 raises an ArithmeticException which is handled


by a try-catch block.
COMMON SCENARIOS OF JAVA EXCEPTIONS
 There are given some scenarios where unchecked exceptions may
occur. They are as follows:
 A scenario where ArithmeticException occurs
 If we divide any number by zero, there occurs an ArithmeticException.

 A scenario where NullPointerException occurs


 If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException
CONTD…
 A scenario where NumberFormatException occurs
 The wrong formatting of any value may occur
NumberFormatException. Suppose I have a string variable that has
characters, converting this variable into digit will occur
NumberFormatException.

 A scenario where ArrayIndexOutOfBoundsException occurs


 If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
JAVA TRY-CATCH
 Java try block
 Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
 Java try block must be followed by either catch or finally block.
CONTD…
 Java catch block
 Java catch block is used to handle the Exception. It must be used
after the try block only.
 You can use multiple catch block with a single try.
PROBLEM WITHOUT EXCEPTION HANDLING
 Let's try to understand the problem if we don't use try-catch block.

 As displayed in the above example, rest of the code is not executed


(in such case, rest of the code... statement is not printed).
 There can be 100 lines of code after exception. So all the code after
exception will not be executed.
SOLUTION BY EXCEPTION HANDLING
 Let's see the solution of above problem by java try-catch block.

 Now, as displayed in the above example, rest of the code is executed


i.e. rest of the code... statement is printed.
INTERNAL WORKING OF JAVA TRY-CATCH BLOCK

 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.

Note: If you don't handle


exception, before terminating the
program, JVM executes finally
block(if any).
WHY USE JAVA FINALLY?
 Finally block in java can be used to put "cleanup" code such as
closing a file, closing connection etc.

 Usage of Java finally


 Let's see the different cases where java finally block can be used:
 Case 1 - where exception doesn't occur
 Case 2 - where exception occurs and not handled
 Case 3 - where exception occurs and handled
CASE 1
 Let's see the java finally example where exception doesn't occur
CASE 2
 When an exception occur but not handled by the catch block
CASE 3
 Let's see the java finally example where exception occurs and
handled
POINTS TO REMEMBER:
 Rule: For each try block there can be zero or more catch blocks, but
only one finally block.
 Note: The finally block will not be executed if program exits(either
by calling System.exit() or by causing a fatal error that causes the
process to abort).
JAVA THROW EXCEPTION
 Java throw keyword
 The Java throw keyword is used to explicitly throw an exception.
 We can throw either checked or uncheked exception in java by
throw keyword. The throw keyword is mainly used to throw custom
exception. We will see custom exceptions later.
 The syntax of java throw keyword is given below.

 Let's see the example of throw IOException.


JAVA THROW KEYWORD 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
otherwise print a message welcome to vote.
JAVA EXCEPTION PROPAGATION
 An exception is first thrown from the top of the stack and if it is not caught, it
drops down the call stack to the previous method.
 If not caught there, the exception again drops down to the previous method, and
so on until they are caught or until they reach the very bottom of the call stack.
 This is called exception propagation. Rule: By default Unchecked
Exceptions are forwarded in
calling chain (propagated).
CONTD…

 In the above example exception occurs in m() method where it is not


handled,so it is propagated to previous n() method where it is not
handled, again it is propagated to p() method where exception is
handled.
 Exception can be handled in any method in call stack either in
main() method,p() method,n() method or m() method.
CONTD…
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 normal flow 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
performing check up before the code being used.
CONTD…
 Which exception should be declared?
 Checked exception only, because:
 unchecked Exception: under your control so correct your code.
 error: beyond your control e.g. you are unable to do anything if there
occurs VirtualMachineError or StackOverflowError.

 Advantages of Java throws keyword:


 Now Checked Exception can be propagated (forwarded in call stack).
 It provides information to the caller of the method about the exception.
JAVA THROWS EXAMPLE
CONTD…
 There are two cases:
 Case1:You caught the exception i.e. handle the exception using
try/catch.
 Case2:You declare the exception i.e. specifying throws with the
method.
CASE1: YOU HANDLE THE EXCEPTION
 In case you handle the exception, the code will be executed fine
whether exception occurs during the program or not.
CASE2: YOU DECLARE THE EXCEPTION
 A) In case you declare the exception, if exception does not occur, the code
will be executed fine.
 B) In case you declare the exception if exception occurs, an exception will
be thrown at runtime because throws does not handle the exception.
 A)Program if exception does not occur
CONTD…
 B)Program if exception occurs
DIFFERENCE BETWEEN THROW AND THROWS IN JAVA
 There are many differences between throw and throws keywords.
 A list of differences between throw and throws are given below:

throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.

Checked exception cannot be propagated Checked exception can be propagated


using throw only. with throws.

Throw is followed by an instance. Throws is followed by class.

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

 Java throws example

 Java throw and throws example


DIFFERENCE BETWEEN FINAL, FINALLY AND FINALIZE
 There are many differences between final, finally and finalize.
 A list of differences between final, finally and finalize are given
below:

final finally finalize


Final is used to apply Finally is used to place Finalize is used to
restrictions on class, important code, it will be perform clean up
method and variable. executed whether processing just before
Final class can't be exception is handled or object is garbage
inherited, final method not. collected.
can't be overridden and
final variable value can't
be changed.

Final is a keyword. Finally is a block. Finalize is a method.


CONTD…
 Java final example

 Java finally example


CONTD…
 Java finalize example
EXCEPTIONHANDLING WITH METHODOVERRIDING IN JAVA

 The Rules are as follows:


 If the superclass method does not declare an exception
 If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it can
declare unchecked exception.
 If the superclass method declares an exception
 If the superclass method declares an exception, subclass overridden
method can declare same, subclass exception or no exception but cannot
declare parent exception.
IF THE SUPERCLASS METHOD DOES NOT DECLARE AN
EXCEPTION

 Rule: If the superclass method does not declare an exception,


subclass overridden method cannot declare the checked exception.
CONTD…
 Rule: If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked exception
but can declare unchecked exception.
IF THE SUPERCLASS METHOD DECLARES AN EXCEPTION
 Rule: If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare parent
exception.
 Example in case subclass overridden method declares parent exception
CONTD…
 Example in case subclass overridden method declares same
exception
CONTD…
 Example in case subclass overridden method declares subclass
exception
CONTD…
 Example in case subclass overridden method declares no
exception
JAVA CUSTOM EXCEPTION
 If you are creating your own
Exception that is known as
custom exception or user-
defined exception. Java
custom exceptions are used to
customize the exception
according to user need.
 By the help of custom
exception, you can have your
own exception and message.
 Let's see a simple example of
java custom exception.
MULTITHREADED PROGRAMMING
 What is a process?
 A process is program in execution.
 A process has a self-contained execution environment. A process
generally has a complete, private set of basic run-time resources; in
particular, each process has its own memory space.
 Two or more processes running concurrently in a computer is called
multitasking.

 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

Single threaded and multithreaded program.


 As shown in the above figure, a thread is executed inside the
process. There is context-switching between the threads. There can
be multiple processes inside the OS, and one process can have
multiple threads.
MULTITASKING
 Multitasking is a process of executing multiple tasks simultaneously.
We use multitasking to utilize the CPU. Multitasking can be
achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)

 Process-based Multitasking (Multiprocessing)


 Each process has an address in memory. In other words, each process
allocates a separate memory area.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving
and loading registers, memory maps, updating lists, etc.
 Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.
CONTD…
 It is important to remember that threads running in parallel does not
really mean that they actually run at same time.
 Java interpreter handles the switching of control between the threads
in such a way that it appears they are running concurrently.

 The advantages of threads over processes are as follows:


 Can be created faster
 Requires less overheads
 Inter-process communication is faster
 Context switching is faster
 Maximum use of CPU time
REAL WORLD EXAMPLES-
 A real world example:
 MS word - You are typing a paragraph on MS word. But in
background one more thread running and checking your spelling
mistakes.
 Lets take an example of bank ,let’s suppose we have an online
banking system, where people can log in and access their account
information. Whenever someone logs in to their account online,
they receive a separate and unique thread so that different bank
account holders can access the central system simultaneously.
 Online bus ticket booking : here many users trying to book available
ticket at same time (ex : tatkal booking ) , here application needs to
handle different threads (diff users request to server ) , if tickets sold
out/not available then rest users will get correct response as not
available to book .
MAIN THREAD IN JAVA
 When a java program starts up , one thread begins running
immediately. This is usually called the main thread of your program,
because it is the one that is executed when your program begins. The
main thread is important for two reasons:
 It is thread from which other “child” threads will be initiate.
 Often , it must be the last thread to finish execution it performs
various shutdown actions.
 Main thread is created automatically when program starts, it can be
controlled through Thread object.
 For that a reference to the main thread is required, which can be
obtained by using currentThread() method of thread class.
 It’s a public static member of thread class: general signature::
public static Thread currentThread()
 This method returns the reference to the thread in which it is called.
 When value of thread object is printed it displays three arguments i.e.,
Name of thread, priority, thread group to which this thread belongs to.
LIFE CYCLE OF A THREAD (THREAD STATES)
 A thread can be in one of the five states. According to sun, there is
only 4 states in thread life cycle in java new, runnable, non-
runnable and terminated. There is no running state.
 But for better understanding the threads, we are explaining it in the
5 states.
 The life cycle of the thread in java is controlled by JVM.
 The java thread states are as follows:
 New
 Runnable
 Running
 Non-Runnable (Blocked)
 Terminated
CONTD…
CONTD…
 Newborn State: When we create a thread object , the thread is born
and said to be in newborn state. The thread is not yet scheduled for
running. At this stage one can do only two things:
 Scheduled it for running start() method.
 Kill it using stop() method.
 If u will try and use any other method at this stage, an exception will be
thrown
CONTD…
 Runnable State: The runnable state means that the thread is ready for
execution of instructions and is waiting for the availability of the processor.
 That is , thread has joined the queue of threads that are waiting for
execution. The run() method contains the set of instructions .
 This method is called automatically after start() method. If we want a
thread to relinquish control to another thread of equal priority before it turn
come, we can do so by using the yield() method.
CONTD…
 Running state: Running means processor has given its time to thread for
its execution. The thread runs until it leaves control on its own or it is
preempted by a higher priority thread. It can leave control in following
situations:
 It has been suspend using suspend() method. A suspend thread can be
resume by using resume() method. It is useful when we want to suspend a
thread for a while but not kill it.
CONTD…
 It has been made to sleep. We can put a thread to sleep for a specified
time period using the method sleep(time) where time is in milliseconds.
Means thread is not in the queue during this period. the thread re-enters
runnable state as soon as this time period is elapsed.
CONTD…
 It has been told to wait until some event occurs. This is done by
using wait() method. The thread can be run again using the notify()
method.
CONTD…
 Blocked state: A thread is said to be blocked when it is prevented
from entering into the runnable state and subsequently the running
state. This happens when a thread is suspended (suspend()),
sleeping (sleep() )or waiting(wait()) in order to satisfy certain
requirements. A blocked thread is considered “not runnable ” but
not dead and therefore fully qualified to run again. While thread is
in the blocked state the scheduler will simply skip over and not give
any CPU time. Until a thread re-enters the runnable state it will not
perform any operations. When a thread is blocked by i/o operations
it enters the not runnable state.
 Dead state: Every thread has a life cycle. A running thread ends its
life when it has completed executing its run() method. It is a natural
death. However, we can kill it by sending the stop message to it at
any state thus causing a premature death to it. A thread can be killed
in any stage: block, running, runnable, new born stage. There is a
destroy() method that should never if we can avoid it, since it is
drastic and does not release objects locks.
HOW TO CREATE THREAD?
 There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.

 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

 Define a class that implements Runnable interface. The Runnable


interface has only one method run(), that is to be defined in the
method with the code to be executed by the thread.
 An instance of the class can then be allocated, passed as an
argument when creating Thread, and started.
 The Runnable interface defines a single method, run, meant to
contain the code executed in the thread.
 The Runnable object is passed to the Thread constructor.
 After u create a class that implements Runnable, you will instantiate
an object of type Thread from within that class
 After the new thread is created, it will not start running until you can
call its start() method, which is declared with Thread.
CONTD…

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.

 The sole purpose of the daemon thread is that it provides services to


user thread for background supporting task.
 If there is no user thread, why should JVM keep running this thread.
That is why JVM terminates the daemon thread if there is no user
thread.
IMPLEMENTATION OF THREAD IN JAVA
 Java multithreading is built upon Thread class, its methods an its
interface Runnable.
 Thread encapsulates a thread of execution.

 To create a new Thread, program will extend either Thread class


or implement Runnable interface.
 When a program starts one thread begins immediately. This is
main thread of your program.
 It is the thread from which other child threads are spawned.

 It must be the last one to finish execution because it performs


various shutdown actions.
 It is controlled by Thread object.
VARIABLE ACCESS THROUGH THREADS
Java supports three types of variables:
- Local variable: each thread is separate, so that local variables

in the method that the thread is executing are separate for


different threads. They are completely private, there is no way
for one thread to access the local variables of another thread.
- Instance variable: objects and instance variable on the other

hand can be shared between threads, it is like sharing data


objects between processes in OS, in fact sharing data between
threads is easier then sharing between processes.
- Static variable: they are automatically shared between all

threads in a java program.


THREAD PRIORITIES
 Thread priorities are used by the thread scheduler to decide when
each thread should be allowed to run. In theory, higher-priority
threads get more CPU time than lower priority threads. A higher-
priority thread can also preempt a lower-priority one.
 For instance, when a lower-priority thread is running and a higher-
priority thread resumes (from sleeping or waiting on I/O, for
example), it will preempt the lower-priority thread To set a thread’s
priority, use the setPriority( ) method, which is a member of
Thread. This is its general form:
final void setPriority(int level)
 Here, level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and
MAX_PRIORITY. Currently, these values are 1 and 10,
respectively. To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities are
defined as final variables within Thread.
CONTD…
 You can obtain the current priority setting by calling the
getPriority( ) method of Thread, shown here:

final int getPriority( )

 The following example (next slide) demonstrates two threads at


different priorities, which do not run on a preemptive platform in
the same way as they run on a nonpreemptive platform.
 One thread is set two levels above the normal priority, as defined by
Thread.NORM_PRIORITY, and the other is set to two levels
below it.
 The threads are started and allowed to run for ten seconds. Each
thread executes a loop, counting the number of iterations. After ten
seconds, the main thread stops both threads. The number of times
that each thread made it through the loop is then displayed.
EXAMPLE OF PRIORITY OF A THREAD:
CONTD…
SYNCHRONIZATION
 When two or more thread need access to a shared resource , they need
some way to ensure that the resource will be used by only one thread at
a time. The process by which this is achieved is called synchronization.
 Key to synchronization is the concept of the monitor. A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one
thread can own a monitor at a given time. When a thread accquires a
lock, it is said to have enter the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the
monitor. These other threads are said to be waiting for monitor. A thread
that owns a monitor can re-enter the same monitor if it desires.
 Most of the languages do not , themselves support synchronization,
instead to synchronize threads your program need to utilize operating
system primitives
 Java supports synchronization through language elements.
 Java supports synchronization through two ways:
 Synchronized method
 Synchronized statement
UNDERSTANDING THE PROBLEM WITHOUT SYNCHRONIZATION

In this example, there is no


synchronization, so output is
inconsistent. Let's see the example:
OUTPUT
USING SYNCHRONIZED METHOD:
 Synchronized is easy in java because all the objects have their own
implicit monitor associated with them.
 To enter an objects monitor just call a method that has been
modified with the synchronized keyword.
 While a thread is inside a synchronized method, all other threads
that try to call it on the same instance have to wait.
 To exit monitor and relinquish control of the object to the next
waiting thread, the owner of the monitor simply returns from the
synchronized method.
 Synchronized keyword is used with a method or group of methods
when they manipulate the internal state of an object in a
multithreaded situation. Once a thread enters synchronized method
on an instance, no other thread enter any other synchronized method
on the same instance. Non-synchronized method on that instance
will be continue to be callable.
OUTPUT
USING SYNCHRONIZED STATEMENT/BLOCK
 Synchronized method is not useful in all the cases.
 Synchronized block can be used to perform synchronization on any
specific resource of the method.
 Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
 Use synchronized block.
Synchronized(object reference expression)
{

}
 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

The point to point explanation of the above diagram is as


follows:
1.Threads enter to acquire lock.
2.Lock is acquired by on thread.
3.Now thread goes to waiting state if you call wait() method
on the object. Otherwise it releases the lock and exits.
4.If you call notify() or notifyAll() method, thread moves to
the notified state (runnable state).
5.Now thread is available to acquire lock.
6.After completion of the task, thread releases the lock and
exits the monitor state of the object.
EXAMPLE OF INTER THREAD COMMUNICATION IN JAVA
OUTPUT
SUSPEND() AND RESUME()
 Suspend() method will suspend() the current or calling thread and
takes it in block state untill or unless resume() method is called for
same. This method is depricated in java, as it is inherently deadlock
prone. If target threads hold a lock on monitor protecting a critical
system resource when it is suspended, no thread can access this
resource untill the target thread is resumed. Since this state is not
interruptable so prone to deadlock.
 Resume() method will bring target thread back in Runnable state.
DIFFERENCE BETWEEN WAIT() AND SUSPEND()
 Unlike suspend() ,wait() releases all the lock before wait() state,
 Suspend() is called on thread and wait is called on object.

DIFFERENCE BETWEEN WAIT() AND SLEEP()


INTERRUPTING A THREAD:
 If any thread is in sleeping or waiting state (i.e. sleep() or wait() is
invoked), calling the interrupt() method on the thread, breaks out the
sleeping or waiting state throwing InterruptedException.
 If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt
the thread but sets the interrupt flag to true.
 The 3 methods provided by the Thread class for interrupting a
thread
 public void interrupt()
 public static boolean interrupted()
 public boolean isInterrupted()
CAN WE OVERRIDE START METHOD?
 start() method
 public void start()
It starts thread to begin execution, JVM calls run method of this
thread.
IllegalThreadStateException – if the thread was already started.
 We can override the start method in thread. But when we class
thread.start() method then overrided method will be called which
results into no execution of run method. Hence no job will be
performed.
 So, we do not have to override the start method.
 Note: We can call super class start method in overrided start
method to invoke run method.
JAVA LIBRARY
 Java I/O (Input and Output) is used to process the
input and produce the output.
 Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and output
operations.
 Streams
 Java programs perform I/O through streams. A stream is an
abstraction that either produces or consumes information.
 A stream is a sequence of data. In Java, a stream is composed of
bytes. It's called a stream because it is like a stream of water that
continues to flow.
 A stream is linked to a physical device by the Java I/O system. Java
2 defines two types of streams:
 Byte
 Character.
BYTE STREAMS
 Byte streams provide a convenient means for handling input and
output of bytes. Byte streams are used, for example, when reading
or writing binary data.
 At the top are two abstract classes: InputStream and OutputStream.
The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement.
 Two of the most important are read( ) and write( ), which,
respectively, read and write bytes of data.
CHARACTER STREAMS
 Character streams provide a convenient means for handling input
and output of characters. Character streams are defined by using two
class hierarchies. At the top are two abstract classes, Reader and
Writer.
 The abstract classes Reader and Writer define several key methods
that the other stream classes implement. Two of the most important
methods are read( ) and write( ), which read and write characters of
data, respectively.
PREDEFINED STREAMS
 All Java programs automatically import the java.lang package. This
package defines a class called System, which encapsulates several
aspects of the run-time environment.
 For example, using some of its methods, you can obtain the current
time and the settings of various properties associated with the system.
System also contains three predefined stream variables, in, out, and
err. These fields are declared as public and static within System.
 This means that they can be used by any other part of your program
and without reference to a specific System object. System.out refers
to the standard output stream. By default, this is the console.
 System.in refers to standard input, which is the keyboard by default.
System.err refers to the standard error stream, which also is the
console by default. However, these streams may be redirected to any
compatible I/O device. System.in is an object of type InputStream;
System.out and System.err are objects of type PrintStream.
 These are byte streams, even though they typically are used to read
and write characters from and to the console.
 In Java, 3 streams are created for us automatically. All these streams
are attached with the console.
 1) System.out: standard output stream
 2) System.in: standard input stream
 3) System.err: standard error stream
 Let's see the code to print output and an error message to the
console.

 Let's see the code to get input from console.


OUTPUTSTREAM HIERARCHY
INPUTSTREAM CLASS
JAVA FILEOUTPUTSTREAM CLASS
 Java FileOutputStream is an output stream used for writing data to
a file.
 If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented as well as
character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
CONTD…
JAVA FILEINPUTSTREAM CLASS
 Java FileInputStream class obtains input bytes from a file. It is used
for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.
 You can also read character-stream data. But, for reading streams of
characters, it is recommended to use FileReader class.
JAVA BUFFEREDOUTPUTSTREAM CLASS
 Java BufferedOutputStream class is used for buffering an output
stream. It internally uses buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the
performance fast.
 For adding the buffer in an OutputStream, use the
BufferedOutputStream class. Let's see the syntax for adding the
buffer in an OutputStream:

 OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));


CONTD…
JAVA BUFFEREDINPUTSTREAM CLASS
 Java BufferedInputStream class is used to read information
from stream. It internally uses buffer mechanism to make the
performance fast.
 The important points about BufferedInputStream are:
 When the bytes from the stream are skipped or read, the internal
buffer automatically refilled from the contained input stream, many
bytes at a time.
 When a BufferedInputStream is created, an internal buffer array is
created.
EXAMPLE-
JAVA CONSOLE CLASS
 The Java Console class is be used to get input from console. It
provides methods to read texts and passwords.
 If you read password using Console class, it will not be displayed to
the user.
 The java.io.Console class is attached with system console internally.
The Console class is introduced since 1.5.
 Let's see a simple example to read text from console.
 String text=System.console().readLine();
 System.out.println("Text is: "+text);
EXAMPLE-
JAVA WRITER
 It is an abstract class for writing to character streams. The methods
that a subclass must implement are write(char[], int, int), flush(),
and close().
 Most subclasses will override some of the methods defined here to
provide higher efficiency, functionality or both.
JAVA READER
 Java Reader is an abstract class for reading character streams. The
only methods that a subclass must implement are read(char[], int,
int) and close(). Most subclasses, however, will override some of the
methods to provide higher efficiency, additional functionality, or
both.
 Some of the
implementation class are BufferedReader, CharArrayReader, FilterR
eader, InputStreamReader, PipedReader, StringReader
JAVA FILEWRITER CLASS
 Java FileWriter class is used to write character-oriented data to
a file. It is character-oriented class which is used for file handling
in java.
 Unlike FileOutputStream class, you don't need to convert string into
byte array because it provides method to write string directly.
JAVA FILEREADER CLASS
 Java FileReader class is used to read data from the file. It returns
data in byte format like FileInputStream class.
 It is character-oriented class which is used for file handling in java.
output
JAVA BUFFEREDWRITER CLASS
 Java BufferedWriter class is used to provide buffering for Writer
instances. It makes the performance fast. It inherits Writer class.
 The buffering characters are used for providing the efficient writing
of single arrays, characters, and strings.
JAVA BUFFEREDREADER CLASS
 Java BufferedReader class is used to read the text from a character-
based input stream. It can be used to read data line by line by
readLine() method.
 It makes the performance fast. It inherits Reader class.
JAVA PRINTSTREAM CLASS
 The PrintStream class provides methods to write data to another
stream. The PrintStream class automatically flushes the data so there
is no need to call flush() method. Moreover, its methods don't throw
IOException.
DIFFERENCE BETWEEN SCANNER AND
BUFFERREADER CLASS IN JAVA
 java.util.Scanner class is a simple text scanner which can parse
primitive types and strings. It internally uses regular expressions to
read different types.
 Java.io.BufferedReader class reads text from a character-input
stream, buffering characters so as to provide for the efficient reading
of sequence of characters
 Following are differences between above two.
 Issue with Scanner when nextLine() is used after nextXXX()
TRY TO GUESS THE OUTPUT OF FOLLOWING CODE :

// Code using Scanner Class


import java.util.Scanner;
class Differ
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter an integer");
int a = scn.nextInt();
System.out.println("Enter a String");
String b = scn.nextLine();
System.out.printf("You have entered:- "
+ a + " " + "and name as " + b);
}
}
OUTPUT:
Input:

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

// Code using Buffer Class


import java.io.*;
class Differ
{
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer");
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
System.out.printf("You have entered:- " + a +
" and name as " + b);
}
}
Run on IDE
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().

 In BufferReader class there is no such type of problem. This


problem occurs only for Scanner class, due to nextXXX() methods
ignore newline character and nextLine() only reads newline
character. If we use one more call of nextLine() method between
nextXXX() and nextLine(), then this problem will not occur because
nextLine() will consume the newline character.
OTHER DIFFERENCES:
 BufferedReader is synchronous while Scanner is not.
 BufferedReader should be used if we are working with multiple
threads.
 BufferedReader has significantly larger buffer memory than
Scanner.
 The Scanner has a little buffer (1KB char buffer) as opposed to the
BufferedReader (8KB byte buffer), but it’s more than enough.
 BufferedReader is a bit faster as compared to scanner because
scanner does parsing of input data and BufferedReader simply reads
sequence of characters.
JAVA STRING
 In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For
example:
CHARSEQUENCE INTERFACE
 The CharSequence interface is used to represent the sequence of
characters. String, StringBuffer and StringBuilder classes implement
it.
 It means, we can create strings in java by using these three classes.

The Java String is immutable which


means it cannot be changed.
Whenever we change any string, a
new instance is created. For mutable
strings, you can use StringBuffer and
StringBuilder classes.
STRING HANDLING
 In Java a string is a sequence of characters. But, unlike many other
languages that implement strings as character arrays, Java
implements strings as objects of type String.
 Implementing strings as built-in objects allows Java to provide a
full complement of features that make string handling convenient.
 For example, Java has methods to compare two strings, search for a
substring, concatenate two strings, and change the case of letters
within a string.
 Also, String objects can be constructed a number of ways, making it
easy to obtain a string when needed.
 Somewhat unexpectedly, when you create a String object, you are
creating a string that cannot be changed.
 That is, once a String object has been created, you cannot change
the characters that comprise that string, 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.
CONTD…
 The original string is left unchanged. This approach is used because
fixed, immutable strings can be implemented more efficiently than
changeable ones.
 For those cases in which a modifiable string is desired, there is a
companion class to String called StringBuffer, whose objects
contain strings that can be modified after they are created.
 Both the String and StringBuffer classes are defined in java.lang.
Thus, they are available to all programs automatically. Both are
declared final, which means that neither of these classes may be
subclassed.
HOW TO CREATE A STRING OBJECT?
 There are two ways to create String object:
 By string literal
 By new keyword

 String Literal: Java String literal is created by using double quotes.


For Example:

 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 the example, only one


object will be created.
 Firstly, JVM will not find
any string object with the
value "Welcome" in string
constant pool, that is why
it will create a new object.
 After that it will find the
string with the value
"Welcome" in the pool, it
will not create a new
object but will return the
reference to the same
instance.
CONTD…
 By new keyword:

 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());

 In the above statement, s.length() could also be written as


“abc”.length(). It means one and the same thing.
CONTD…
 String concatenation:
 It concatenates two strings with the help of + operator
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
 This displays the string “He is 9 years old.”
CONTD…
 toString() : return "Dimensions are " + width + " by " +
// Override toString() for Box class. depth + " by " + height + ".";
class Box { }
double width; }
double height; class toStringDemo {
double depth; public static void main(String args[]) {
Box(double w, double h, double d) { Box b = new Box(10, 12, 14);
width = w; String s = "Box b: " + b; // concatenate Box
object
height = h;
System.out.println(b); // convert Box to
depth = d; string
} System.out.println(s);
public String toString() { }
}
The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0
As you can see, Box’s toString( ) method is automatically invoked when a Box object is
used in a concatenation expression or in a call to println( ).
CONTD…
 CharAt() :
 To extract a single character from a String, you can refer directly to
an individual character via the charAt( ) method. It has this general
form:
char charAt(int where)
 Here, where is the index of the character that you want to obtain.
The value of where must be nonnegative and specify a location
within the string. charAt( ) returns the
 character at the specified location. For example,
 char ch;
 ch = "abc".charAt(1);
 Above statement, assigns the value “b” to ch.
CONTD…
 equals() and equalsIgnoreCase():
 To compare two strings for equality, use equals( ). It has this
general form:
boolean equals(Object str)
 Here, str is the String object being compared with the invoking
String object. It returns true if the strings contain the same
characters in the same order, and false otherwise. The comparison is
case-sensitive. To perform a comparison that ignores case
differences, call equalsIgnoreCase( ).
 When it compares two strings, it considers A-Z to be the same as a-
z. It has this general form:
boolean equalsIgnoreCase(String str)
 Here, str is the String object being compared with the invoking
String object. It, too, returns true if the strings contain the same
characters in the same order, and false otherwise.
CONTD…
 Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):
 // Demonstrate equals() and equalsIgnoreCase().
 class EqualsDemo {
 public static void main(String args[]) {
 String s1 = "Hello";
 String s2 = "Hello";
 String s3 = "Good-bye";
 String s4 = "HELLO";
 System.out.println(s1 + " equals " + s2 + " -> " +
 s1.equals(s2));
 System.out.println(s1 + " equals " + s3 + " -> " +
 s1.equals(s3));
 System.out.println(s1 + " equals " + s4 + " -> " +
 s1.equals(s4));
 System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
 s1.equalsIgnoreCase(s4));
 }
 }
CONTD…
 The output from the program is shown here:
 Hello equals Hello -> true
 Hello equals Good-bye -> false
 Hello equals HELLO -> false
 Hello equalsIgnoreCase HELLO -> true
CONTD…
 equals verses = = :
 The equals( ) method compares the characters inside a String object.
The = = operator compares two object references to see whether they
refer to the same instance. The following program shows how two
different String objects can contain the same characters, but references
to these objects will not compare as equal:
 // equals() vs = =
 class EqualsNotEqualTo {
 public static void main(String args[]) {
 String s1 = "Hello";
 String s2 = new String(s1);
 System.out.println(s1 + " equals " + s2 + " -> " +
 s1.equals(s2));
 System.out.println(s1 + " = = " + s2 + " -> " + (s1 == s2));
 }
 }
CONTD…
 The variable s1 refers to the String instance created by “Hello”. The
object referred to by s2 is created with s1 as an initializer. Thus, the
contents of the two String objects are identical, but they are distinct
objects. This means that s1 and s2 do not refer to the same objects
and are, therefore, not ==, as is shown here by the
 output of the preceding example:
 Hello equals Hello -> true
 Hello == Hello -> false
CONTD…
 Searching strings:
 The String class provides two methods that allow you to search a
string for a specified character or substring:
 indexOf( ) Searches for the first occurrence of a character or substring.
 lastIndexOf( ) Searches for the last occurrence of a character or
substring.
 These two methods are overloaded in several different ways. In all
cases, the methods return the index at which the character or
substring was found, or –1 on failure.
 To search for the first occurrence of a character, use
int indexOf(int ch)
 To search for the last occurrence of a character, use
int lastIndexOf(int ch)
CONTD…
 Here, ch is the character being sought.
 To search for the first or last occurrence of a substring, use
 int indexOf(String str)
 int lastIndexOf(String str)
 Here, str specifies the substring.
 You can specify a starting point for the search using these forms:
 int indexOf(int ch, int startIndex)
 int lastIndexOf(int ch, int startIndex)
 int indexOf(String str, int startIndex)
 int lastIndexOf(String str, int startIndex)
 Here, startIndex specifies the index at which point the search begins.
For indexOf( ), the search runs from startIndex to the end of the string.
For lastIndexOf( ), the search runs from startIndex to zero.
 The following example shows how to use the various index methods to
search
 inside of Strings:
CONTD…
 class indexOfDemo {  System.out.println("indexOf(t, 10) = " +
 public static void main(String args[])  s.indexOf('t', 10));
{  System.out.println("lastIndexOf(t, 60) = "
+
 String s = "Now is the time for all
good men " +
 s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = "
 "to come to the aid of their country."; +
 System.out.println(s);  s.indexOf("the", 10));
 System.out.println("indexOf(t) = " +  System.out.println("lastIndexOf(the, 60)
 s.indexOf('t')); ="+
 s.lastIndexOf("the", 60));
 System.out.println("lastIndexOf(t) =
"+
 }
 }
 s.lastIndexOf('t'));
Here is the output of this program:
 System.out.println("indexOf(the) = " Now is the time for all good men to come to
+ the aid of their country.
indexOf(t) = 7
 s.indexOf("the")); lastIndexOf(t) = 65
indexOf(the) = 7
 System.out.println("lastIndexOf(the) lastIndexOf(the) = 55
="+ indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
 s.lastIndexOf("the")); indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
CONTD…
 concat():
 You can concatenate two strings using concat( ), shown here:
 String concat(String str)
 This method creates a new object that contains the invoking string with
the contents of str appended to the end. concat( ) performs the same
function as +. For example,
 String s1 = "one";
 String s2 = s1.concat("two");
 replace():
 The replace( ) method replaces all occurrences of one character in the
invoking string with another character. It has the following general form:
 String replace(char original, char replacement)
 Here, original specifies the character to be replaced by the character
specified by replacement. The resulting string is returned. For example,
 String s = "Hello".replace('l', 'w');
 puts the string “Hewwo” into s.
CONTD…
 trim():
 The trim( ) method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed. It has this
general form:
 String trim( )
 Here is an example:
 String s = " Hello World ".trim();
 This puts the string “Hello World” into s.
STRING BUFFER CLASS
 Java StringBuffer class is used to create mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is
mutable i.e. it can be changed.
 StringBuffer class is a peer class of string that provides much of the
functionality of strings. As you know, string represent fixed length,
immutable character sequences.
 In contrast, StringBuffer represent growable and writeable
characters. You can insert character or substring in middle of
stringbuffer class object, it will automatically grow and adjust these
insertions.
 String buffer often has more characters preallocated than are
actually needed, to allow room for growth.

 Note: Java StringBuffer class is thread-safe i.e. multiple threads


cannot access it simultaneously. So it is safe and will result in an
order.
IMPORTANT CONSTRUCTORS OF STRINGBUFFER CLASS

String buffer allocates room for 16 additional characters when no


specific buffer length is requested, because reallocation is a costly
process in terms of time. Also frequent reallocation can fragment
memory. By allocating room for few extra characters, StringBuffer
reduces the number of reallocation that takes place.
IMPORTANT METHODS OF STRINGBUFFER CLASS
 append(String s)
 insert(int offset, String s)
 replace(int startIndex, int endIndex, String str)
 delete(int startIndex, int endIndex)
 reverse()
 capacity()
 ensureCapacity(int minimumCapacity)
 charAt(int index)
 length()
 substring(int beginIndex)
 substring(int beginIndex, int endIndex)
1) STRINGBUFFER APPEND() METHOD
2) STRINGBUFFER INSERT() METHOD
3) STRINGBUFFER REPLACE() METHOD
4) STRINGBUFFER DELETE() METHOD
5) STRINGBUFFER REVERSE() METHOD
6) STRINGBUFFER CAPACITY() METHOD
 The capacity() method of StringBuffer class returns the current
capacity of the buffer. The default capacity of the buffer is 16. If the
number of character increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
7) STRINGBUFFER ENSURECAPACITY() METHOD
 The ensureCapacity() method of StringBuffer class ensures that the given
capacity is the minimum to the current capacity. If it is greater than the
current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.
DIFFERENCE BETWEEN STRING AND STRINGBUFFER
 There are many differences between String and StringBuffer. A list
of differences between String and StringBuffer are given below:

String StringBuffer
String class is immutable. StringBuffer class is mutable.

String is slow and consumes StringBuffer is fast and


more memory when you consumes less memory when
concat too many strings you concat strings.
because every time it creates
new instance.
String class overrides the StringBuffer class doesn't
equals() method of Object override the equals() method
class. So you can compare of Object class.
the contents of two strings by
equals() method.

You might also like