0% found this document useful (0 votes)
210 views287 pages

Java Yesterday and Today Class Notes

The Object class sits at the top of the class hierarchy in Java. It defines common methods like equals(), clone(), finalize(), and getClass() that are inherited by all other classes. The equals() method determines if two objects are equal, clone() creates a copy of an object, finalize() performs cleanup before garbage collection, and getClass() returns the object's runtime class. The Object class also defines methods like notify(), notifyAll(), and wait() that are used to synchronize activities between threads.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
210 views287 pages

Java Yesterday and Today Class Notes

The Object class sits at the top of the class hierarchy in Java. It defines common methods like equals(), clone(), finalize(), and getClass() that are inherited by all other classes. The equals() method determines if two objects are equal, clone() creates a copy of an object, finalize() performs cleanup before garbage collection, and getClass() returns the object's runtime class. The Object class also defines methods like notify(), notifyAll(), and wait() that are used to synchronize activities between threads.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 287

Using Predefined Lang package & other Classes

java.lang.Object Class in Java


The Object class, in the java.lang package sits at the top of the class hierarchy tree. Every class
is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the
instance methods of Object. You need not to use any of these methods, but, if you choose to
do so, you may need to override them with code that is specific to your class.

Object Class Methods

1. protected Object clone()


2. booleanequals(Object obj)
3. protected void finalize()
4. Class<?>getClass()
5. int hashCode()
6. void notify()
7. void notifyAll()
8. void wait()
9. String toString()

The notify, notifyAll, and wait methods of Object all play a part in synchronizing the


activities of independently running threads in a program. There are five of these methods:

 public final void notify()


 public final void notifyAll()
 public final void wait()
 public final void wait(long timeout)
 public final void wait(long timeout, int nanos)

The below diagram is an Object class diagram shows a list of methods it provides.


Let's discuss above each method with examples.

Object Class Methods


1. protected Object clone()
2. booleanequals(Object obj)
3. protected void finalize()
4. Class<?>getClass()
5. int hashCode()
6. void notify()
7. void notifyAll()
8. void wait()
9. String toString()

The notify, notifyAll, and wait methods of Object all play a part in synchronizing the


activities of independently running threads in a program. There are five of these methods:

 public final void notify()


 public final void notifyAll()
 public final void wait()
 public final void wait(long timeout)
 public final void wait(long timeout, int nanos)
The below diagram is a Object class diagram shows a list of methods it provides.

Let's discuss above each method with examples.

1. protected Object clone() Method


clone() method creates and returns a copy of this object. The precise meaning of "copy" may
depend on the class of the object. The general intent is that for any object x, the expression:

x.clone() != x

will be true, and that the expression:

x.clone().getClass() ==x.getClass()

will be true, but these are not absolute requirements. While it is typically the case that:

x.clone().equals(x)

will be true, this is not an absolute requirement.

By convention, the returned object should be obtained by calling super.clone. If a class and all of
its superclasses (except Object) obey this convention, it will be the case that x.clone().getClass()
== x.getClass().
clone() method throws a CloneNotSupportedException if the object's class does not support
the Cloneable interface. Subclasses that override the clone method can also throw this exception
to indicate that an instance cannot be cloned.

protected Object clone() Method Example

This example shows the usage of clone() method:

publicclassObjectClass {

publicstaticvoidmain(String[] args) {
Datedate=newDate();
System.out.println(date.toString());
Date date2 = (Date) date.clone();
System.out.println(date2.toString());
}
}

Output:

Tue Sep 04 14:15:00 IST 2018


Tue Sep 04 14:15:00 IST 2018

Let's discuss one more example using the Closable interface and clone() method together.

First, create a Person class which implements a Closable interface.

publicclassPersonimplementsCloneable {
privateString firstName;
privateString lastName;

publicStringgetFirstName() {
returnfirstName;
}

publicvoidsetFirstName(StringfirstName) {
this.firstName=firstName;
}

publicStringgetLastName() {
returnlastName;
}

publicvoidsetLastName(StringlastName) {
this.lastName=lastName;
}
@Override
publicObjectclone() throwsCloneNotSupportedException {
Personperson= (Person) super.clone();
return person;
}

@Override
publicStringtoString() {
return"Person [firstName="+firstName+", lastName="+lastName+"]";
}

publicstaticvoidmain(String[] args) throwsCloneNotSupportedException {


Personperson=newPerson();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");

System.out.println(person.toString());

Person person2 = (Person) person.clone();

System.out.println(person2.toString());
}
}

Output:

Person [firstName=Ramesh, lastName=Fadatare]


Person [firstName=Ramesh, lastName=Fadatare]

Note that we have to override the clone() method from Object class and made a call to


Object clone() method using super.clone().

@Override
publicObjectclone() throws CloneNotSupportedException {
Personperson= (Person) super.clone();
return person;
}

2. Boolean equals(Object obj)


The java.lang.Object.equals(Object obj) indicates whether some other object is "equal to" this
one.

The equals method implements an equivalence relation on non-null object references:


 It is reflexive: for any non-null reference value x, x.equals(x) should return true.
 It is symmetric: for any non-null reference values x and y, x.equals(y) should
return true if and only if y.equals(x) returns true.
 It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns
true and y.equals(z) returns true, then x.equals(z) should return true.
 It is consistent: for any non-null reference values x and y, multiple invocations of
x.equals(y) consistently return true or consistently return false, provided no
information used in equals comparisons on the objects is modified.
 For any non-null reference value x, x.equals(null) should return false.

boolean equals(Object obj) Example

Let's create a simple example to demonstrate the usage of equals method:

// get an integer, which is an object


Integer x =newInteger(50);

// get a float, which is an object as well


Float y =newFloat(50f);

// check if these are equal,which is


// false since they are different class
System.out.println(""+x.equals(y));

// check if x is equal with another int 50


System.out.println(""+x.equals(50));

Output:

false
true

The equals() method for Person class is:

@Override
publicbooleanequals(Object obj) {
if (this== obj)
returntrue;
if (obj ==null)
returnfalse;
if (getClass() !=obj.getClass())
returnfalse;
Person other = (Person) obj;
if (firstName==null) {
if (other.firstName!=null)
returnfalse;
} elseif(!firstName.equals(other.firstName))
returnfalse;
if (lastName==null) {
if (other.lastName!=null)
returnfalse;
} elseif(!lastName.equals(other.lastName))
returnfalse;
returntrue;
}

Let's test above equals method:

publicclassPersonimplementsCloneable {
privateStringfirstName;
privateStringlastName;

publicStringgetFirstName() {
returnfirstName;
}

publicvoidsetFirstName(StringfirstName) {
this.firstName=firstName;
}

publicStringgetLastName() {
returnlastName;
}

publicvoidsetLastName(StringlastName) {
this.lastName=lastName;
}

@Override
publicbooleanequals(Object obj) {
if (this== obj)
returntrue;
if (obj ==null)
returnfalse;
if (getClass() !=obj.getClass())
returnfalse;
Person other = (Person) obj;
if (firstName==null) {
if (other.firstName!=null)
returnfalse;
} elseif(!firstName.equals(other.firstName))
returnfalse;
if (lastName==null) {
if (other.lastName!=null)
returnfalse;
} elseif(!lastName.equals(other.lastName))
returnfalse;
returntrue;
}

@Override
publicStringtoString() {
return"Person [firstName="+firstName+", lastName="+lastName+"]";
}

publicstaticvoidmain(String[] args) throwsCloneNotSupportedException {


Personperson=newPerson();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");

Person person1 =newPerson();


person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");

booleanhasEqual=person.equals(person1);
System.out.println("Both objects equal :: "+hasEqual);
}
}

Output:

Both objects equal :: true

Note: If you override equals(), you must override hashCode() as well.

3. protected void finalize() Method


The java.lang.Object.finalize() is called by the garbage collector on an object when
garbage collection determines that there are no more references to the object. A subclass
overrides the finalize method to dispose of system resources or to perform other cleanups.

The finalize() method may be called automatically by the system, but when it is called, or even if
it is called, is uncertain. Therefore, you should not rely on this method to do your cleanup for
you. For example, if you don't close file descriptors in your code after performing I/O and you
expect finalize() to close them for you, you may run out of file descriptors.

protected void finalize() Method Example

Let's override finalize() method from Object class into Person class and test it using main()
method.
publicclassPerson {
privateStringfirstName;
privateStringlastName;

publicStringgetFirstName() {
returnfirstName;
}

publicvoidsetFirstName(StringfirstName) {
this.firstName=firstName;
}

publicStringgetLastName() {
returnlastName;
}

publicvoidsetLastName(StringlastName) {
this.lastName=lastName;
}

// This method is called just before an object is garbage collected


@Override
protectedvoidfinalize() throwsThrowable {
// TODO Auto-generated method stub
super.finalize();
}

@Override
publicStringtoString() {
return"Person [firstName="+firstName+", lastName="+lastName+"]";
}

publicstaticvoidmain(String[] args) {
Personperson=newPerson();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");

System.out.println("Before Finalize");
try {
person.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("After Finalize");
}
}

Let us compile and run the above program, this will produce the following result −

Before Finalize
After Finalize

4. Class<?>getClass() Method
The java.lang.Object.getClass() method returns the runtime class of an object. That Class
object is the object that is locked by static synchronized methods of the represented class.

Class<?>getClass() Method Example

The following example shows the usage of lang.Object.getClass() method.

publicclassPerson {
privateStringfirstName;
privateStringlastName;

publicStringgetFirstName() {
returnfirstName;
}

publicvoidsetFirstName(StringfirstName) {
this.firstName=firstName;
}

publicStringgetLastName() {
returnlastName;
}

publicvoidsetLastName(StringlastName) {
this.lastName=lastName;
}

publicstaticvoidmain(String[] args) {
Personperson=newPerson();
System.out.println(person.getClass());
}
}

Let us compile and run the above program, this will produce the following result −

class com.javaguides.corejava.lang.Person

4. int hashCode() Method


The java.lang.Object.hashCode() method returns a hash code value for the object. This method is
supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

 Whenever it is invoked on the same object more than once during an execution of
a Java application, the hashCode method must consistently return the same
integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application.
 If two objects are equal according to the equals(Object) method, then calling the
hashCode method on each of the two objects must produce the same integer
result.
 It is not required that if two objects are unequal according to the
java.lang.Object.equals(java.lang.Object) method, then calling the hashCode
method on each of the two objects must produce distinct integer results. However,
the programmer should be aware that producing distinct integer results for
unequal objects may improve the performance of hash tables.

int hashCode() Method Example

The following example shows the usage of lang.Object.hashCode() method:

publicclassPerson {
privateStringfirstName;
privateStringlastName;

publicStringgetFirstName() {
returnfirstName;
}

publicvoidsetFirstName(StringfirstName) {
this.firstName=firstName;
}

publicStringgetLastName() {
returnlastName;
}

publicvoidsetLastName(StringlastName) {
this.lastName=lastName;
}

@Override
publicinthashCode() {
finalint prime =31;
int result =1;
result = prime * result + ((firstName==null) ?0:firstName.hashCode());
result = prime * result + ((lastName==null) ?0:lastName.hashCode());
return result;
}

publicstaticvoidmain(String[] args) {
Personperson=newPerson();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");

System.out.println(person.hashCode());

Person person1 =newPerson();


person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");
System.out.println(person1.hashCode());
}
}

Let us compile and run the above program, this will produce the following result −

-1066062211
-1066062211

By definition, if two objects are equal, their hashcode must also be equal. If you override
the equals() method, you change the way two objects are equated and Object's
implementation of hashCode() is no longer valid. Therefore, if you override
the equals() method, you must also override the hashCode() method as well.

6. notify() , 7. notifyAll() and 8. wait() Methods


 void notify() - This method wakes up a single thread that is waiting on this object's
monitor.
 void notifyAll() - This method wakes up all threads that are waiting on this object's
monitor.
 void wait() - This method causes the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object.

notify() , 7. notifyAll() and 8. wait() Methods Example

The following example shows the usage of notify() , notifyAll() and wait() Methods:
importjava.util.Collections;
importjava.util.LinkedList;
importjava.util.List;

publicclassObjectClassNotifyNotifyAllAndWaitExample {
privateList<String>synchedList;

publicObjectClassNotifyNotifyAllAndWaitExample() {
// create a new synchronized list to be used
synchedList=Collections.synchronizedList(newLinkedList<>());
}

// method used to remove an element from the list


publicStringremoveElement() throwsInterruptedException {
synchronized (synchedList) {

// while the list is empty, wait


while (synchedList.isEmpty()) {

System.out.println("List is empty...");

synchedList.wait();

System.out.println("Waiting...");
}
String element =synchedList.remove(0);

return element;
}
}

// method to add an element in the list


publicvoidaddElement(Stringelement) {
System.out.println("Opening...");
synchronized (synchedList) {

// add an element and notify all that an element exists


synchedList.add(element);

System.out.println("New Element added:'"+ element +"'");

synchedList.notifyAll();
System.out.println("notifyAll called!");
}

System.out.println("Closing in AddElement method...");


}

publicstaticvoidmain(String[] args) {
finalObjectClassNotifyNotifyAllAndWaitExample demo
=newObjectClassNotifyNotifyAllAndWaitExample();

RunnablerunA= () -> {
try {
String item =demo.removeElement();
System.out.println(""+ item);
} catch (InterruptedException ix) {
System.out.println("Interrupted Exception!");
} catch (Exception x) {
System.out.println("Exception thrown.");
}
};

RunnablerunB= () -> {
// run adds an element in the list and starts the loop
demo.addElement("Hello!");
};

try {
Thread threadA1 =newThread(runA, "A");
threadA1.start();

Thread.sleep(500);

Thread threadA2 =newThread(runA, "B");


threadA2.start();

Thread.sleep(500);

ThreadthreadB=newThread(runB, "C");
threadB.start();

Thread.sleep(1000);

threadA1.interrupt();
threadA2.interrupt();
} catch (InterruptedException x) {
}
}
}

Output:

List is empty...
List is empty...
Opening...
New Element added:'Hello!'
notifyAll called!
Waiting...
Closing in AddElement method...
Hello!
Waiting...
List is empty...
Interrupted Exception!

9. String toString() Method


The java.lang.Object.toString() method returns a string representation of the object. In
general, the toString method returns a string that "textually represents" this object. The result
should be a concise but informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.

String toString() Method Example

The following example shows the usage of lang.Object.toString() method.

publicclassPerson {
privateStringfirstName;
privateStringlastName;

publicStringgetFirstName() {
returnfirstName;
}

publicvoidsetFirstName(StringfirstName) {
this.firstName=firstName;
}

publicStringgetLastName() {
returnlastName;
}

publicvoidsetLastName(StringlastName) {
this.lastName=lastName;
}

@Override
publicStringtoString() {
return"Person [firstName="+firstName+", lastName="+lastName+"]";
}

publicstaticvoidmain(String[] args) {
Personperson=newPerson();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
System.out.println(person.toString());
}
}
Let us compile and run the above program, this will produce the following result −

Person [firstName=Ramesh, lastName=Fadatare]

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and


objects into primitives automatically. The automatic conversion of primitive into an object is
known as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. Let us see the different
scenarios, where we need to use the wrapper classes.

o Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
o Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with
objects.
o Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

Wrapper class Example: Primitive to Wrapper

1. //Java program to convert primitive into objects  
2. //Autoboxing example of int to Integer  
3. public class WrapperExample1{  
4. public static void main(String args[]){  
5. //Converting int into Integer  
6. int a=20;  
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly  
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
9.   
10. System.out.println(a+" "+i+" "+j);  
11. }}  

Output:

20 20 20

Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive

1. //Java program to convert object into primitives  
2. //Unboxing example of Integer to int  
3. public class WrapperExample2{    
4. public static void main(String args[]){    
5. //Converting Integer to int    
6. Integer a=new Integer(3);    
7. int i=a.intValue();//converting Integer to int explicitly  
8. int j=a;//unboxing, now compiler will write a.intValue() internally    
9.     
10. System.out.println(a+" "+i+" "+j);    
11. }}    

Output:

3 3 3

Java Wrapper classes Example


1. //Java Program to convert all primitives into its corresponding   
2. //wrapper objects and vice-versa  
3. public class WrapperExample3{  
4. public static void main(String args[]){  
5. byte b=10;  
6. short s=20;  
7. int i=30;  
8. long l=40;  
9. float f=50.0F;  
10. double d=60.0D;  
11. char c='a';  
12. boolean b2=true;  
13.   
14. //Autoboxing: Converting primitives into objects  
15. Byte byteobj=b;  
16. Short shortobj=s;  
17. Integer intobj=i;  
18. Long longobj=l;  
19. Float floatobj=f;  
20. Double doubleobj=d;  
21. Character charobj=c;  
22. Boolean boolobj=b2;  
23.   
24. //Printing objects  
25. System.out.println("---Printing object values---");  
26. System.out.println("Byte object: "+byteobj);  
27. System.out.println("Short object: "+shortobj);  
28. System.out.println("Integer object: "+intobj);  
29. System.out.println("Long object: "+longobj);  
30. System.out.println("Float object: "+floatobj);  
31. System.out.println("Double object: "+doubleobj);  
32. System.out.println("Character object: "+charobj);  
33. System.out.println("Boolean object: "+boolobj);  
34.   
35. //Unboxing: Converting Objects to Primitives  
36. byte bytevalue=byteobj;  
37. short shortvalue=shortobj;  
38. int intvalue=intobj;  
39. long longvalue=longobj;  
40. float floatvalue=floatobj;  
41. double doublevalue=doubleobj;  
42. char charvalue=charobj;  
43. boolean boolvalue=boolobj;  
44.   
45. //Printing primitives  
46. System.out.println("---Printing primitive values---");  
47. System.out.println("byte value: "+bytevalue);  
48. System.out.println("short value: "+shortvalue);  
49. System.out.println("int value: "+intvalue);  
50. System.out.println("long value: "+longvalue);  
51. System.out.println("float value: "+floatvalue);  
52. System.out.println("double value: "+doublevalue);  
53. System.out.println("char value: "+charvalue);  
54. System.out.println("boolean value: "+boolvalue);  
55. }}  

Output:

---Printing object values---


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true

Custom Wrapper class in Java


Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper
classes. We can also create a class which wraps a primitive data type. So, we can create a
custom wrapper class in Java.

1. //Creating the custom wrapper class  
2. class Javatpoint{  
3. private int i;  
4. Javatpoint(){}  
5. Javatpoint(int i){  
6. this.i=i;  
7. }  
8. public int getValue(){  
9. return i;  
10. }  
11. public void setValue(int i){  
12. this.i=i;  
13. }  
14. @Override  
15. public String toString() {  
16.   return Integer.toString(i);  
17. }  
18. }  
19. //Testing the custom wrapper class  
20. public class TestJavatpoint{  
21. public static void main(String[] args){  
22. Javatpoint j=new Javatpoint(10);  
23. System.out.println(j);  
24. }}  

Output:

10

Java Math class


Java Math class provides several methods to work on math calculations like min(), max(),
avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Unlike some of the StrictMath class numeric methods, all implementations of the equivalent
function of Math class can't define to return the bit-for-bit same results. This relaxation
permits implementation with better-performance where strict reproducibility is not required.

If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw
an ArithmeticException.

For other arithmetic operations like increment, decrement, divide, absolute value, and
negation overflow occur only with a specific minimum or maximum value. It should be
checked against the maximum and minimum value as appropriate.

Example 1
1. public class JavaMathExample1    
2. {    
3.     public static void main(String[] args)     
4.     {    
5.         double x = 28;    
6.         double y = 4;    
7.           
8.         // return the maximum of two numbers  
9.         System.out.println("Maximum number of x and y is: " +Math.max(x, y));   
10.           
11.         // return the square root of y   
12.         System.out.println("Square root of y is: " + Math.sqrt(y));   
13.           
14.         //returns 28 power of 4 i.e. 28*28*28*28    
15.         System.out.println("Power of x and y is: " + Math.pow(x, y));      
16.   
17.         // return the logarithm of given value       
18.         System.out.println("Logarithm of x is: " + Math.log(x));   
19.         System.out.println("Logarithm of y is: " + Math.log(y));  
20.           
21.         // return the logarithm of given value when base is 10      
22.         System.out.println("log10 of x is: " + Math.log10(x));   
23.         System.out.println("log10 of y is: " + Math.log10(y));    
24.           
25.         // return the log of x + 1  
26.         System.out.println("log1p of x is: " +Math.log1p(x));    
27.   
28.         // return a power of 2    
29.         System.out.println("exp of a is: " +Math.exp(x));    
30.           
31.         // return (a power of 2)-1  
32.         System.out.println("expm1 of a is: " +Math.expm1(x));  
33.     }    
34. }    
Test it Now

Output:

Maximum number of x and y is: 28.0


Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12
expm1 of a is: 1.446257064290475E12

Example 2
1. public class JavaMathExample2    
2. {    
3.     public static void main(String[] args)     
4.     {    
5.         double a = 30;    
6.           
7.         // converting values to radian    
8.         double b = Math.toRadians(a);   
9.           
10.         // return the trigonometric sine of a      
11.         System.out.println("Sine value of a is: " +Math.sin(a));    
12.           
13.         // return the trigonometric cosine value of a  
14.         System.out.println("Cosine value of a is: " +Math.cos(a));  
15.           
16.         // return the trigonometric tangent value of a  
17.         System.out.println("Tangent value of a is: " +Math.tan(a));  
18.           
19.         // return the trigonometric arc sine of a      
20.         System.out.println("Sine value of a is: " +Math.asin(a));    
21.           
22.         // return the trigonometric arc cosine value of a  
23.         System.out.println("Cosine value of a is: " +Math.acos(a));  
24.           
25.         // return the trigonometric arc tangent value of a  
26.         System.out.println("Tangent value of a is: " +Math.atan(a));  
27.   
28.         // return the hyperbolic sine of a      
29.         System.out.println("Sine value of a is: " +Math.sinh(a));    
30.           
31.         // return the hyperbolic cosine value of a  
32.         System.out.println("Cosine value of a is: " +Math.cosh(a));  
33.           
34.         // return the hyperbolic tangent value of a  
35.         System.out.println("Tangent value of a is: " +Math.tanh(a));  
36.     }    
37. }    
Test it Now

Output:

Sine value of a is: -0.9880316240928618


Cosine value of a is: 0.15425144988758405
Tangent value of a is: -6.405331196646276
Sine value of a is: NaN
Cosine value of a is: NaN
Tangent value of a is: 1.5374753309166493
Sine value of a is: 5.343237290762231E12
Cosine value of a is: 5.343237290762231E12
Tangent value of a is: 1.0

Java Math Methods


The java.lang.Math class contains various methods for performing basic numeric
operations such as the logarithm, cube root, and trigonometric functions etc. The various
java math methods are as follows:

Basic Math methods

Method Description

Math.abs() It will return the Absolute value of the given value.

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.

Math.sqrt() It is used to return the square root of a number.

Math.cbrt() It is used to return the cube root of a number.

Math.pow() It returns the value of first argument raised to the power to second argum

Math.signum() It is used to find the sign of a given value.

Math.ceil() It is used to find the smallest integer value that is greater than or equal to
mathematical integer.

Math.copySign() It is used to find the Absolute value of first argument along with sign speci
argument.
Math.nextAfter() It is used to return the floating-point number adjacent to the first argumen
the second argument.

Math.nextUp() It returns the floating-point value adjacent to d in the direction of positive

Math.nextDown() It returns the floating-point value adjacent to d in the direction of negative

Math.floor() It is used to find the largest integer value which is less than or equal to the
equal to the mathematical integer of a double value.

Math.floorDiv() It is used to find the largest integer value that is less than or equal to the

Math.random() It returns a double value with a positive sign, greater than or equal to 0.0 

Math.rint() It returns the double value that is closest to the given argument and equa
integer.

Math.hypot() It returns sqrt(x2 +y2) without intermediate overflow or underflow.

Math.ulp() It returns the size of an ulp of the argument.

Math.getExponent() It is used to return the unbiased exponent used in the representation of a 

Math.IEEEremainder() It is used to calculate the remainder operation on two arguments as prescr


754 standard and returns value.

Math.addExact() It is used to return the sum of its arguments, throwing an exception if the
an int or long.

Math.subtractExact() It returns the difference of the arguments, throwing an exception if the res

Math.multiplyExact() It is used to return the product of the arguments, throwing an exception if


an int or long.

Math.incrementExact() It returns the argument incremented by one, throwing an exception if the


an int.

Math.decrementExact() It is used to return the argument decremented by one, throwing an except


overflows an int or long.

Math.negateExact() It is used to return the negation of the argument, throwing an exception if


an int or long.

Math.toIntExact() It returns the value of the long argument, throwing an exception if the val

Logarithmic Math Methods

Method Description

Math.log() It returns the natural logarithm of a double value.

Math.log10() It is used to return the base 10 logarithm of a double value.

Math.log1p() It returns the natural logarithm of the sum of the argument and 1.

Math.exp() It returns E raised to the power of a double value, where E is Euler's number and it
equal to 2.71828.

Math.expm1() It is used to calculate the power of E and subtract one from it.

Trigonometric Math Methods


Method Description

Math.sin() It is used to return the trigonometric Sine value of a Given double value.

Math.cos() It is used to return the trigonometric Cosine value of a Given double value.

Math.tan() It is used to return the trigonometric Tangent value of a Given double value.

Math.asin() It is used to return the trigonometric Arc Sine value of a Given double value

Math.acos() It is used to return the trigonometric Arc Cosine value of a Given double value.

Math.atan() It is used to return the trigonometric Arc Tangent value of a Given double value.

Hyperbolic Math Methods

Method Description

Math.sinh() It is used to return the trigonometric Hyperbolic Cosine value of a Given double val

Math.cosh() It is used to return the trigonometric Hyperbolic Sine value of a Given double value

Math.tanh() It is used to return the trigonometric Hyperbolic Tangent value of a Given double v

Angular Math Methods

Method Description

Math.toDegrees It is used to convert the specified Radians angle to equivalent angle


measured in Degrees.

Math.toRadians It is used to convert the specified Degrees angle to equivalent angle

measured in Radians.

1. String Basics
As we know Strings are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.

The Java platform provides the  java.lang.String class to create and manipulate strings.

1.1 Create a String object


There are two ways to create a String object:

 By string literal
 By new keyword

Using String Literal

Java String literal is created by using double quotes.

For Example:

String s="javaguides";

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 a string doesn't exist
in the pool, a new string instance is created and placed in the pool.

For example:

String s1="javaguides";
String s2="javaguides";
//will not create new instance
To know more detail how the String Pool works on  Guide to Java String Constant Pool

Now the question is why java uses a concept of a string literal?

It's simple, to make Java more memory efficient (because no new objects are created if it exists
already in string constant pool).

Using a new Keyword

Let's create a simple example to demonstrate by creating String objects using the new keyword.

publicstaticvoidmain(String[] args) {
String str =newString("Java Guides");
// create String object using new Keyword
int length =str.length();
System.out.println(" length of the string '"+ str +"' is :: "+ length);
}

Output:

length of the string 'Java Guides' is:: 11

From the above example, JVM will create a new string object in normal(non-pool) heap memory
and the literal "Java Guides" will be placed in the string constant pool. The variable str will refer
to the object in heap(non-pool).

To create a String initialized by an array of characters, Here is an example:

charchars[] = {
'a',
'b',
'c'
}

;
String s =newString(chars);

Let's learn the String in depth by exploring all the String APIs with examples.
1.2 String Class Hierarchy in Java

String class implemented interfaces:  Serializable, CharSequence, Comparable< String>


.  Refer more detail on  java.lang.String  JavaDoc.

String class implemented interfaces

2. The String Constructors


The String class supports several constructors.

 String()  - Initializes a newly created String object so that it represents an empty


character sequence.
 String(byte[] bytes)  - Constructs a new String by decoding the specified array of
bytes using the platform's default charset.
 String(byte[] bytes, Charset charset)  - Constructs a new String by decoding
the specified array of bytes using the specified charset.
 String(byte[] bytes, int offset, int length)  - Constructs a new String by
decoding the specified subarray of bytes using the platform's default charset.
 String(byte[] bytes, int offset, int length, Charset charset)  -
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
 String(byte[] bytes, int offset, int length, String charsetName)  -
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
 String(byte[] bytes, String charsetName)  - Constructs a new String by
decoding the specified array of bytes using the specified charset.
 String(char[] value)  - Allocates a new String so that it represents the sequence of
characters currently contained in the character array argument.
 String(char[] value, int offset, int count)  - Allocates a new String that
contains characters from a subarray of the character array argument.
 String(int[] codePoints, int offset, int count)  - Allocates a new String that
contains characters from a subarray of the Unicode code point array argument.
 String(String original)  - Initializes a newly created String object so that it
represents the same sequence of characters as the argument; in other words, the newly
created string is a copy of the argument string.
 String(StringBuffer buffer)  - Allocates a new string that contains the sequence of
characters currently contained in the string buffer argument.
 String(StringBuilder builder)  - Allocates a new string that contains the sequence
of characters currently contained in the string builder argument.

Let's learn a few important String offered Constructors with examples.

1. To create an empty String, call the default constructor.  For example,

String s =newString();

will create an instance of String with no characters in it.

2. To create a String initialized by an array of characters.  Here is an example:

charchars[] = {
'a',
'b',
'c'
}

;
String s =newString(chars);

This constructor initializes s with the string "abc".

3. We can specify a subrange of a character array as an initializer using the following


constructor:
String(char chars[], intstartIndex, intnumChars)

Here, startIndex specifies the index at which the subrange begins, and numChars specifies the
number of characters to use. Here is an example:

charchars[] = {
'a',
'b',
'c',
'd',
'e',
'f'
}

;
String s =newString(chars, 2, 3);

This initializes s with the characters cde.

4. We can construct a String object that contains the same character sequence as
another String object using this constructor:

String(StringstrObj)

Here, strObj is a String object. Consider this example:

// Construct one String from another.


classMakeString {
publicstaticvoidmain(Stringargs[]) {
charc[] = {
'J',
'a',
'v',
'a'
}
;
String s1 =newString(c);
String s2 =newString(s1);
System.out.println(s1);
System.out.println(s2);
}
}

The output from this program is as follows:


Java Java

As you can see, s1 and s2 contain the same string.

5. String class provides constructors that initialize a string when given a byte
array.  Two forms are shown here:

String(bytechrs[]) String(bytechrs[], intstartIndex, intnumChars)

Here, chrs  specifies the array of bytes. The second form allows you to specify a subrange. In
each of these constructors, the byte-to-character conversion is done by using the default
character encoding of the platform. The following program illustrates these constructors:

// Construct string from subset of char array.


classSubStringCons {
publicstaticvoidmain(Stringargs[]) {
byteascii[] = {
65,
66,
67,
68,
69,
70
}
;
String s1 =newString(ascii);
System.out.println(s1);
String s2 =newString(ascii, 2, 3);
System.out.println(s2);
}
}

This program generates the following output:

ABCDEF CDE

6. We can construct a  String  from a  StringBuffer  and StringBuilder using String


constructors

String(StringBufferstrBufObj) String(StringBuilderstrBuildObj)

Examples:
Stringstring=newString(newStringBuffer("JavaGuides"));
System.out.println(string);
String string2 =newString(newStringBuilder("JavaGuides"));
System.out.println(string2);

Output:

JavaGuidesJavaGuides

3. All String APIs/ Methods with


Examples
charAt(int index)

To extract a single character from a  String, you can refer directly to an individual character via
the charAt()  method.

Example 1:  Returns the char value at the specified index of this string. The first char value is at
index 0.

String str ="Welcome to string handling guide";


char ch1 =str.charAt(0);
char ch2 =str.charAt(5);
char ch3 =str.charAt(11);
char ch4 =str.charAt(20);
System.out.println("Character at 0 index is: "+ ch1);
System.out.println("Character at 5th index is: "+ ch2);
System.out.println("Character at 11th index is: "+ ch3);
System.out.println("Character at 20th index is: "+ ch4);

Output:

Character at 0 index is: W Character at 5th index is: m Character at 11th


index is: s Character at 20th index is: n

Example 2:  Throws  IndexOutOfBoundsException  - if the index argument is negative or not


less than the length of this string.

String str ="Java Guides";


char ch1 =str.charAt(str.length() +1);
System.out.println("character :: "+ ch1);

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String


index out of range: 12 at java.lang.String.charAt(String.java:658) at
com.javaguides.strings.methods.ChatAtExample.charAtExample2(ChatAtExample.java
:26) at
com.javaguides.strings.methods.ChatAtExample.main(ChatAtExample.java:6)

Example 3:  How to get the first and last character of the string

String str ="Java Guides";


intstrLength=str.length();
// Fetching first character
System.out.println("Character at 0 index is: "+str.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: "+str.charAt(strLength-1));

Output;

Character at 0 index is: J Character at last index is: s

codePointAt(int index)

This method returns the character (Unicode code point) at the specified index. The index refers
to char values (Unicode code units) and ranges from 0 to length()- 1.

This method throws the  IndexOutOfBoundsException  - if the index argument is negative or


not less than the length of this string.

Example:

publicclassCodePointAtExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
intunicode=str.codePointAt(0);
System.out.println("the character (Unicode code point) at the specified index
is :: "+unicode);
}
}

Output:
the character (Unicode code point) at the specified index is:: 106

codePointBefore(int index)

This method returns the character (Unicode code point) before the specified index. The index
refers to char values (Unicode code units) and ranges from 1 to length.

This method throws the  IndexOutOfBoundsException  - if the index argument is negative or


not less than the length of this string.

Example:

publicclassCodePointBeforeExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
intunicode=str.codePointBefore(1);
System.out.println("the character (Unicode code point)"+" at the before
specified index is :: "+unicode);
}
}

Output:

the character (Unicode code point) at the before specified index is:: 106

This method returns the number of Unicode code points in the specified text range of this
String. The text range begins at the specified beginIndex and extends to the char at
index endIndex - 1.

This method throws  IndexOutOfBoundsException  - if the beginIndex is negative, or endIndex


is larger than the length of this String, or beginIndex is larger than endIndex.

Example:

publicclassCodePointCountExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
System.out.println("length of the string :: "+str.length());
intunicode=str.codePointCount(0, str.length());
System.out.println("the character (Unicode code point) "+" at the specified
index is :: "+unicode);
}
}

Output:

length of the string:: 10 the character (Unicode code point) at the specified
index is:: 10

compareTo(String anotherString)

Often, it is not enough to simply know whether two strings are identical. For sorting
applications, you need to know which is less than, equal to, or greater than the next. A string is
less than another if it comes before the other in the dictionary order.

A string is greater than another if it comes after the other in the dictionary order. The
method compareTo()  serves this purpose. It is specified by the Comparable interface, which
String implements. It has this general form:

intcompareTo(String str)

Here, str is the String being compared with the invoking String. The result of the comparison is
returned as values meaning:

 Less than zero The invoking string is less than str.


 Greater than zero The invoking string is greater than str.
 Zero The two strings are equal.

Example 1: Here is a sample program that sorts an array of strings. The program
uses  compareTo()  to determine sort ordering for a bubble sort:

// A bubble sort for Strings.


publicclassCompareToSecondExample {
staticStringarr[] = {
"Now",
"is",
"the",
"time",
"for",
"all",
"good",
"men",
"to",
"come",
"to",
"the",
"aid",
"of",
"their",
"country"
}
;
publicstaticvoidmain(Stringargs[]) {
for (int j =0; j <arr.length; j++) {
for (inti= j +1; i<arr.length; i++) {
if (arr[i].compareTo(arr[j]) <0) {
String t =arr[j];
arr[j] =arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

The output of this program is the list of words:

Now aid all come country for good is men of the the their time to to

As you can see from the output of this example,   compareTo()  takes into account uppercase
and lowercase letters. The word "Now" came out before all the others because it begins with an
uppercase letter, which means it has a lower value in the ASCII character set.

Example 2: compareTo method return different values example

String s1 ="Hello World";


String s2 ="Hello World";
String s3 ="Java";
String s4 ="Guides";
System.out.println(s1.compareTo(s2));
// 0 because both are equal
System.out.println(s1.compareTo(s3));
// -2 because "H" is 2 times lower than "J"
System.out.println(s1.compareTo(s4));
// 1 because "G" is 1 times greater than "H"

Output:

0 -2 1
Example 3: Compare the string with black or empty string using compareTo() method. Note
that compare with an empty string returns length of the string.

String s1 ="hello";
String s2 ="";
String s3 ="me";
// compare with empty string, returns length of the string
System.out.println(s1.compareTo(s2));
// If first string is empty, result would be negative
System.out.println(s2.compareTo(s3));

Output:

5 -2

compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences. This method returns an
integer whose sign is that of calling compareTo with normalized versions of the strings where
case differences have been eliminated by
calling  Character.toLowerCase(Character.toUpperCase(character))  on each
character.

Example:

String s1="Hello World";


String s2="hello world";
String s3="Java";
String s4="java";
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));

Output:

0 0

This method returns a negative integer, zero, or a positive integer as the specified String is
greater than, equal to, or less than this String, ignoring case considerations.

concat(String str)

Concatenates the specified string to the end of this string.


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

Example:

publicclassConcatExmaple {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
str =str.concat(".net");
System.out.println("Concatenates the specified string to the end of this
string :"+ str);
System.out.println("cares".concat("s"));
System.out.println("to".concat("get"));
}
}

Output:

Concatenates the specified string to the end of this string: javaguides.net


caress toget

contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values.

Example:

publicclassContainsExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
boolean contains =str.contains("guides");
System.out.println("Contains :"+ contains);
}
}

Output:

Contains: true
contentEquals()

There are two versions of contentEquals methods;

1. contentEquals(CharSequence cs)  - Compares this string to the


specified  CharSequence.
2. contentEquals(StringBuffer sb)  - Compares this string to the
specified  StringBuffer.

Example:

publicclassContentEqualsExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr="javaguides";
booleanisContentEquals=str.contentEquals(subStr);
System.out.println("isContentEquals :: "+isContentEquals);
isContentEquals=str.contentEquals(newStringBuffer(subStr));
System.out.println("isContentEquals :: "+isContentEquals);
}
}

Output:

isContentEquals:: true isContentEquals:: true

endsWith(String suffix)

This method tests if this string ends with the specified suffix. Returns true if the character
sequence represented by the argument is a suffix of the character sequence represented by this
object; false otherwise.

Example:

publicclassEndsWithExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr="guides";
booleanendsWith=str.endsWith(subStr);
System.out.println(str +"endsWith"+subStr+" :: "+endsWith);
}
}
Output:

javaguidesendsWithguides:: true

equals(Object anObject) and equalsIgnoreCase(String


anotherString)

To compare two strings for equality, use equals(). It has this general form:

booleanequals(Object str)

Here, str is the String object is 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:

booleanequalsIgnoreCase(String str)

Here, str is the String object is compared with the invoking String object. It, too, returns true if
the strings contain the same characters in the same order, and false otherwise.

Here is an example that demonstrates  equals()  and  equalsIgnoreCase():

// Demonstrate equals() and equalsIgnoreCase().


classequalsDemo {
publicstaticvoidmain(Stringargs[]) {
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));
}
}

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

Example 2:

publicclassEqualsExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
String str1 ="javaguides";
String str3 ="javatutorial";
boolean equal =str.equals(str1);
System.out.println(" Is both string are equal :: "+ equal);
}
}

Output:

Is both string are equal:: true

Example 3:

publicclassEqualsIgnoreCaseExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
boolean equal =str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: "+ equal);
}
}

Output:

Strings are equal:: true

getBytes()

There are four versions of getBytes()  methods. There is an alternative to getChars()  that
stores the characters in an array of bytes.  byte[] getBytes()  - Encodes this String into a
sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(Charset charset)  - Encodes this String into a sequence of bytes using
the given charset, storing the result into a new byte array.

void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)  - Deprecated.

byte[] getBytes(String charsetName)  - Encodes this String into a sequence of bytes


using the named charset, storing the result into a new byte array.

Let's write an example to demonstrate all the getBytes() methods.

publicclassGetBytesExamples {
publicstaticvoidmain(String[] args) throwsUnsupportedEncodingException {
String str ="javaguides";
// Encodes this String into a sequence of bytes using the platform's
// default charset, storing the result into a new byte array.
byte[] bs =str.getBytes();
for (byteb : bs) {
System.out.println(b);
}
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs1 =str.getBytes(Charset.forName("UTF-8"));
for (byteb : bs1) {
System.out.println(b);
}
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs2 =str.getBytes("UTF-8");
for (byteb : bs2) {
System.out.println(b);
}
byte[] dest=newbyte[str.length()];
str.getBytes(0, str.length(), dest, 0);
for (byteb :dest) {
System.out.println(b);
}
}
}

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

If you need to extract more than one character at a time, you can use the getChars() method.
It has this general form:

voidgetChars(intsourceStart, intsourceEnd, char target[], inttargetStart)


Here, sourceStart specifies the index of the beginning of the substring,
and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the
substring contains the characters from sourceStart through sourceEnd–1.

The array that will receive the characters is specified by target. The index within the target at
which the substring will be copied is passed in targetStart. Care must be taken to assure that the
target array is large enough to hold the number of characters in the specified substring.

The following program demonstrates  getChars():

classgetCharsDemo {
publicstaticvoidmain(Stringargs[]) {
String s ="This is a demo of the getChars method.";
int start =10;
int end =14;
charbuf[] =newchar[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

Here is the output of this program:

demo

hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) +...+ s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and
^ indicates exponentiation. (The hash value of the empty string is zero.)

Example:

publicclassHashcodeExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
inthashcode=str.hashCode();
System.out.println("hashcode of "+ str +"is :: "+hashcode);
}
}

Output:

hashcode of javaguidesis:: -138203751

indexOf()

There are 4 types of an indexOf method in java. The signature of indexOf methods are given
below:

 indexOf(int ch)  - Returns the index within this string of the first occurrence of the
specified character.
 indexOf(int ch, int fromIndex)  - Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
 indexOf(String str) -  Returns the index within this string of the first occurrence of
the specified substring.
 indexOf(String str, int fromIndex) -  Returns the index within this string of the
first occurrence of the specified substring, starting at the specified index.

Example: This program demonstrates the example of all the 4  indexOf()  methods.

publicclassIndexOfExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
// method 1
int index =str.indexOf("java");
System.out.println(index);
// Remember index starts with 0 so count from 0
System.out.println("index of guides :: "+str.indexOf("guides"));
System.out.println(" index of des :: "+str.indexOf("des"));
// method 2
System.out.println(str.indexOf('s'));
// method 3
System.out.println(str.indexOf('g', 0));
// method 4
System.out.println(str.indexOf("guides", 3));
}
}

Output:
0 index of guides:: 4 index of des:: 7 9 4 4

intern()

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

Example:

publicclassInternExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringnewStr=newString("javaguides");
System.out.println(newStr.intern().equals(str));
System.out.println(newStr.equals(str));
newStr.intern();
str.intern();
}
}

Output:

true true

lastIndexOf() methods

There are 4 types of a lastIndexOf method in java. The signature of lastIndexOf methods are


given below:

 lastIndexOf(int ch)  - Returns the index within this string of the last occurrence of
the specified character.
 lastIndexOf(int ch, int fromIndex)  - Returns the index within this string of the
last occurrence of the specified character, searching backward starting at the specified
index.
 lastIndexOf(String str)  - Returns the index within this string of the last
occurrence of the specified substring.
 lastIndexOf(String str, int fromIndex)  - Returns the index within this string of
the last occurrence of the specified substring, searching backward starting at the
specified index.
The main usage of lastIndexOf()  - Searches for the last occurrence of a character or
substring.
Example: This program demonstrates the usage of all 4  lastIndexOf()  methods.

publicclassLastIndexOfExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
// method1
intlastIndexOf=str.lastIndexOf('s');
System.out.println(" last index of given character 's' in' "+""+ str+"' ::
"+lastIndexOf);
// method 2
lastIndexOf=str.lastIndexOf("guides");
System.out.println(" last index of given string 'guides' in' "+""+ str+"' ::
"+lastIndexOf);
// method 3
lastIndexOf=str.lastIndexOf("guides", 4);
System.out.println(" last index of guides in given string"+""+ str+" and from
index "+lastIndexOf);
// method 4
lastIndexOf=str.lastIndexOf('g', str.length());
System.out.println(" last index of given char :: "+lastIndexOf);
}
}

Output:

last index of given character 's' in' javaguides':: 9 last index of given
string 'guides' in' javaguides':: 4 last index of guides in given string
javaguides and from index 4 last index of given char:: 4

length()

The length of a string is the number of characters that it contains. To obtain this value, call
the  length()  method, shown here:

intlength()

Example: Example to print the length of string "Java Guides".

publicclassLengthExample {
publicstaticvoidmain(String[] args) {
String str =newString("Java Guides");
int length =str.length();
System.out.println(" length of the string '"+ str +"' is :: "+ length);
}
}

Output:

length of the string 'Java Guides' is:: 11

regionMatches()  methods

There are two types of regionMatches()  methods.

 regionMatches(booleanignoreCase, int toffset, String other, int


ooffset, int len)  - Tests if two string regions are equal.
 regionMatches(int toffset, String other, int ooffset, int len)  - Tests if
two string regions are equal.

Example: Example to tests if two string regions are equal.

publicclassRegionMatchesExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr="guides";
boolean b =str.regionMatches(0, subStr, str.length(), str.length());
boolean b1 =str.regionMatches(true, 0, str, 0, str.length());
System.out.println(b);
System.out.println(b1);
}
}

Output:

false true

replace()  methods

The replace()  method has two forms. The first replaces all occurrences of one character in the
invoking string with another character. It has the following general form:
Stringreplace(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.

The second form of replace() replaces one character sequence with another. It has this
general form:

Stringreplace(CharSequence original, CharSequence replacement)

Example: This is a complete example to demonstrate the usage of replace() methods.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replace('a', 'b');
System.out.println("replace char 'a' with char 'b' from given
string :"+subStr);
subStr=str.replace("guides", "tutorials");
System.out.println("replace guides with tutorials from given
string :"+subStr);
subStr=str.replaceAll("[a-z]", "java");
System.out.println(subStr);
subStr=str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}

Output:

replace char 'a' with char 'b' from given string: jbvbguides replace guides
with tutorials from given string:
javatutorialsjavajavajavajavajavajavajavajavajavajavajavaavaguides

replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given
replacement.
Example: This is a complete example to demonstrate the usage of replaceAll()  methods.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replaceAll("[a-z]", "java");
System.out.println(subStr);
}
}

Output:

javajavajavajavajavajavajavajavajavajava

replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the
given replacement.

Example: This is a complete example to demonstrate the usage of replaceFirst()  methods.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}

Output:

javaavaguides

split() methods

There are two form of split() methods.

 split(String regex)  Splits this string around matches of the given regular
expression. 
 split(String regex, int limit)  - Splits this string around matches of the given
regular expression.

Example: This is a complete example to demonstrate the usage of split()  methods.

publicclassSplitExample {
publicstaticvoidmain(String[] args) {
String str ="java,guides.net";
String[] strArray=str.split(",");
for (inti=0;
i<
strArray.length;
i++) {
System.out.println(strArray[i]);
}
strArray=str.split(",", 0);
for (inti=0;
i<
strArray.length;
i++) {
System.out.println(strArray[i]);
}
}
}

Output:

java guides.net java guides.net 

startsWith() methods

There are two forms of startsWith()  methods.

 startsWith(String prefix)  - Tests if this string starts with the specified prefix.
 booleanstartsWith(String prefix, int toffset)  - Tests if the substring of this
string beginning at the specified index starts with the specified prefix.

The startsWith()  method determines whether a given String begins with a specified string.
Example: This is a complete example to demonstrate the usage of startsWith()  methods.

publicclassStartsWithExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
booleanstartWith=str.startsWith("ja");
System.out.println("startWith :: "+startWith);
// Remember index starts from 0
booleanstartWithOffset=str.startsWith("guides", 4);
System.out.println("startWithOffset :: "+startWithOffset);
}
}

Output:

startWith:: true startWithOffset:: true

subSequence(int beginIndex, int endIndex)

Returns a character sequence that is a subsequence of this sequence.

An invocation of this method of the form

str.subSequence(begin, end)

behaves in exactly the same way as the invocation

str.substring(begin, end)

Example: This is a complete example to demonstrate the usage of subSequence() method.

publicclassSubSequenceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
CharSequencesubStr=str.subSequence(0, str.length());
System.out.println("Returns a character sequence that "+" is a subsequence of
this sequence :"+subStr);
}
}

Output:

Returns a character sequence that is a subsequence of this sequence:


javaguides
substring()  methods

There are two forms of substring()  methods.

 String substring(int beginIndex) -  Returns a string that is a substring of this


string. 
 String substring(int beginIndex, int endIndex)  - Returns a string that is a
substring of this string.

These methods throw IndexOutOfBoundsException- if beginIndex is negative or larger than


the length of this String object.
Example: This is a complete example to demonstrate the usage of both substring()  methods.

publicclassSubStringExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
// substring from start to end
StringsubStr=str.substring(0, str.length());
System.out.println("substring from 0 to length of the string :"+subStr);
subStr=str.substring(4);
System.out.println("Sub string starts from index 4 :"+subStr);
// Remember index starts from 0
System.out.println(str.substring(1));
System.out.println("unhappy".substring(2));
System.out.println("Harbison".substring(3));
System.out.println("emptiness".substring(8));
}
}

Output:

substring from 0 to length of the string: javaguides Sub string starts from
index 4: guides avaguides happy bison s

char[] java.lang.String.toCharArray()

Converts this string to a new character array.

Example: This is a complete example to demonstrate the usage of toCharArray()  method.

publicclassToCharArrayExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
char[] characters =str.toCharArray();
for (charc : characters) {
System.out.println(c);
}
}
}

Output:

j a v a g u i d e s

toLowerCase()  methods

There are two forms of toLowerCase()  methods.

 toLowerCase()  - Converts all of the characters in this String to lower case using the
rules of the default locale.
 String toLowerCase(Locale locale)  - Converts all of the characters in this String to
lower case using the rules of the given Locale.

Example: This is a complete example to demonstrate the usage of


both toLowerCase() methods.

publicclassToLowerCaseExample {
publicstaticvoidmain(String[] args) {
String str ="JAVAGUIDES";
StringsubStr=str.toLowerCase();
System.out.println(subStr);
subStr=str.toLowerCase(Locale.ENGLISH);
System.out.println(subStr);
}
}

Output:

javaguidesjavaguides

toString()

This object (which is already a string!) is itself returned. Example:


publicclassToStringExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
System.out.println(str.toString());
}
}

Output:

javaguides

toUpperCase() methods

There are two forms of toUpperCase() methods.

 toUpperCase()  - Converts all of the characters in this String to upper case using the
rules of the default locale.
 String toUpperCase(Locale locale)  - Converts all of the characters in this String
to upper case using the rules of the given Locale.

Example: This is a complete example to demonstrate the usage of


both toUpperCase() methods.

publicclassToUpperCaseExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.toUpperCase();
System.out.println(subStr);
subStr=str.toUpperCase(Locale.ENGLISH);
System.out.println(subStr);
}
}

Output:

JAVAGUIDES JAVAGUIDES

trim()

Returns a string whose value is this string, with any leading and trailing whitespace removed.
Example: This is a complete example to demonstrate the usage of trim()  method.

publicclassTrimExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.trim();
System.out.println("trim the space from given string :"+subStr);
}
}

Output:

trim the space from given string: javaguides

valueOf()

The  valueOf()  method converts data from its internal format into a human-readable form.

The Java string valueOf ()  method converts different types of values into a string. By the help
of string valueOf ()  method, you can
convert int to string, long to string, boolean to string, character to string, float to
a string, double to a string, object to string and char array to string.

Here are a few of its forms and the signature or syntax of string valueOf() method is given
below:

publicstaticStringvalueOf(boolean b) publicstaticStringvalueOf(char c)
publicstaticStringvalueOf(char[] c) publicstaticStringvalueOf(inti)
publicstaticStringvalueOf(long l) publicstaticStringvalueOf(float f)
publicstaticStringvalueOf(double d) publicstaticStringvalueOf(Object o)

Example: Let's see an example where we are converting all primitives and objects into strings.

publicclassStringValueOfExample5 {
publicstaticvoidmain(String[] args) {
boolean b1=true;
byte b2=11;
shortsh=12;
inti=13;
long l =14L;
float f =15.5f;
double d =16.5d;
charchr[]= {
'j',
'a',
'v',
'a'
}
;
StringValueOfExample5 obj=newStringValueOfExample5();
String s1 =String.valueOf(b1);
String s2 =String.valueOf(b2);
String s3 =String.valueOf(sh);
String s4 =String.valueOf(i);
String s5 =String.valueOf(l);
String s6 =String.valueOf(f);
String s7 =String.valueOf(d);
String s8 =String.valueOf(chr);
String s9 =String.valueOf(obj);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
System.out.println(s8);
System.out.println(s9);
}
}

Output:

true 11 12 13 14 15.5 16.5 java StringValueOfExample5@2a139a55

StringBuffer

Key Points About StringBuffer Class


 Java StringBuffer class is used to create a mutable (modifiable) string.
The StringBuffer class in Java is the same as String class except it is mutable i.e. it can
be changed.
 Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
 StringBuffer may have characters and substrings inserted in the middle or appended
to the end. StringBuffer will automatically grow to make room for such additions and
often has more characters preallocated than are actually needed, to allow room for
growth.
 The principal operations on a StringBuffer are the append and insert methods,
which are overloaded so as to accept data of any type. Each effectively converts a given
datum to a string and then appends or inserts the characters of that string to the string
buffer. The append method always adds these characters at the end of the buffer; the
insert method adds the characters at a specified point.
 StringBuffer Implemented Interfaces - Serializable, Appendable, CharSequence

StringBuffer Constructors
StringBuffer defines these four constructors:

 StringBuffer( )
 StringBuffer(int size)
 StringBuffer(String str)
 StringBuffer(CharSequence chars)

StringBuffer()

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.


Example:

StringBuffer buffer =newStringBuffer();


System.out.println(buffer.capacity());

Output:

16

StringBuffer(int capacity)

Constructs a string buffer with no characters in it and the specified initial capacity. The
parameters capacity of the initial capacity. This method
throws NegativeArraySizeException - if the capacity argument is less than 0.

Example:

StringBuffer buffer4 = new StringBuffer(20);


System.out.println(buffer4.capacity());
Output:

20

StringBuffer(String str)

Constructs a string buffer initialized to the contents of the specified string. The initial capacity of
the string buffer is 16 plus the length of the string argument. the parameter str the initial
contents of the buffer. Example:

StringBuffer buffer2 =newStringBuffer("javaguides");


System.out.println(buffer2.capacity());

Output:

26

Note that the capacity in the above example, it gives String length plus initial capacity.

StringBuffer(CharSequence seq)

Constructs a string buffer that contains the same characters as the specified CharSequence. The
initial capacity of the string buffer is 16 plus the length of the CharSequence argument.

If the length of the specified CharSequence is less than or equal to zero, then an empty buffer
of capacity 16 is returned.

Example:

CharSequencecharSequence=newStringBuilder("charSequence");
StringBuffer buffer3 =newStringBuffer(charSequence);
System.out.println(buffer3);

Output:

charSequence

StringBuffer APIs/Methods
A diagram shows a list of methods offered by StringBuffer
Class

append() methods
It has several overloaded versions:

1. StringBufferappend(boolean b) - Appends the string representation of the boolean


argument to the sequence.
2. StringBufferappend(char c) - Appends the string representation of the char
argument to this sequence.
3. StringBuffer append(char[] str) - Appends the string representation of the char
array argument to this sequence.
4. StringBuffer append(char[] str, int offset, int len) - Appends the string
representation of a subarray of the char array argument to this sequence.
5. StringBufferappend(CharSequence s) - Appends the specified CharSequence to this
sequence.
6. StringBufferappend(CharSequence s, int start, int end) - Appends a
subsequence of the specified CharSequence to this sequence.
7. StringBufferappend(double d) - Appends the string representation of the double
argument to this sequence.
8. StringBufferappend(float f) - Appends the string representation of the float
argument to this sequence.
9. StringBufferappend(int i) - Appends the string representation of the int argument
to this sequence.
10. StringBufferappend(long lng) - Appends the string representation of the long
argument to this sequence.
11. StringBufferappend(Object obj) - Appends the string representation of the Object
argument.
12. StringBufferappend(String str) - Appends the specified string to this character
sequence.
13. StringBufferappend(StringBuffer sb) - Appends the specified StringBuffer to this
sequence.
14. StringBufferappendCodePoint(int codePoint) - Appends the string representation
of the codePoint argument to this sequence.

Let's demonstrate each append() method with examples.


Example: This program demonstrates the usage of above 14 append methods.
publicclassAppendExample {
publicstaticvoidmain(String[] args) {
// 14 append overloaded methods

// Append String
StringBuffer buffer;
buffer =newStringBuffer().append("guides");
System.out.println("Append String :"+ buffer);

// Append char
buffer =newStringBuffer().append('c');
System.out.println("Append char :"+ buffer);

// Append Object
buffer =newStringBuffer().append(newObject().getClass());
System.out.println("Append Object :"+ buffer);

// Append chars
char[] chars = { 'j', 'a', 'v', 'a' };
buffer =newStringBuffer().append(chars);
System.out.println("Append chars :"+ buffer);

// Append charSequence
CharSequencecharSequence=newString("charSequence");
buffer =newStringBuffer().append(charSequence);
System.out.println("Append charSequence :"+ buffer);

// Append Double
buffer =newStringBuffer().append(10.0d);
System.out.println("Append Double :"+ buffer);

// Append Float
buffer =newStringBuffer().append(10.5f);
System.out.println("Append Float :"+ buffer);

// Append int
buffer =newStringBuffer().append(100);
System.out.println("Append int :"+ buffer);

// Append Boolean
buffer =newStringBuffer().append(true);
System.out.println("Append Boolean :"+ buffer);

// Append Long
buffer =newStringBuffer().append(1000);
System.out.println("Append Long :"+ buffer);

// Append stringbuffer
buffer =newStringBuffer().append(newStringBuffer("stringbuffer"));
System.out.println("Append stringbuffer :"+ buffer);

// Appends the string representation of a subarray of the char array


// argument to this sequence.
buffer =newStringBuffer().append(chars, 1, 3);
System.out.println("Appends the string representation of a "
+" subarray of the char array argument to this sequence. :"+ buffer);

// Appends a subsequence of the specified CharSequence to this sequence


buffer =newStringBuffer().append("javaguides", 0, 9);
System.out.println("Appends a subsequence of the specified "
+"CharSequence to this sequence. :"+ buffer);

// Appends the string representation of the codePoint argument to this


// sequence.
buffer =newStringBuffer().appendCodePoint(5);
System.out.println(
"Appends the string representation of the "
+"codePoint argument to this sequence. :"+ buffer);
}
}

Output:

Append String : guides


Append char : c
Append Object : class java.lang.Object
Append chars : java
Append charSequence :charSequence
Append Double : 10.0
Append Float : 10.5
Append int : 100
Append Boolean : true
Append Long : 1000
Append stringbuffer :stringbuffer
Appends the string representation of a subarray of the char array argument to this
sequence. : ava
Appends a subsequence of the specified CharSequence to this sequence. : javaguide
Appends the string representation of the codePoint argument to this sequence. :

capacity()

This method returns the current capacity. The capacity is the amount of storage available for
newly inserted characters, beyond which an allocation will occur.

Example: This simple program demonstrates the usage of capacity() method.

publicclassCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuffer builder =newStringBuffer("javaguides");
int capacity =builder.capacity();

// inital capacity
System.out.println(newStringBuffer().capacity());

// intial capacity 16 + number of characters in string


System.out.println("Capacity of the string :: "+ capacity);
}
}

Output:

16
Capacity of the string :: 26

charAt(int index)

Returns the char value at the specified index. An index ranges from zero to length() - 1. The
first char value of the sequence is at index zero, the next at index one, and so on, as for array
indexing.

To extract a single character from a String, you can refer directly to an individual character via
the charAt( ) method.

This method throws IndexOutOfBoundsException - if an index is negative or greater than or


equal to the length().

Example 1: Returns the char value at the specified index of this string. The first char value is at
index 0.

StringBuffer buffer =newStringBuffer("Welcome to string handling guide");


char ch1 =buffer.charAt(0);
char ch2 =buffer.charAt(5);
char ch3 =buffer.charAt(11);
char ch4 =buffer.charAt(20);
System.out.println("Character at 0 index is: "+ ch1);
System.out.println("Character at 5th index is: "+ ch2);
System.out.println("Character at 11th index is: "+ ch3);
System.out.println("Character at 20th index is: "+ ch4);

Output:
Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

Example 2: Example to throws IndexOutOfBoundsException - if an index is negative or greater


than or equal to the length().

publicstaticvoid charAtExample2() {
StringBuffer builder =newStringBuffer("Java Guides");
char ch1 =builder.charAt(builder.length());
System.out.println("character :: "+ ch1);

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index


out of range: 11
at java.lang.StringBuffer.charAt(StringBuffer.java:202)
at
com.javaguides.stringbuffer.methods.ChatAtExample.charAtExample2(ChatAtExample.java:2
6)
at com.javaguides.stringbuffer.methods.ChatAtExample.main(ChatAtExample.java:6)

Example 3: Example how to get a first and last character of the string

publicstaticvoid charAtExample3() {
StringBuffer buffer =newStringBuffer("Java Guides");
intstrLength=buffer.length() -1;
// Fetching first character
System.out.println("Character at 0 index is: "+buffer.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: "+buffer.charAt(strLength));

Output:

Character at 0 index is: J


Character at last index is: s

codePointAt(int index)

This method returns the character (Unicode code point) at the specified index. The index refers
to char values (Unicode code units) and ranges from 0 to length()- 1.
This method throws the IndexOutOfBoundsException - if the index argument is negative or
not less than the length of this string.

Example:

publicclassCodePointAtExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
intunicode=buffer.codePointAt(0);
System.out.println("the character (Unicode code point) at the specified index is ::
"+unicode);
}
}

Output;

the character (Unicode code point) at the specified index is :: 106

codePointBefore(int index)

This method returns the character (Unicode code point) before the specified index. The index
refers to char values (Unicode code units) and ranges from 1 to length.

This method throws the IndexOutOfBoundsException - if the index argument is negative or


not less than the length of this string.

Example:

publicclassCodePointBeforeExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
intunicode=buffer.codePointBefore(1);
System.out.println("the character (Unicode code point)"
+" at the before specified index is :: "+unicode);
}
}

Output:

the character (Unicode code point) at the before specified index is :: 106
codePointCount(int beginIndex, int endIndex)

This method returns the number of Unicode code points in the specified text range of this
String. The text range begins at the specified beginIndex and extends to the char at index
endIndex - 1.

This method throws IndexOutOfBoundsException - if the beginIndex is negative, or endIndex


is larger than the length of this String, or beginIndex is larger than endIndex.

Example:

publicclassCodePointCountExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
System.out.println("length of the string :: "+buffer.length());
intunicode=buffer.codePointCount(0, buffer.length());
System.out.println("the character (Unicode code point) "
+" at the specified index is :: "+unicode);
}
}

Output:

length of the string :: 10


the character (Unicode code point) at the specified index is :: 10

delete(int start, int end)

This method removes the characters in a substring of this sequence. The substring begins at the
specified start and extends to the character at index end - 1 or to the end of the sequence if no
such character exists. If start is equal to end, no changes are made.

Example: Example to delete substring 'java' from string 'javaguides' using delete() method.

publicclassDeleteExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");

// start with index and end with end -1


StringBuffersubBuffer=buffer.delete(0, 4);
System.out.println("Delete string 'java' from string
'javaguides' :"+subBuffer.toString());
}
}

Output:

Delete string 'java' from string 'javaguides' : guides

deleteCharAt(int index)

This method removes the char at the specified position in this sequence. This sequence is
shortened by one char.

This method throws StringIndexOutOfBoundsException - if the index is negative or greater


than or equal to the length().

Example: Example to delete character 'g' from string 'javaguides' using deleteCharAt() method.

public class DeleteCharAtExample {


public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("javaguides").deleteCharAt(4);
System.out.println("Delete char 'g' from string 'javaguides' : " + buffer);
}
}

Output:

Delete char 'g' from string 'javaguides' :javauides

ensureCapacity(int minimumCapacity)

Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less
than the argument, then a new internal array is allocated with greater capacity. The new capacity
is the larger of:

 The minimumCapacity argument.


 Twice the old capacity, plus 2.

Example: Example to ensure the capacity of the string buffer using ensureCapacity() method.

publicclassEnsureCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuffer builder =newStringBuffer();
builder.ensureCapacity(11);
System.out.println(builder.capacity());
builder.ensureCapacity(17);
System.out.println(builder.capacity());
}
}

Output:

16
34

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Characters are copied from this sequence into the destination character array dst.

Example: This is an example to copy characters from this sequence into the destination character
array dst.

publicclassGetCharsExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
char[] dst=newchar[buffer.length()];
buffer.getChars(0, buffer.length(), dst, 0);

for (charc :dst) {


System.out.println(c);
}
}
}

Output:

j
a
v
a
g
u
i
d
e
s
indexOf() methods

There two forms of indexOf() methods

 indexOf(String str) - Returns the index within this string of the first occurrence of
the specified substring.
 indexOf(String str, int fromIndex) - Returns the index within this string of the
first occurrence of the specified substring, starting at the specified index.

Example: This is a simple program to demonstrate 2 indexOf() methods with different


signatures.

publicclassIndexOfExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");

// method 1
int index =buffer.indexOf("guides");
System.out.println(index);

// method2
index =buffer.indexOf("guides", 3);
System.out.println(index);
}
}

Output:

4
4

insert() methods

insert() method has 12 overloaded versions:

1. StringBufferinsert(int offset, boolean b) - Inserts the string representation of


the boolean argument into this sequence.
2. StringBufferinsert(int offset, char c) - Inserts the string representation of the
char argument into this sequence.
3. StringBufferinsert(int offset, char[] str) - Inserts the string representation
of the char array argument into this sequence.
4. StringBufferinsert(int index, char[] str, int offset, int len) - Inserts
the string representation of a subarray of the str array argument into this sequence.
5. StringBufferinsert(int dstOffset, CharSequence s) - Inserts the specified
CharSequence into this sequence.
6. StringBufferinsert(int dstOffset, CharSequence s, int start, int end) -
Inserts a subsequence of the specified CharSequence into this sequence.
7. StringBufferinsert(int offset, double d) - Inserts the string representation of
the double argument into this sequence.
8. StringBufferinsert(int offset, float f) - Inserts the string representation of
the float argument into this sequence.
9. StringBufferinsert(int offset, int i) - Inserts the string representation of the
second int argument into this sequence.
10. StringBufferinsert(int offset, long l) - Inserts the string representation of the
long argument into this sequence.
11. StringBufferinsert(int offset, Object obj) - Inserts the string representation
of the Object argument into this character sequence.
12. StringBufferinsert(int offset, String str) - Inserts the string into this
character sequence.

Example: Below simple program demonstrate the usage of all insert() overloaded methods.

publicclassInsertExample {
publicstaticvoidmain(String[] args) {

// 12 insert overloaded method


StringBuffer builder =newStringBuffer("javaguides").insert(1,true);
System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, 'J');


System.out.println(builder.toString());

char[] chars = {'d','e','v','e','l','o','p','e','r'};


builder =newStringBuffer("javaguides").insert(4, chars);
System.out.println(builder.toString());

CharSequencecharSequence=newStringBuilder("J2EE/");
builder =newStringBuffer("javaguides").insert(0, charSequence);
System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, 100.0d);


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, 100.0f);


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, 100);


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, 100l);


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, newObject());


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, "ultimate");


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, chars, 0, chars.length);


System.out.println(builder.toString());

builder =newStringBuffer("javaguides").insert(0, charSequence, 0,


charSequence.length());
System.out.println(builder.toString());

}
}

Output:

jtrueavaguides
Jjavaguides
javadeveloperguides
J2EE/javaguides
100.0javaguides
100.0javaguides
100javaguides
100javaguides
java.lang.Object@15db9742javaguides
ultimatejavaguides
developerjavaguides
J2EE/javaguides

lastIndexOf() methods

lastIndexOf() method has 2 overloaded versions. Here are all of its forms:

1. int lastIndexOf(String str) - Returns the index within this string of the rightmost
occurrence of the specified substring.
2. int lastIndexOf(String str, int fromIndex) - Returns the index within this
string of the last occurrence of the specified substring.

Example: This example demonstrates the usage of 2 lastIndexOf() overloaded methods.

publicclassLastIndexOfExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");

// method1
intlastIndexOf=buffer.lastIndexOf("guides");
System.out.println(" last index of given string 'guides' in' "
+buffer.toString()+"' :: "+lastIndexOf);

// method 2
lastIndexOf=buffer.lastIndexOf("java", 3);
System.out.println(" last index of given string 'java' in' "
+buffer.toString()+"' :: "+lastIndexOf);
}
}

Output:

last index of given string 'guides' in' javaguides' :: 4


last index of given string 'java' in' javaguides' :: 0

length()

Returns the length (character count).

Example:

publicclassLengthExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
int length =buffer.length();
System.out.println(" length of the string '"+ buffer +"' is :: "+ length);
}
}

Output:

length of the string 'javaguides' is :: 10

replace(int start, int end, String str)

Replaces the characters in a substring of this sequence with characters in the specified String.
The substring begins at the specified start and extends to the character at index end - 1 or to
the end of the sequence if no such character exists. First, the characters in the substring are
removed and then the specified String is inserted at the start. (This sequence will be lengthened
to accommodate the specified String if necessary.)

Example: Example to replace the string "ja" with string "java" using replace() method.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("jaguides");

// replace ja with java- start index 0 and end index -1


StringBuffersubBuffer=buffer.replace(0, 2, "java");

System.out.println(subBuffer);
}
}

Output:

javaguides

reverse()

Causes this character sequence to be replaced by the reverse of the sequence.

Example: Example to reverse the given String "javaguides" using reverse() method.

publicclassReverseExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
StringBuffer reverse =buffer.reverse();
System.out.println("Reversed string :"+ reverse);
}
}

Output:

Reversed string :sediugavaj

setCharAt(int index, char ch)

The character at the specified index is set to ch.


Example: Example to set character at index 0 with character 'J' using setCharAt() method.

publicclassSetCharExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
buffer.setCharAt(0, 'J');
System.out.println(buffer.toString());
}
}

Output;

Javaguides

setLength(int newLength)

Sets the length of the character sequence.

Example: Example to reset the length of the StringBuffer using setLength() method.

publicclassSetLengthExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
System.out.println("Before set length to 0 :"+buffer.length());
buffer.setLength(0);
System.out.println("After set length to 0 :"+buffer.length());
}
}

Output:

Before set length to 0 : 10


After set length to 0 : 0

substring() methods

There are two overloaded versions of substring() method:

1. String substring(int start) - Returns a new String that contains a subsequence of


characters currently contained in this character sequence.
2. String substring(int start, int end) - Returns a new String that contains a
subsequence of characters currently contained in this sequence.

Example: This example demonstrates the usage of both overloaded versions


of substring() methods.

publicclassSubStringExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");

// substring from start to end


StringsubStr=buffer.substring(0, buffer.length());
System.out.println("substring from 0 to length of the string :"+subStr);

// print java
System.out.println(buffer.substring(0, 4));

// print guides
System.out.println(buffer.substring(4, buffer.length()));
}
}

Output:

substring from 0 to length of the string :javaguides


java
guides

toString()

Returns a string representing the data in this sequence.

Example:

publicclassToStringExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
System.out.println(buffer.toString());
}
}

Output:

javaguides
trimToSize()

Attempts to reduce storage used for the character sequence.

Example:

publicclassTrimToSizeExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
System.out.println(buffer.capacity());
buffer.trimToSize();
System.out.println(buffer.capacity());
}
}

Output:

27
11

StringBuilder 

Key Points About StringBuilder Class


 Java StringBuilder class is used to create mutable (modifiable) string. The
Java StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.
 A mutable sequence of characters. This class provides an API compatible
with StringBuffer, but with no guarantee of synchronization. This class is designed for
use as a drop-in replacement for StringBuffer in places where the string buffer was
being used by a single thread (as is generally the case).
 Where possible, it is recommended that this class be used in preference
to StringBuffer as it will be faster under most implementations.
 The principal operations on a StringBuilder are the append and insert methods, which
are overloaded so as to accept data of any type. Each effectively converts a given datum
to a string and then appends or inserts the characters of that string to the string builder.
The append method always adds these characters at the end of the builder; the insert
method adds the characters at a specified point.
 As we know instances of StringBuilder are not safe for use by multiple threads. If
such synchronization is required then it is recommended that StringBuffer is used.
StringBuilder Class Hierarchy 
The below class diagram shows the hierarchy of StringBuilder Class. All Implemented Interfaces:

Serializable, Appendable, CharSequence.

From the above class diagram, StringBuilder extends AbstractStringBuilder Class which


intern implements Appendable, CharSequence interface. Read more about hierarchy
on StringBuilder JavaDoc 8

StringBuilder Constructors
StringBuilder defines these four constructors:

 StringBuilder()
 StringBuilder(String str)
 StringBuilder(int capacity)
 StringBuilder(CharSequence seq)

StringBuilder()

Constructs a string builder with no characters in it and an initial capacity of 16 characters.


StringBuilder builder =newStringBuilder();
System.out.println(builder.capacity());

Output:

16

StringBuilder(String str)

Constructs a string builder initialized to the contents of the specified string. The initial capacity
of the string builder is 16 plus the length of the string argument.

Example:

StringBuilder builder2 =newStringBuilder("javaguides");


System.out.println(builder2.capacity());

Output:

26

StringBuilder(int capacity)

Constructs a string builder with no characters in it and an initial capacity specified by the
capacity argument.

Example:

StringBuilder builder4 =newStringBuilder(10);


System.out.println(builder4.capacity());

Output:

10
StringBuilder(CharSequence seq)

Constructs a string builder that contains the same characters as the specified CharSequence.
The initial capacity of the string builder is 16 plus the length of the CharSequence argument.

Example:

CharSequencecharSequence=newString("charSequence");
StringBuilder builder3 =newStringBuilder(charSequence);
System.out.println(builder3.capacity());

Output:

28

StringBuilder APIs/Methods

append() methods
It has several overloaded versions. Here are all of its forms:

1. StringBuilder append(boolean b) - Appends the string representation of the


boolean argument to the sequence.
2. StringBuilder append(char c) - Appends the string representation of the char
argument to this sequence.
3. StringBuilder append(char[] str) - Appends the string representation of the char
array argument to this sequence.
4. StringBuilder append(char[] str, int offset, int len) - Appends the string
representation of a subarray of the char array argument to this sequence.
5. StringBuilder append(CharSequence s) - Appends the specified CharSequence to
this sequence.
6. StringBuilder append(CharSequence s, int start, int end) - Appends a
subsequence of the specified CharSequence to this sequence.
7. StringBuilder append(double d) - Appends the string representation of the double
argument to this sequence.
8. StringBuilder append(float f) - Appends the string representation of the float
argument to this sequence.
9. StringBuilder append(int i) - Appends the string representation of the int
argument to this sequence.
10. StringBuilder append(long lng) - Appends the string representation of the long
argument to this sequence.
11. StringBuilder append(Object obj) - Appends the string representation of the
Object argument.
12. StringBuilder append(String str) - Appends the specified string to this character
sequence.
13. StringBuilder append(StringBuffer sb) - Appends the specified StringBuffer to
this sequence.
14. StringBuilder appendCodePoint(int codePoint) - Appends the string
representation of the codePoint argument to this sequence.

Let's demonstrate each append() method with examples.


Example: This program demonstrates the usage of above 14 append methods.

publicclassAppendExample {
publicstaticvoidmain(String[] args) {
// 13 append overloaded methods

StringBuilder builder;
// append String

// Append String
builder =newStringBuilder().append("guides");
System.out.println("Append string :"+ builder);

// Append char
builder =newStringBuilder().append('c');
System.out.println("Append char :"+ builder);
// Append Object
builder =newStringBuilder().append(newObject().getClass());
System.out.println("Append Object :"+ builder);

// Append chars
char[] chars = { 'j', 'a', 'v', 'a' };
builder =newStringBuilder().append(chars);
System.out.println("Append chars :"+ builder);

// Append charSequence
builder =newStringBuilder().append("charSequence");
System.out.println("Append charSequence :"+ builder);

// Append Double
builder =newStringBuilder().append(10.0d);
System.out.println("Append Double :"+ builder);
// Append Float
builder =newStringBuilder().append(10.5f);
System.out.println("Append Float :"+ builder);

// Append int
builder =newStringBuilder().append(100);
System.out.println("Append int :"+ builder);

// Append Boolean
builder =newStringBuilder().append(true);
System.out.println("Append Boolean :"+ builder);

// Append Long
builder =newStringBuilder().append(100000);
System.out.println("Append Long :"+ builder);

// Appends the specified StringBuffer to this sequence


builder =newStringBuilder().append(newStringBuffer("stringbuffer"));
System.out.println("Append StringBuffer :"+ builder);

// Appends the string representation of a subarray of the char array.


builder =newStringBuilder().append(chars, 1, 3);
System.out.println("Append subarray of the char array :"+ builder);

// Appends a subsequence of the specified CharSequence to this sequence.


builder =newStringBuilder().append("javaguides", 0, 9);
System.out.println("Append CharSequence :"+ builder);

// Appends the string representation of the codePoint argument to this


// sequence.
builder =newStringBuilder("javaguides").appendCodePoint(0);
System.out.println("Append appendCodePoint :"+ builder);

}
}

Output:

Append string : guides


Append char : c
Append Object : class java.lang.Object
Append chars : java
Append charSequence :charSequence
Append Double : 10.0
Append Float : 10.5
Append int : 100
Append Boolean : true
Append Long : 100000
Append StringBuffer :stringbuffer
Append subarray of the char array : ava
Append CharSequence :javaguide
Append appendCodePoint :javaguides

capacity()

This method returns the current capacity. The capacity is the amount of storage available for
newly inserted characters, beyond which an allocation will occur.

Example: This simple program demonstrates the usage of capacity() method.

publicclassCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuilderbuilder=newStringBuilder("javaguides");
int capacity =builder.capacity();

// inital capacity
System.out.println(newStringBuilder().capacity());

// intial capacity 16 + number of characters in string


System.out.println("Capacity of the string :: "+ capacity);
}
}

Output:

16
Capacity of the string :: 26

charAt(int index)

Returns the char value at the specified index. An index ranges from zero to length() - 1. The
first char value of the sequence is at index zero, the next at index one, and so on, as for array
indexing.

To extract a single character from a String, you can refer directly to an individual character via
the charAt( ) method.

This method throws IndexOutOfBoundsException - if an index is negative or greater than or


equal to a length().

Example 1: Returns the char value at the specified index of this string. The first char value is at
index 0.
StringBuilder builder =newStringBuilder("Welcome to string handling guide");
char ch1 =builder.charAt(0);
char ch2 =builder.charAt(5);
char ch3 =builder.charAt(11);
char ch4 =builder.charAt(20);
System.out.println("Character at 0 index is: "+ ch1);
System.out.println("Character at 5th index is: "+ ch2);
System.out.println("Character at 11th index is: "+ ch3);
System.out.println("Character at 20th index is: "+ ch4);

Output:

Character at 0 index is: W


Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

Example 2: Example how to get a first and last character of the string

publicstaticvoid charAtExample2() {
StringBuilder builder =newStringBuilder("Java Guides");
intstrLength=builder .length() -1;
// Fetching first character
System.out.println("Character at 0 index is: "+builder .charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: "+builder .charAt(strLength));

Output:

Character at 0 index is: J


Character at last index is: s

codePointAt(int index)

This method returns the character (Unicode code point) at the specified index. The index refers
to char values (Unicode code units) and ranges from 0 to length()- 1.

This method throws the IndexOutOfBoundsException - if the index argument is negative or


not less than the length of this string.

Example:

publicclassCodePointAtExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
intunicode=builder.codePointAt(0);
System.out.println("the character (Unicode code point) at the specified index is ::
"+unicode);
}
}

Output;

the character (Unicode code point) at the specified index is :: 106

codePointBefore(int index)

Returns the character (Unicode code point) before the specified index. The index refers to char
values (Unicode code units) and ranges from 1 to length().

Example:

publicclassCodePointBeforeExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
intunicode=builder.codePointBefore(1);
System.out.println("the character (Unicode code point) at the before specified index
is :: "+unicode);
}
}

Output:

the character (Unicode code point) at the before specified index is :: 106

codePointCount(int beginIndex, int endIndex)

This method returns the number of Unicode code points in the specified text range of this
String. The text range begins at the specified beginIndex and extends to the char at index
endIndex - 1.

This method throws IndexOutOfBoundsException - if the beginIndex is negative, or endIndex


is larger than the length of this String, or beginIndex is larger than endIndex.
Example:

publicclassCodePointCountExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
System.out.println("length of the string :: "+builder.length());
intunicode=builder.codePointCount(0, builder.length());
System.out.println("the character (Unicode code point) at the specified index is ::
"+unicode);
}
}

Output:

length of the string :: 10


the character (Unicode code point) at the specified index is :: 10

delete(int start, int end)

This method removes the characters in a substring of this sequence. The substring begins at the
specified start and extends to the character at index end - 1 or to the end of the sequence if no
such character exists. If start is equal to end, no changes are made.

Example: Example to delete substring 'java' from string 'javaguides' using delete() method.

publicclassDeleteExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");

// start with index and end with end -1


StringBuildersubBuilder=buffer.delete(0, 4);
System.out.println("Delete string 'java' from string
'javaguides' :"+subBuilder.toString());
}
}

Output:

Delete string 'java' from string 'javaguides' : guides


deleteCharAt(int index)

This method removes the char at the specified position in this sequence. This sequence is
shortened by one char.

This method throws StringIndexOutOfBoundsException - if the index is negative or greater


than or equal to a length().

Example: Example to delete character 'g' from string 'javaguides' using deleteCharAt() method.

public class DeleteCharAtExample {


public static void main(String[] args) {
StringBuilder subBuilder = new StringBuilder("javaguides").deleteCharAt(4);
System.out.println("Delete char 'g' from string 'javaguides' : " + subBuilder1);
}
}

Output:

Delete char 'g' from string 'javaguides' :javauides

ensureCapacity(int minimumCapacity)

Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less
than the argument, then a new internal array is allocated with greater capacity. The new capacity
is the larger of:

 The minimumCapacity argument.


 Twice the old capacity, plus 2.

Example: Example to ensure the capacity of string buffer using ensureCapacity() method.

publicclassEnsureCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder();
builder.ensureCapacity(11);
System.out.println(builder.capacity());
}
}

Output:
16

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Characters are copied from this sequence into the destination character array dst.

Example: Example to copy characters from this sequence into the destination character
array dst.

publicclassGetCharsExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
char[] dst=newchar[builder.length()];
builder.getChars(0, builder.length(), dst, 0);

for (charc :dst) {


System.out.println(c);
}
}
}

Output:

j
a
v
a
g
u
i
d
e
s

indexOf() methods

There two forms of indexOf() methods

 indexOf(String str) - Returns the index within this string of the first occurrence of
the specified substring.
 indexOf(String str, int fromIndex) - Returns the index within this string of the
first occurrence of the specified substring, starting at the specified index.
Example: This is a simple program to demonstrate 2 indexOf() methods with different
signatures.

publicclassIndexOfExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");

// method 1
int index =builder.indexOf("guides");
System.out.println(index);

// method2
index =builder.indexOf("guides", 3);
System.out.println(index);
}
}

Output:

4
4

insert() methods

insert() method has 12 overloaded versions. Here are all of its forms:

1. StringBuilder insert(int offset, boolean b) - Inserts the string representation


of the boolean argument into this sequence.
2. StringBuilder insert(int offset, char c) - Inserts the string representation of
the char argument into this sequence.
3. StringBuilder insert(int offset, char[] str) - Inserts the string representation
of the char array argument into this sequence.
4. StringBuilder insert(int index, char[] str, int offset, int len) - Inserts
the string representation of a subarray of the str array argument into this sequence.
5. StringBuilder insert(int dstOffset, CharSequence s) - Inserts the specified
CharSequence into this sequence.
6. StringBuilder insert(int dstOffset, CharSequence s, int start, int
end) - Inserts a subsequence of the specified CharSequence into this sequence.
7. StringBuilder insert(int offset, double d) - Inserts the string representation
of the double argument into this sequence.
8. StringBuilder insert(int offset, float f) - Inserts the string representation of
the float argument into this sequence.
9. StringBuilder insert(int offset, int i) - Inserts the string representation of
the second int argument into this sequence.
10. StringBuilder insert(int offset, long l) - Inserts the string representation of
the long argument into this sequence.
11. StringBuilder insert(int offset, Object obj) - Inserts the string representation
of the Object argument into this character sequence.
12. StringBuilder insert(int offset, String str) - Inserts the string into this
character sequence.

Example: Below simple program demonstrate the usage of all insert() overloaded methods.

publicclassInsertExample {
publicstaticvoidmain(String[] args) {

// 12 insert overloaded method


StringBuilder builder =newStringBuilder("javaguides").insert(1, true);
System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, 'J');


System.out.println(builder.toString());

char[] chars = { 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r' };
builder =newStringBuilder("javaguides").insert(4, chars);
System.out.println(builder.toString());

CharSequencecharSequence=newStringBuilder("J2EE/");
builder =newStringBuilder("javaguides").insert(0, charSequence);
System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, 100.0d);


System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, 100.0f);


System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, 100);


System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, 100l);


System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, newObject());


System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, "ultimate");


System.out.println(builder.toString());

builder =newStringBuilder("javaguides").insert(0, chars, 0, chars.length);


System.out.println(builder.toString());
builder =newStringBuilder("javaguides").insert(0, charSequence, 0,
charSequence.length());
System.out.println(builder.toString());
}
}

Output:

jtrueavaguides
Jjavaguides
javadeveloperguides
J2EE/javaguides
100.0javaguides
100.0javaguides
100javaguides
100javaguides
java.lang.Object@15db9742javaguides
ultimatejavaguides
developerjavaguides
J2EE/javaguides

lastIndexOf() methods

lastIndexOf() method has 2 overloaded versions. Here are all of its forms:

1. int lastIndexOf(String str) - Returns the index within this string of the rightmost
occurrence of the specified substring.
2. int lastIndexOf(String str, int fromIndex) - Returns the index within this
string of the last occurrence of the specified substring.

Example: This example demonstrates the usage of 2 lastIndexOf() overloaded methods.

publicclassLastIndexOfExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");

// method1
intlastIndexOf=builder.lastIndexOf("guides");
System.out.println(" last index of given string 'guides' in' "
+builder.toString() +"' :: "+lastIndexOf);

// method 2
lastIndexOf=builder.lastIndexOf("java", 3);
System.out.println(" last index of given string 'java' in' "
+builder.toString() +"' :: "+lastIndexOf);
}
}

Output:

last index of given string 'guides' in' javaguides' :: 4


last index of given string 'java' in' javaguides' :: 0

length()

Returns the length (character count).

Example:

publicclassLengthExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
int length =builder.length();
System.out.println(" length of the string '"+ builder +"' is :: "+ length);
}
}

Output:

length of the string 'javaguides' is :: 10

replace(int start, int end, String str)

Replaces the characters in a substring of this sequence with characters in the specified String.
The substring begins at the specified start and extends to the character at index end - 1 or to
the end of the sequence if no such character exists. First, the characters in the substring are
removed and then the specified String is inserted at the start. (This sequence will be lengthened
to accommodate the specified String if necessary.)

Example: Example to replace the string "ja" with string "java" using replace() method.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
StringBuilder buffer =newStringBuilder("jaguides");
// replace ja with java- start index 0 and end index -1
StringBuildersubBuffer=buffer.replace(0, 2, "java");

System.out.println(subBuffer);
}
}

Output:

javaguides

reverse()

Causes this character sequence to be replaced by the reverse of the sequence.

Example: Example to reverse the given String "javaguides" using reverse() method.

publicclassReverseExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
StringBuilder reverse =builder.reverse();
System.out.println("Reversed string :"+ reverse);
}
}

Output:

Reversed string :sediugavaj

setCharAt(int index, char ch)

The character at the specified index is set to ch.

Example: Example to set character at index 0 with character 'J' using setCharAt() method.

publicclassSetCharExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
builder.setCharAt(0, 'J');
System.out.println(builder.toString());
}
}

Output;

Javaguides

setLength(int newLength)

Sets the length of the character sequence.

Example: Example to reset the length of the StringBuilder using setLength() method.

publicclassSetLengthExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
System.out.println("Before set length to 0 :"+builder.length());
builder.setLength(0);
System.out.println("After set length to 0 :"+builder.length());
}
}

Output:

Before set length to 0 : 10


After set length to 0 : 0

substring() methods

There are two overloaded versions of substring() method:

1. String substring(int start) - Returns a new String that contains a subsequence of


characters currently contained in this character sequence.
2. String substring(int start, int end) - Returns a new String that contains a
subsequence of characters currently contained in this sequence.

Example: This example demonstrates the usage of both overloaded versions


of substring() methods.

publicclassSubStringExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
// substring from start to end
StringsubStr=buffer.substring(0, builder.length());
System.out.println("substring from 0 to length of the string :"+subStr);

// print java
System.out.println(builder.substring(0, 4));

// print guides
System.out.println(builder.substring(4, builder.length()));
}
}

Output:

substring from 0 to length of the string :javaguides


java
guides

toString()

Returns a string representing the data in this sequence.

Example:

publicclassToStringExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
System.out.println(builder.toString());
}
}

Output:

javaguides

trimToSize()

Attempts to reduce storage used for the character sequence.

Example:
publicclassTrimToSizeExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
System.out.println(builder.capacity());
builder.trimToSize();
System.out.println(builder.capacity());
}
}

Output:

27
11

String Constant Pool

1. Overview
In this post, we will learn the important topic that is String Constant Pool. The String object is the
most used class in the Java language and it is immutable. String objects are stored in a special memory
area known as String Constant Pool.

As we know that the string is immutable in Java because String objects are cached in String pool. Since
cached String literals are shared between multiple clients there is always a risk, where one client's action
would affect all another client. For example, if one client changes the value of String "demo" to "DEMO",
all other clients will also see that value. Since caching of String objects was important from performance
reason this risk was avoided by making String class Immutable.

As String is immutable it can safely share between many threads which is very important for multi-
threaded programming and to avoid any synchronization issues in Java, Immutability also
makes String instance thread-safe in Java, means you don't need to synchronize String operation
externally.

The main advantage of immutable objects is that

You can share duplicates by pointing them to a single instance.


String class in Java is final class because if String were not final,
you could create a subclass and have two strings that look alike when
"seen as Strings", but that are actually different.

2. What will we learn?


1. What is the String Constant Pool
2. String Interning
3. String object using the new keyword
4. How to manually intern the String?
5. Garbage Collection

2.1. What is the String Constant Pool

String objects are stored in a special memory area known as String Constant Pool. 

 In the above example, only one object will be created. Firstly JVM will not find any string object
with the value "Helloworld" in string constant pool so it will create a new object. After that it
will find the string with the value "Helloworld" in the pool, it will not create the new object
but will return the reference to the same instance.

 String s1 ="Helloworld";
 String s2 ="Helloworld";

String s5 ="Helloworld";

 The "Greeting" object is created by using the new keyword, this "Greeting" object stored in the
heap memory.

String s4 =newString("Greeting");
2.2. String Interning
As we know String is immutable in Java, the JVM can optimize the amount of memory allocated for
them by storing only one copy of each literal String in the pool. This process is called interning.

When we create a String variable and assign a value to it, the JVM searches the pool for a String of equal
value.

If found, the Java compiler will simply return a reference to its memory address, without allocating
additional memory.

If not found, it’ll be added to the pool (interned) and its reference will be returned.

Let’s write a small test to verify this:

privatestaticvoidstringPool(){
String s1 ="Helloworld";
String s2 ="Helloworld";
String s3 ="Greeting";
String s4 =newString("Greeting");
String s5 ="Helloworld";

// == operator used to check equality of reference variables.


if(s1 == s2){
System.out.println("Helloworld");
}

// s3 and s4 are not equal.


// s3 refer to string pool
// s4 refer to heap memory
if(s3 == s4){
System.out.println("equals");
}else{
System.out.println("not equals");
}
}

2.3. String object using the new keyword


What happens if we create String object using new keyword and where this object will get a store.

When we create a String via the new operator, the Java compiler will create a new object and store it in
the heap space reserved for the JVM.

Every String created like this will point to a different memory region with its own address.

Example:
String s3 ="Helloworld";
String s4 =newString("Greeting");

// s3 and s4 are not equal.


// s3 refer to string pool
// s4 refer to heap memory
if(s3 == s4){
System.out.println("equals");
}else{
System.out.println("not equals");
}

2.4. How to manually intern the String?


We can manually intern a String in the Java String Pool by calling the intern() method on the object we
want to intern.

Manually interning the String will store its reference in the pool, and the JVM will return this reference
when needed.

String s3 ="Helloworld";
String s4 =newString("Helloworld");

s4 = s4.intern();
// s3 and s4 are not equal.
// s3 refer to string pool
// s4 refer to heap memory
if(s3 == s4){
System.out.println("equals");
}else{
System.out.println("not equals");
}

2.5. Garbage Collection


Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it
can’t be expanded at runtime and is not eligible for garbage collection.

The risk of interning Strings in the PermGen (instead of the Heap) is that we can get
an OutOfMemory error from the JVM if we intern too many Strings.

From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the
JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced
Strings will be removed from the pool, thereby releasing memory.
3. Key Points why String is immutable in Java
1. String pool is possible only because String is immutable in Java, this way Java Runtime
saves a lot of java heap space because different String variables can refer to a same String
variable in the pool. This String Pool process we have seen in this post.
2. As String is immutable it can safely share between many threads which are very important for
multi-threaded programming and to avoid any synchronization issues in Java, Immutability also
makes String instance thread-safe in Java, means you don't need to synchronize String operation
externally.
3. Strings are used in java classloader and immutability provides security that correct class is getting
loaded by Classloader.
4. Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be
calculated again. This makes it a great candidate for a key in a Map and it’s processing is fast than
other HashMap key objects. This is why String is mostly used Object as HashMap keys.

Read this post to know how to write your own immutable class.

4. Conclusion
In this guide, we have seen how the JVM and the Java compiler optimize memory allocations for String
objects via the Java String Pool. We learned why the string is immutable or final in java.

String Best Practices

1. Overview
In this guide, I would like to explain the best practices for String Handling. This post belongs
to Java Best Practices Series category. Basically, this guide explains how effectively we can use
String in the day to day project work.

Check out beginners to expert String Tutorial/Guide at Java String API Guide/Tutorial

2. String Best Practices in Java


Let's discuss each String best practices with an example.

2.1. Use StringBuilder or StringBuffer for string


concatenations instead of the + operator
If you have more string concatenation operations, then prefer using StringBuilder object over
the + operator.

StringBuffer acts like StringBuilder, as it has the same methods except they are synchronized.
That means StringBuffer should be used in multi-threading context.

Let's write a simple program to demonstrate the performance of String, StringBuilder,


and StringBuffer.

publicclassPerformanceTest{

publicstaticvoidmain(String []args){
String str ="";
longstartTime=System.nanoTime();
for(inti=0 ; i<10 ; i++) {
str = str +i;
}
longendTime=System.nanoTime();
System.out.println(String.format("String opetation with
+ operator took [%d] nano seconds",(endTime-startTime)));
StringBuilder builder =newStringBuilder();
startTime=System.nanoTime();
for(inti=0;i<10;i++) {
builder.append(i);
}
endTime=System.nanoTime();
System.out.println(String.format("String opetation with
StringBuilder took [%d] nano seconds",(endTime-startTime)));

StringBufferstrBuffer=newStringBuffer();
startTime=System.nanoTime();
for(inti=0;i<10;i++) {
strBuffer.append(i);
}
endTime=System.nanoTime();
System.out.println(String.format("String opetation with
StringBuffer took [%d] nano seconds",(endTime-startTime)));

}
}

Output:

String opetation with + operator took [86037] nano seconds


String opetation with StringBuilder took [7928] nano seconds
String opetation with StringBuffer took [14165] nano seconds

From above result note that StringBuilder and StringBuffer for String concatenation are


more faster than String concatenation using + operator.

Eclipse Tip
Did you know, in Eclipse you can automatically convert '+' String concatenations to StringBuilder
append()s? It also picks the right append() depending on the type. Ctrl+1 is very handy!
2.2. Compare Two String by equals() Method Instead
== Operator
Refer below points while comparing string contents and string references.

1. use == to compare primitive e.g. boolean, int, char etc, while use equals() to compare
objects in Java. 
2. == return true if two references are of the same object. The result of equals() method
depends on overridden implementation. 
3. For comparing the content of two Strings use equals() instead of == equality operator. 

Simple program to demonstrate compare two string by equals() method instead == operator.

publicclassStringEqualsTest{

publicstaticvoidmain(String []args){
String s1 ="string";
String s2 ="string";
String s3 =newString("string");

System.out.println(" == opearator result for s1 and s2 :"+ (s1 == s2));


System.out.println(" == opearator result for s1 and s3 :"+ (s1 == s3));
System.out.println("equals() method result for s1 and s2 : "+ s1.equals(s2));

System.out.println("equals() method result for s1 and s3 : "+ s1.equals(s3));


}
}

Output:

== opearator result for s1 and s2 : true


== opearator result for s1 and s3 : false
equals() method result for s1 and s2 : true
equals() method result for s1 and s3 : true

2.3. Call .equals() Method on Known String Constants


Rather Than Unknown Variable
If you know some constants are fixed then use equals method on know constants rather than
unknown variable. Some time variable may contain null and if you are calling equals method
on null contains variable leads to null pointer exception.

publicclassConstantEqualsTest{
privatestaticfinalStringCONSTANT="constant value";

publicstaticvoidmain(String []args){
processString("constant value");

}
privatestaticvoidprocessString(Stringstr){
if(CONSTANT.equals(str)){
System.out.println("CONSTANT.equals(string): "
+CONSTANT.equals(str));
}
}
}

Output:

CONSTANT.equals(string): true

2.4. Prefer switch( ) Statement Instead of Multiple if-


else-if
Java 1.7 introduces the switch statement for Strings. If there is the scenario to compare multiple strings
then use switch over multiple if-else-if statements. Here is a comparison of the performance of these two
approaches.

publicclassTest {
publicstaticfinalStringCONSTANT="someConstant";

publicstaticvoidmain(String[] args) {
Testtest=newTest();
longstartTime=System.nanoTime();
test.convertStringToIntegerWithSwitch("FOUR");
longendTime=System.nanoTime();
System.out.println(String.format("String comparison with Switch took [%d] nano seconds.",(endTime-startTime)));

startTime=System.nanoTime();
test.convertStringToIntegerWithIf("FOUR");
endTime=System.nanoTime();
System.out.println(String.format("String comparison with If took [%d] nano seconds.",(endTime-startTime)));
}

privateintconvertStringToIntegerWithSwitch(StringstringNumber) {
switch(stringNumber) {
case"ZERO":
return0;
case"ONE":
return1;
case"TWO":
return2;
case"THREE":
return3;
default:
return-1;
}
}

privateintconvertStringToIntegerWithIf(StringstringNumber) {
if("ZERO".equals(stringNumber)) {
return0;
} elseif("ONE".equals(stringNumber)) {
return1;
} elseif("TWO".equals(stringNumber)) {
return2;
} elseif("THREE".equals(stringNumber)) {
return3;
} else {
return-1;
}
}
}

That means using switch we can improve the performance, from the above result it is clear that
comparison with if-else takes double time than the time taken by the switch. This example has
only 4 comparisons, if there are more than 4 if-else then switch will give a better result than if-
else.

2.5. Use String.valueOf() Instead of toString()


If object needs to be converted to string then the result of obj.toString() and String.valueOf(obj) will
be same but String.valueOf() is null safe, means it will never throw NullPointerException.

Testtest=null;
// Below statement will not throw NPE
System.out.println(String.valueOf(test));
// Next statement will throw NPE
System.out.println(test.toString())

means if we are sure the object will never be null then we should always
use toString() otherwise, String.valueOf() is preferable.

2.6. Use String Utility Classes


Prefer StringUtility classes from different popular libraries because these Utility classes are tested and
well-known libraries.

I have created my own String Utility classes and have used in tons of projects.
You should refer these utility classes or methods:

1. Java String Utility Class

1. 27 Useful String Utility Methods

2.7 Avoid Duplicate Literals


Code containing duplicate String literals can usually be improved by declaring the String as a constant
field.

Example:

privatevoidbar() {
String howdy="Howdy"
buz(howdy);
buz(howdy);
}

privatevoidbuz(String x) {}
// Better
privatestaticfinalStringHOWDY="Howdy";
privatevoidbar() {
buz(HOWDY);
buz(HOWDY);
}
privatevoidbuz(String x) {}

Other Basic String Best Practices


Unnecessary Case Change
Using equalsIgnoreCase() is faster than using toUpperCase() or toLowerCase().equals()

Append Character With Char


Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.

Example:

StringBuffer sb =newStringBuffer();
sb.append("a"); // avoid this
StringBuffer sb =newStringBuffer();
sb.append('a'); // use this instead

Consecutive Appends Should Reuse


Consecutive calls to StringBuffer/StringBuilder.append should be chained, reusing the target
object. This can improve the performance by producing a smaller bytecode, reducing overhead and
improving inlining. A complete analysis can be found here

Example:

String foo ="";


StringBufferbuf=newStringBuffer();
buf.append("Hello"); // poor
buf.append(foo);
buf.append("World");

StringBufferbuf=newStringBuffer();
buf.append("Hello").append(foo).append("World"); // good

Avoid StringBuffer Field


StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if
held within objects with long lifetimes.
Example:

publicclassFoo {
privateStringBuffer buffer;
// potential memory leak as an instance variable;
}

Unnecessary Conversion Temporary


Avoid unnecessary temporaries when converting primitives to Strings.

Example:

publicStringconvert(int x) {
// this wastes an object
String foo =newInteger(x).toString();
// this is better
returnInteger.toString(x);
}

Let me know if you know any other best practices for Strings in Java.

Eclipse Tip - Use MessageFormatter


Do you prefer your strings concatenations 'printf' style? Eclipse can do it for you automatically!.

3. Conclusion
This post explained the best practices for String API. Learn more Java best practices on Java
Best Practices Series. Let us know if you know any other best practices for String Handling in
Java.
String Special Operations
As we know strings are a common and important part of programming, Java has added special
support for several string operations within the syntax of the language. These operations include
the automatic creation of new String instances from string literals, concatenation of multiple
String objects by use of the + operator, and the conversion of other data types to a string
representation. There are explicit methods available to perform all of these functions, but Java
does them automatically as a convenience for the programmer and to add clarity.

Let's discuss below Special String Operations with examples.

 String Literals
 String Concatenation
 String Concatenation with Other Data Types
 String Conversion and toString( )

Learn complete Java programming language at Java Tutorial | Learn Java Programming with
Examples

String Literals
Java String literal is created by using double quotes. For Example:

String s="javaguides";

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 string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";
String s2="Welcome";//will not create new instance

In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will return
the reference to the same instance.

String objects are stored in a special memory area known as string constant pool.
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception to
this rule is the + operator, which concatenates two strings, producing a String object as the
result. This allows you to chain together a series of + operations. For example, the following
fragment concatenates three strings:

String age ="9";


String s ="He is "+ age +" years old.";
System.out.println(s);

This displays the string "He is 9 years old."

One practical use of string concatenation is found when you are creating very long strings.
Instead of letting long strings wrap around within your source code, you can break them into
smaller pieces, using the + to concatenate them. Here is an example:

// Using concatenation to prevent long lines.


classConCat {
publicstaticvoidmain(Stringargs[]) {
StringlongStr="This could have been "+"a very long line that would have "
+"wrapped around. But string concatenation "+"prevents this.";
System.out.println(longStr);
}
}

String provides String java.lang.String.concat(String str) method to concatenates the specified


string to the end of this string.

String java.lang.String.concat(String str)

This method returns a string that represents the concatenation of this object's characters
followed by the string argument's characters.

Example:

publicclassConcatExmaple {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
str =str.concat(".net");
System.out.println("Concatenates the specified string to the end of this
string :"+ str);
System.out.println("cares".concat("s"));
System.out.println("to".concat("get"));
}
}

Output:

Concatenates the specified string to the end of this string : javaguides.net


caress
toget

String Concatenation with Other Data Types


You can concatenate strings with other types of data. For example, consider this slightly
different version of the earlier example:

int age =9;


String s ="He is "+ age +" years old.";
System.out.println(s);

In this case, age is an int rather than another String, but the output produced is the same as
before. This is because the int value in age is automatically converted into its string
representation within a String object. This string is then concatenated as before. The compiler
will convert an operand to its string equivalent whenever the other operand of the + is an
instance of String.

Be careful when you mix other types of operations with string concatenation expressions,
however. You might get surprising results. Consider the following:

String s ="four: "+2+2;


System.out.println(s);

This fragment displays

four: 22

rather than the

four: 4
that you probably expected. Here’s why. Operator precedence causes the concatenation of
"four" with the string equivalent of 2 to take place first. This result is then concatenated with the
string equivalent of 2 a second time. To complete the integer addition first, you must use
parentheses, like this:

String s ="four: "+ (2+2);

Now s variable contains the string "four: 4".

String Conversion and toString( )


When Java converts data into its string representation during concatenation, it does so by
calling one of the overloaded versions of the string conversion method valueOf( ) defined by
String.

valueOf( ) is overloaded for all the primitive types and for type Object. For the primitive types,
valueOf( ) returns a string that contains the human-readable equivalent of the value with which
it is called. For objects, valueOf( ) calls the toString( ) method on the object.

Let's understand the usage of valueOf() and toString() methods with examples.

valueOf( )

The valueOf( ) method converts data from its internal format into a human-readable form.

The Java string valueOf() method converts different types of values into a string. By the help of
string valueOf() method, you can convert int to string, long to string, boolean to string, character
to string, float to a string, double to string, object to string and char array to string.

Here are a few of its forms and the signature or syntax of string valueOf() method is given
below:

publicstaticStringvalueOf(boolean b)
publicstaticStringvalueOf(char c)
publicstaticStringvalueOf(char[] c)
publicstaticStringvalueOf(inti)
publicstaticStringvalueOf(long l)
publicstaticStringvalueOf(float f)
publicstaticStringvalueOf(double d)
publicstaticStringvalueOf(Object o)

Example: Let's see an example where we are converting all primitives and objects into strings.
publicclassStringValueOfExample5 {
publicstaticvoidmain(String[] args) {
boolean b1=true;
byte b2=11;
shortsh=12;
inti=13;
long l =14L;
float f =15.5f;
double d =16.5d;
charchr[]={'j','a','v','a'};
StringValueOfExample5 obj=newStringValueOfExample5();
String s1 =String.valueOf(b1);
String s2 =String.valueOf(b2);
String s3 =String.valueOf(sh);
String s4 =String.valueOf(i);
String s5 =String.valueOf(l);
String s6 =String.valueOf(f);
String s7 =String.valueOf(d);
String s8 =String.valueOf(chr);
String s9 =String.valueOf(obj);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
System.out.println(s8);
System.out.println(s9);
}
}

Output:

true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55

toString()

let’s examine the toString( ) method, because it is the means by which you can determine the
string representation for objects of classes that you create.
Every class implements toString( ) because it is defined by Object. However, the default
implementation of toString( ) is seldom sufficient. For most important classes that you create,
you will want to override toString( ) and provide your own string representations.

Fortunately, this is easy to do. The toString( ) method has this general form:

StringtoString( )

To implement toString( ), simply return a String object that contains the human-readable string
that appropriately describes an object of your class.

For example, they can be used in print( ) and println( ) statements and in concatenation
expressions.

The following program demonstrates this by overriding toString( ) for the Box class:

classBox {
double width;
double height;
double depth;

Box(doublew, doubleh, doubled) {


width = w;
height = h;
depth = d;
}

publicStringtoString() {
return"Dimensions are "+ width +" by "+ depth +" by "+ height +".";
}
}

classtoStringDemo {
publicstaticvoidmain(Stringargs[]) {
Box b =newBox(10, 12, 14);
String s ="Box b: "+ b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}

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( ).
String Comparison Methods
String Comparison Methods Overview
The String class includes a number of methods that compare strings or substrings within strings.
Several are examined in this post.

 equals(Object anObject)
 equalsIgnoreCase(String str)
 regionMatches( )
 startsWith( ) methods
 endsWith( ) methods
 equals( ) Versus ==
 compareTo( )
 compareToIgnoreCase(String str)

String Comparison Methods with Examples

equals(Object anObject)

To compare two strings for equality, use equals( ). It has this general form:

booleanequals(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.

Example 2: This example demonstrate the usage of equals() method.

publicclassEqualsExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
String str1 ="javaguides";
String str3 ="javatutorial";
boolean equal =str.equals(str1);
System.out.println(" Is both string are equal :: "+ equal);
}

Output:
Is both string are equal :: true

equalsIgnoreCase(String str)

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:

booleanequalsIgnoreCase(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.

Example 3: This example demonstrate the usage of equalsIgnoreCase() method.

publicclassEqualsIgnoreCaseExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
boolean equal =str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: "+ equal);
}
}

Output:

Strings are equal :: true

Here is an example that demonstrates both equals( ) and equalsIgnoreCase( ):

// Demonstrate equals() and equalsIgnoreCase().


classequalsDemo {
publicstaticvoidmain(Stringargs[]) {
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));
}
}

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

regionMatches() methods

There are two types of regionMatches() methods.

 regionMatches(booleanignoreCase, int toffset, String other, int


ooffset, int len) - Tests if two string regions are equal.
 regionMatches(int toffset, String other, int ooffset, int len) - Tests if
two string regions are equal.

Example: Example to tests if two string regions are equal.

publicclassRegionMatchesExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr="guides";
boolean b =str.regionMatches(0, subStr, str.length(), str.length());
boolean b1 =str.regionMatches(true, 0, str, 0, str.length());
System.out.println(b);
System.out.println(b1);
}
}

Output:

false
true

startsWith() methods

There are two forms of startsWith() methods.

 startsWith(String prefix) - Tests if this string starts with the specified prefix.
 booleanstartsWith(String prefix, int toffset) - Tests if the substring of this
string beginning at the specified index starts with the specified prefix.

The startsWith( ) method determines whether a given String begins with a specified string.
Example: This is complete example to demonstrate the usage of startsWith() methods.
publicclassStartsWithExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
booleanstartWith=str.startsWith("ja");
System.out.println("startWith :: "+startWith);

// Remember index starts from 0


booleanstartWithOffset=str.startsWith("guides", 4);
System.out.println("startWithOffset :: "+startWithOffset);
}
}

Output:

startWith :: true
startWithOffset :: true

endsWith(String suffix)

This method tests if this string ends with the specified suffix. Returns true if the character
sequence represented by the argument is a suffix of the character sequence represented by this
object; false otherwise.

Example:

publicclassEndsWithExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr="guides";
booleanendsWith=str.endsWith(subStr);
System.out.println(str +"endsWith"+subStr+" :: "+endsWith);
}
}

Output:

javaguidesendsWithguides :: true

It is important to understand that the equals( ) method and the == operator perform two
different operations.

 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 ==
classEqualsNotEqualTo {
publicstaticvoidmain(Stringargs[]) {
String s1 ="Hello";
String s2 =newString(s1);
System.out.println(s1 +" equals "+ s2 +" ->"+ s1.equals(s2));
System.out.println(s1 +" == "+ s2 +" ->"+ (s1 == s2));
}
}

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

compareTo(String anotherString)

Often, it is not enough to simply know whether two strings are identical. For sorting
applications, you need to know which is less than, equal to, or greater than the next. A string is
less than another if it comes before the other in dictionary order. A string is greater than
another if it comes after the other in dictionary order.

The method compareTo( ) serves this purpose. It is specified by the Comparable interface,


which String implements. It has this general form:

intcompareTo(String str)

Here, str is the String being compared with the invoking String. The result of the comparison is
returned as values meaning:

 Less than zero The invoking string is less than str.


 Greater than zero The invoking string is greater than str.
 Zero The two strings are equal.

Example 1: Here is a sample program that sorts an array of strings. The program
uses compareTo( ) to determine sort ordering for a bubble sort:
// A bubble sort for Strings.
publicclassCompareToSecondExample {
staticStringarr[] = { "Now", "is", "the", "time",
"for", "all", "good", "men", "to", "come", "to", "the", "aid",
"of", "their", "country" };

publicstaticvoidmain(Stringargs[]) {
for (int j =0; j <arr.length; j++) {
for (inti= j +1; i<arr.length; i++) {
if (arr[i].compareTo(arr[j]) <0) {
String t =arr[j];
arr[j] =arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

The output of this program is the list of words:

Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to

As you can see from the output of this example, compareTo( ) takes into account uppercase
and lowercase letters. The word "Now" came out before all the others because it begins with an
uppercase letter, which means it has a lower value in the ASCII character set.

Example 2: compareTo method return different values example

String s1 ="Hello World";


String s2 ="Hello World";
String s3 ="Java";
String s4 ="Guides";
System.out.println(s1.compareTo(s2));// 0 because both are equal
System.out.println(s1.compareTo(s3));// -2 because "H" is 2 times lower than
"J"
System.out.println(s1.compareTo(s4));// 1 because "G" is 1 times greater than
"H"

Output:

0
-2
1

Example 3: Compare string with black or empty string using compareTo() method. Note that
compare with empty string, returns length of the string.

String s1 ="hello";
String s2 ="";
String s3 ="me";

// compare with empty string, returns length of the string


System.out.println(s1.compareTo(s2));

// If first string is empty, result would be negative


System.out.println(s2.compareTo(s3));

Output:

5
-2

compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences. This method returns an
integer whose sign is that of calling compareTo with normalized versions of the strings where
case differences have been eliminated by
calling Character.toLowerCase(Character.toUpperCase(character)) on each character.

Example:

String s1="Hello World";


String s2="hello world";
String s3="Java";
String s4="java";
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));
Output:

0
0

This method returns a negative integer, zero, or a positive integer as the specified String is
greater than, equal to, or less than this String, ignoring case considerations.

String Methods for Character Extraction


The String class provides a number of ways in which characters can be extracted from a String
object. In this post we will see several of character extraction methods . Although the characters
that comprise a string within a String object cannot be indexed as if they were a character array,
many of the String methods employ an index (or offset) into the string for their operation. Like
arrays, the string indexes begin at zero.

String Character Extraction Methods


 charAt()
 getChars()
 getBytes()
 toCharArray()

charAt(int index)

To extract a single character from a String, you can refer directly to an individual character via
the charAt( ) method.

Example 1: Returns the char value at the specified index of this string. The first char value is at
index 0.

String str ="Welcome to string handling guide";


char ch1 =str.charAt(0);
char ch2 =str.charAt(5);
char ch3 =str.charAt(11);
char ch4 =str.charAt(20);
System.out.println("Character at 0 index is: "+ ch1);
System.out.println("Character at 5th index is: "+ ch2);
System.out.println("Character at 11th index is: "+ ch3);
System.out.println("Character at 20th index is: "+ ch4);

Output:
Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

Example 2: Throws IndexOutOfBoundsException - if the index argument is negative or not less


than the length of this string.

String str ="Java Guides";


char ch1 =str.charAt(str.length() +1);
System.out.println("character :: "+ ch1);

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String


index out of range: 12
at java.lang.String.charAt(String.java:658)
at
com.javaguides.strings.methods.ChatAtExample.charAtExample2(ChatAtExample.java
:26)
at com.javaguides.strings.methods.ChatAtExample.main(ChatAtExample.java:6)

Example 3: How to get first and last character of the string

String str ="Java Guides";


intstrLength=str.length();
// Fetching first character
System.out.println("Character at 0 index is: "+str.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: "+str.charAt(strLength-1));

Output;

Character at 0 index is: J


Character at last index is: s

getChars()

If you need to extract more than one character at a time, you can use the getChars( ) method. It
has this general form:

voidgetChars(intsourceStart, intsourceEnd, char target[ ], inttargetStart)


Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies
an index that is one past the end of the desired substring. Thus, the substring contains the
characters from sourceStart through sourceEnd–1. The array that will receive the characters is
specified by target. The index within target at which the substring will be copied is passed in
targetStart. Care must be taken to assure that the target array is large enough to hold the
number of characters in the specified substring.

The following program demonstrates getChars( ):

classgetCharsDemo {
publicstaticvoidmain(Stringargs[]) {
String s ="This is a demo of the getChars method.";
int start =10;
int end =14;
charbuf[] =newchar[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

Here is the output of this program:

demo

getBytes()

There are four versions of getBytes() methods. There is an alternative to getChars( ) that stores
the characters in an array of bytes. byte[] getBytes() - Encodes this String into a sequence of
bytes using the platform's default charset, storing the result into a new byte array.

byte[] getBytes(Charset charset) - Encodes this String into a sequence of bytes using the given
charset, storing the result into a new byte array.

void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) - Deprecated.

byte[] getBytes(String charsetName) - Encodes this String into a sequence of bytes using the
named charset, storing the result into a new byte array.

Let's write an example to demonstrate all the getBytes() methods.

publicclassGetBytesExamples {
publicstaticvoidmain(String[] args) throwsUnsupportedEncodingException {
String str ="javaguides";

// Encodes this String into a sequence of bytes using the platform's


// default charset, storing the result into a new byte array.
byte[] bs =str.getBytes();
for (byte b: bs) {
System.out.println(b);
}

// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs1 =str.getBytes(Charset.forName("UTF-8"));
for (byte b: bs1) {
System.out.println(b);
}

// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs2 =str.getBytes("UTF-8");
for (byte b: bs2) {
System.out.println(b);
}

byte[] dest=newbyte[str.length()];
str.getBytes(0, str.length(), dest, 0);
for (byte b:dest) {
System.out.println(b);
}

}
}

toCharArray()

Converts this string to a new character array.

Example: This is a complete example to demonstrate the usage of toCharArray() method.

publicclassToCharArrayExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
char[] characters =str.toCharArray();
for (charc : characters) {
System.out.println(c);
}

}
}

Ouput:

j
a
v
a
g
u
i
d
e
s

String Searching Methods


String Searching Methods Overview
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

intindexOf(intch)

To search for the last occurrence of a character, use

intlastIndexOf(intch)

Here, ch is the character being sought.

To search for the first or last occurrence of a substring, use

intindexOf(String str)
intlastIndexOf(String str)

Here, str specifies the substring.


You can specify a starting point for the search using these forms:

intindexOf(intch, intstartIndex)
intlastIndexOf(intch, intstartIndex)
intindexOf(String str, intstartIndex)
intlastIndexOf(String str, intstartIndex)

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 a String:

// Demonstrate indexOf() and lastIndexOf().


classindexOfDemo {
publicstaticvoidmain(Stringargs[]) {
String s ="Now is the time for all good men "+"to come to the aid of their
country.";
System.out.println(s);
System.out.println("indexOf(t) = "+s.indexOf('t'));
System.out.println("lastIndexOf(t) = "+s.lastIndexOf('t'));
System.out.println("indexOf(the) = "+s.indexOf("the"));
System.out.println("lastIndexOf(the) = "+s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = "+s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = "+s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = "+s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = "+s.lastIndexOf("the", 60));
}
}

Here is the output of this program:

Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

Let's understand indexOf() and lastIndexOf() methods and their different forms in depth.

String Searching Methods with Examples


indexOf()

There are 4 types of an indexOf method in java. The signature of indexOf methods are given
below:

 indexOf(int ch) - Returns the index within this string of the first occurrence of the
specified character.
 indexOf(int ch, int fromIndex) - Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
 indexOf(String str) - Returns the index within this string of the first occurrence of
the specified substring.
 indexOf(String str, int fromIndex) - Returns the index within this string of the
first occurrence of the specified substring, starting at the specified index.

Example: This program demonstrates the example of all the 4 indexOf() methods.

publicclassIndexOfExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";

// method 1
int index =str.indexOf("java");
System.out.println(index);

// Remember index starts with 0 so count from 0


System.out.println("index of guides :: "+str.indexOf("guides"));

System.out.println(" index of des :: "+str.indexOf("des"));

// method 2
System.out.println(str.indexOf('s'));

// method 3
System.out.println(str.indexOf('g', 0));

// method 4
System.out.println(str.indexOf("guides", 3));
}
}

Output:

0
index of guides :: 4
index of des :: 7
9
4
4
lastIndexOf() methods

There are 4 types of a lastIndexOf method in java. The signature of lastIndexOf methods are


given below:

 lastIndexOf(int ch) - Returns the index within this string of the last occurrence of
the specified character.
 lastIndexOf(int ch, int fromIndex) - Returns the index within this string of the
last occurrence of the specified character, searching backward starting at the specified
index.
 lastIndexOf(String str) - Returns the index within this string of the last occurrence
of the specified substring.
 lastIndexOf(String str, int fromIndex) - Returns the index within this string of
the last occurrence of the specified substring, searching backward starting at the
specified index.

The main usage of lastIndexOf( ) - Searches for the last occurrence of a character or
substring.
Example: This program demonstrate the usage of all 4 lastIndexOf() methods.

publicclassLastIndexOfExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";

// method1
intlastIndexOf=str.lastIndexOf('s');
System.out.println(" last index of given character 's' in' "
+""+ str+"' :: "+lastIndexOf);

// method 2
lastIndexOf=str.lastIndexOf("guides");
System.out.println(" last index of given string 'guides' in' "
+""+ str+"' :: "+lastIndexOf);

// method 3
lastIndexOf=str.lastIndexOf("guides", 4);
System.out.println(" last index of guides in given string"
+""+ str+" and from index "+lastIndexOf);

// method 4
lastIndexOf=str.lastIndexOf('g', str.length());
System.out.println(" last index of given char :: "+lastIndexOf);
}
}

Output:
last index of given character 's' in' javaguides' :: 9
last index of given string 'guides' in' javaguides' :: 4
last index of guides in given stringjavaguides and from index 4
last index of given char :: 4

String Modifying Methods


String Modifying Methods Overview
As we know that objects are immutable, whenever you want to modify a String, you must either
copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new
copy of the string with your modifications complete. A sampling of these methods are described
in this post.

In this post, we will discuss below methods for modifying a String objects.

 substring()
 concat()
 replace()
 replaceAll()
 replaceFirst()
 trim()

String Modifying Methods with


Examples
substring() methods

We can extract a substring using substring( ) methods. There are two forms of substring()
methods.

 substring(int beginIndex) - Returns a string that is a substring of this string.


 substring(int beginIndex, int endIndex) - Returns a string that is a substring of this string.

These methods throws IndexOutOfBoundsException- if beginIndex is negative or larger than the


length of this String object.
Example: This is complete example to demonstrate the usage of both substring() methods.
publicclassSubStringExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";

// substring from start to end


StringsubStr=str.substring(0, str.length());
System.out.println("substring from 0 to length of the string :"+subStr);

subStr=str.substring(4);
System.out.println("Sub string starts from index 4 :"+subStr);

// Remember index starts from 0


System.out.println(str.substring(1));

System.out.println("unhappy".substring(2));
System.out.println("Harbison".substring(3));
System.out.println("emptiness".substring(8));
}
}

Output:

substring from 0 to length of the string :javaguides


Sub string starts from index 4 : guides
avaguides
happy
bison
s

concat(String str)

We can concatenate two strings using concat( ). The concat() method concatenates the specified
string to the end of this string.

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

Example:

publicclassConcatExmaple {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
str =str.concat(".net");
System.out.println("Concatenates the specified string to the end of this
string :"+ str);

System.out.println("cares".concat("s"));
System.out.println("to".concat("get"));
}
}

Output:

Concatenates the specified string to the end of this string : javaguides.net


caress
toget

replace( ) methods

The replace( ) method has two forms. The first replaces all occurrences of one character in the
invoking string with another character. It has the following general form:

Stringreplace(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.

The second form of replace( ) replaces one character sequence with another. It has this general
form:

Stringreplace(CharSequence original, CharSequence replacement)

Example: This is complete example to demonstrate the usage of replace() methods.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replace('a', 'b');
System.out.println("replace char 'a' with char 'b' from given
string :"+subStr);

subStr=str.replace("guides", "tutorials");
System.out.println("replace guides with tutorials from given
string :"+subStr);
subStr=str.replaceAll("[a-z]", "java");
System.out.println(subStr);

subStr=str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}

Output:

replace char 'a' with char 'b' from given string :jbvbguides
replace guides with tutorials from given string :javatutorials
javajavajavajavajavajavajavajavajavajava
javaavaguides

replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given
replacement.

Example: This is complete example to demonstrate the usage of replaceAll() methods.

publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replaceAll("[a-z]", "java");
System.out.println(subStr);
}
}

Output:

javajavajavajavajavajavajavajavajavajava

replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the
given replacement.

Example: This is complete example to demonstrate the usage of replaceFirst() methods.


publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}

Output:

javaavaguides

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:

Stringtrim( )

Here is an example:

String s =" Hello World ".trim();

This puts the string "Hello World" into s.

The trim( ) method is quite useful when you process user commands. For example, the following
program prompts the user for the name of a state and then displays that state’s capital. It uses
trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered
by the user.

// Using trim() to process commands.


importjava.io.*;
classUseTrim {
publicstaticvoidmain(Stringargs[]) throwsIOException {
// create a BufferedReader using System.in
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str =br.readLine();
str =str.trim(); // remove whitespace
if (str.equals("Illinois"))
System.out.println("Capital is Springfield.");
elseif (str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
elseif (str.equals("California"))
System.out.println("Capital is Sacramento.");
elseif (str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while(!str.equals("stop"));
}
}

Example 2: This is complete example to demonstrate the usage of trim() method.

publicclassTrimExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.trim();
System.out.println("trim the space from given string :"+subStr);
}
}

Output:

trim the space from given string :javaguides

 System Class using gc(), exit()

Java System gc() Method


The gc() method of System class runs the garbage collector. Through this method, JVM
makes best effort to reuse the memory of discarded objects for quick reuse.

Syntax
1. public static void gc()  

Example 1
1. import java.awt.Window;  
2. public class SystemGCExample1 {  
3.   
4.     public static void main(String[] args) {  
5.            
6.         for (int i = 0; i< 100; i++) {  
7.         new Window(null);  
8.              }  
9.         System.out.println("before garbage collection = "+Window.getWindows().length);  
10.         System.gc();  
11.         System.out.println("after garbage collection = "+Window.getWindows().length);  
12.           }  
13. }  
Test it Now

Output:

before garbage collection = 100


after garbage collection = 0

Example 2
1. public class SystemGCExample2 {  
2.   
3.     public static void main(String[] args) {  
4.         String i=null; //value of i is null  
5.         System.gc();   
6.         System.out.println(i); //value of i after gc          
7.         }  
8. }  
Test it Now

Output:

null

Java System exit() Method


The exit() method of System class terminates the current Java virtual machine running on
system. This method takes status code as an argument.

o Note: Status - exit(0) - indicates Successful termination


o Status - exit(-1) - indicates unsuccessful termination with Exception
o Status - exit(1) - indicates Unsuccessful termination
Syntax
1. public static void exit(int status)  

Parameter
status - It is the exit status.

Returns
This method does not return any value.

Exception
If security manager exist and his checkexit method doesn't approve exit with specified
status then a SecurityException is thorwn.

Example 1
1. import java.lang.*;  
2. public class SystemExitExample1 {  
3.   
4.     public static void main(String[] args) {  
5.         int a[]= {9,8,7,6,5,4,3,2,1};  
6.         for(int i=0;i<a.length;i++)  
7.         {  
8.             if(a[i]>5)  
9.             {  
10.             System.out.println("array["+i+"]="+a[i]);  
11.             }  
12.             else  
13.             {  
14.                 System.out.println("terminating jvm,exiting");  
15.                 System.exit(0);//Treminatejvm  
16.             }  
17.         }  
18.     }  
19. }  
Test it Now

Output:
array[0]=9
array[1]=8
array[2]=7
array[3]=6
terminatingjvm,exiting

Example 2
1. public class SystemExitExample2 {  
2.   
3.     public static void main(String[] args) {  
4.         System.out.println("program will terminate when i is 1");  
5. for(int i=10;i>0;i--)    {         
6. System.out.println("your no is "+i);  
7. if(i==1){  
8. System.out.println("Value is 1 now terminating your program");  
9. System.exit(1); //exit program  
10.             }  
11.             }  
12.     }  
13. }  
Test it Now

Output:

program will terminate when i is 1


your no is 10
your no is 9
your no is 8
your no is 7
your no is 6
your no is 5
your no is 4
your no is 3
your no is 2
your no is 1
Value is 1 now terminating your program

Exception Handling
 Exception Handling in Java
 The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
 In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.
 What is Exception in Java?
 Dictionary Meaning: Exception is an abnormal condition.
 In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.
 What is Exception Handling?
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

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 need to handle exceptions. Let's consider a scenario:

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5;//exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;  
9. statement 9;  
10. statement 10;  

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed. However, when we perform exception handling, the rest of the statements will
be executed. That is why we use exception handling in Java

Do You Know?

o What is the difference between checked and unchecked exceptions?


o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keywor Description
d

try The "try" keyword is used to specify a block where we should place an exception code. It mean
we can't use try block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which mean
we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed whether a
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 specifies that there may occur an exceptio
in the method. It doesn't throw an exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{  
2.   public static void main(String args[]){  
3.    try{  
4.       //code that may raise exception  
5.       int data=100/0;  
6.    }catch(ArithmeticException e){System.out.println(e);}  
7.    //rest code of the program   
8.    System.out.println("rest of the code...");  
9.   }  
10. }  

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

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:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException  

2) A scenario where NullPointerException occurs

If we have a null value in any variable

, performing any operation on the variable throws a NullPointerException.


1. String s=null;  
2. System.out.println(s.length());//NullPointerException  

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string

variable that has characters; converting this variable into digit will cause NumberFormatException.

1. String s="abc";  
2. int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there


may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

1. int a[]=new int[5];  
2. a[10]=50; //ArrayIndexOutOfBoundsException 

Java try-catch block


Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{    
2. //code that may throw an exception    
3. }catch(Exception_class_Name ref){}    

Syntax of try-finally block

1. try{    
2. //code that may throw an exception    
3. }finally{}    

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block
with a single try block.

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:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.

Example 1
TryCatchExample1.java

1. public class TryCatchExample1 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.         int data=50/0; //may throw exception   
6.           
7.         System.out.println("rest of the code");  
8.           
9.     }  
10.       
11. }  
Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in such case,
the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all
the code below the exception won't be executed.

Solution by exception handling


Let's see the solution of the above problem by a java try-catch block.

Example 2
TryCatchExample2.java

1. public class TryCatchExample2 {  
2.   
3.     public static void main(String[] args) {  
4.         try  
5.         {  
6.         int data=50/0; //may throw exception   
7.         }  
8.             //handling the exception  
9.         catch(ArithmeticException e)  
10.         {  
11.             System.out.println(e);  
12.         }  
13.         System.out.println("rest of the code");  
14.     }  
15.       
16. }  
Test it Now

Output:

java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an exception.

TryCatchExample3.java

1. public class TryCatchExample3 {  
2.   
3.     public static void main(String[] args) {  
4.         try  
5.         {  
6.         int data=50/0; //may throw exception   
7.                          // if exception occurs, the remaining statement will not exceute  
8.         System.out.println("rest of the code");  
9.         }  
10.              // handling the exception   
11.         catch(ArithmeticException e)  
12.         {  
13.             System.out.println(e);  
14.         }  
15.           
16.     }  
17.       
18. }  
Test it Now

Output:

java.lang.ArithmeticException: / by zero

Here, we can see that if an exception occurs in the try block, the rest of the block code
will not execute.
Example 4
Here, we handle the exception using the parent class exception.

TryCatchExample4.java

1. public class TryCatchExample4 {  
2.   
3.     public static void main(String[] args) {  
4.         try  
5.         {  
6.         int data=50/0; //may throw exception   
7.         }  
8.             // handling the exception by using Exception class      
9.         catch(Exception e)  
10.         {  
11.             System.out.println(e);  
12.         }  
13.         System.out.println("rest of the code");  
14.     }  
15.       
16. }  
Test it Now

Output:

java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.

TryCatchExample5.java

1. public class TryCatchExample5 {  
2.   
3.     public static void main(String[] args) {  
4.         try  
5.         {  
6.         int data=50/0; //may throw exception   
7.         }  
8.              // handling the exception  
9.         catch(Exception e)  
10.         {  
11.                   // displaying the custom message  
12.             System.out.println("Can't divided by zero");  
13.         }  
14.     }  
15.       
16. }  
Test it Now

Output:

Can't divided by zero

Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java

1. public class TryCatchExample6 {  
2.   
3.     public static void main(String[] args) {  
4.         int i=50;  
5.         int j=0;  
6.         int data;  
7.         try  
8.         {  
9.         data=i/j; //may throw exception   
10.         }  
11.             // handling the exception  
12.         catch(Exception e)  
13.         {  
14.              // resolving the exception in catch block  
15.             System.out.println(i/(j+2));  
16.         }  
17.     }  
18. }  
Test it Now

Output:

25

Example 7
In this example, along with try block, we also enclose exception code in a catch block.
TryCatchExample7.java

1. public class TryCatchExample7 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.         try  
6.         {  
7.         int data1=50/0; //may throw exception   
8.   
9.         }  
10.              // handling the exception  
11.         catch(Exception e)  
12.         {  
13.             // generating the exception in catch block  
14.         int data2=50/0; //may throw exception   
15.   
16.         }  
17.     System.out.println("rest of the code");  
18.     }  
19. }  
Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Here, we can see that the catch block didn't contain the exception code. So, enclose
exception code within a try block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a
different type of exception class (ArrayIndexOutOfBoundsException).

TryCatchExample8.java

1. public class TryCatchExample8 {  
2.   
3.     public static void main(String[] args) {  
4.         try  
5.         {  
6.         int data=50/0; //may throw exception   
7.   
8.         }  
9.             // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException  
10.         catch(ArrayIndexOutOfBoundsException e)  
11.         {  
12.             System.out.println(e);  
13.         }  
14.         System.out.println("rest of the code");  
15.     }  
16.       
17. }  
Test it Now

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


Example 9
Let's see an example to handle another unchecked exception.

TryCatchExample9.java

1. public class TryCatchExample9 {  
2.   
3.     public static void main(String[] args) {  
4.         try  
5.         {  
6.         int arr[]= {1,3,5,7};  
7.         System.out.println(arr[10]); //may throw exception   
8.         }  
9.             // handling the array exception  
10.         catch(ArrayIndexOutOfBoundsException e)  
11.         {  
12.             System.out.println(e);  
13.         }  
14.         System.out.println("rest of the code");  
15.     }  
16.       
17. }  
Test it Now

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.

TryCatchExample10.java

1. import java.io.FileNotFoundException;  
2. import java.io.PrintWriter;  
3.   
4. public class TryCatchExample10 {  
5.   
6.     public static void main(String[] args) {  
7.           
8.           
9.         PrintWriter pw;  
10.         try {  
11.             pw = new PrintWriter("jtp.txt"); //may throw exception   
12.             pw.println("saved");  
13. e
14.         }  
15. // providing the checked exception handler  
16.  catch (FileNotFoundException e) {  
17.               
18.             System.out.println(e);  
19.         }         
20.     System.out.println("File saved successfully");  
21.     }  
22. }  
Test it Now
Output:

File saved successfully

Java Catch Multiple Exceptions


Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block


Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.            try{    
6.                 int a[]=new int[5];    
7.                 a[5]=30/0;    
8.                }    
9.                catch(ArithmeticException e)  
10.                   {  
11.                    System.out.println("Arithmetic Exception occurs");  
12.                   }    
13.                catch(ArrayIndexOutOfBoundsException e)  
14.                   {  
15.                    System.out.println("ArrayIndexOutOfBounds Exception occurs");  
16.                   }    
17.                catch(Exception e)  
18.                   {  
19.                    System.out.println("Parent Exception occurs");  
20.                   }             
21.                System.out.println("rest of the code");    
22.     }  
23. }  
Test it Now
Output:

Skip Ad

Arithmetic Exception occurs


rest of the code

Example 2
MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.            try{    
6.                 int a[]=new int[5];    
7.                 
8.                 System.out.println(a[10]);  
9.                }    
10.                catch(ArithmeticException e)  
11.                   {  
12.                    System.out.println("Arithmetic Exception occurs");  
13.                   }    
14.                catch(ArrayIndexOutOfBoundsException e)  
15.                   {  
16.                    System.out.println("ArrayIndexOutOfBounds Exception occurs");  
17.                   }    
18.                catch(Exception e)  
19.                   {  
20.                    System.out.println("Parent Exception occurs");  
21.                   }             
22.                System.out.println("rest of the code");    
23.     }  
24. }  
Test it Now

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

In this example, try block contains two exceptions. But at a time only one exception
occurs and its corresponding catch block is executed.

MultipleCatchBlock3.java

1. public class MultipleCatchBlock3 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.            try{    
6.                 int a[]=new int[5];    
7.                 a[5]=30/0;    
8.                 System.out.println(a[10]);  
9.                }    
10.                catch(ArithmeticException e)  
11.                   {  
12.                    System.out.println("Arithmetic Exception occurs");  
13.                   }    
14.                catch(ArrayIndexOutOfBoundsException e)  
15.                   {  
16.                    System.out.println("ArrayIndexOutOfBounds Exception occurs");  
17.                   }    
18.                catch(Exception e)  
19.                   {  
20.                    System.out.println("Parent Exception occurs");  
21.                   }             
22.                System.out.println("rest of the code");    
23.     }  
24. }  
Test it Now

Output:

Arithmetic Exception occurs


rest of the code

Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception
class Exception will invoked.

MultipleCatchBlock4.java

1. public class MultipleCatchBlock4 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.            try{    
6.                 String s=null;  
7.                 System.out.println(s.length());  
8.                }    
9.                catch(ArithmeticException e)  
10.                   {  
11.                    System.out.println("Arithmetic Exception occurs");  
12.                   }    
13.                catch(ArrayIndexOutOfBoundsException e)  
14.                   {  
15.                    System.out.println("ArrayIndexOutOfBounds Exception occurs");  
16.                   }    
17.                catch(Exception e)  
18.                   {  
19.                    System.out.println("Parent Exception occurs");  
20.                   }             
21.                System.out.println("rest of the code");    
22.     }  
23. }  
Test it Now

Output:

Parent Exception occurs


rest of the code

Example 5
Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).

MultipleCatchBlock5.java
1. class MultipleCatchBlock5{    
2.   public static void main(String args[]){    
3.    try{    
4.     int a[]=new int[5];    
5.     a[5]=30/0;    
6.    }    
7.    catch(Exception e){System.out.println("common task completed");}    
8.    catch(ArithmeticException e){System.out.println("task1 is completed");}    
9.    catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}    
10.    System.out.println("rest of the code...");    
11.  }    
12. }   
Test it Now

Output:

Compile-time error

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

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.

Syntax:
1. ....    
2. //main try block  
3. try    
4. {    
5.     statement 1;    
6.     statement 2;    
7. //try catch block within another try block  
8.     try    
9.     {    
10.         statement 3;    
11.         statement 4;    
12. //try catch block within nested try block  
13.         try    
14.         {    
15.             statement 5;    
16.             statement 6;    
17.      }    
18.         catch(Exception e2)    
19.         {    
20. //exception message  
21.         }    
22.   
23.     }    
24.     catch(Exception e1)    
25.     {    
26. //exception message  
27.     }    
28. }    
29. //catch block of parent (outer) try block  
30. catch(Exception e3)    
31. {    
32. //exception message  
33. }    
34. ....   
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block for two
different exceptions.

Prime Ministers of India | List of Prime Minister of India (1947-2020)

NestedTryBlock.java

1. public class NestedTryBlock{    
2.  public static void main(String args[]){   
3.  //outer try block   
4.   try{    
5.   //inner try block 1  
6.     try{    
7.      System.out.println("going to divide by 0");    
8.      int b =39/0;    
9.    }  
10.     //catch block of inner try block 1  
11.     catch(ArithmeticException e)  
12.     {  
13.       System.out.println(e);  
14.     }    
15.        
16.     
17.     //inner try block 2  
18.     try{    
19.     int a[]=new int[5];    
20.   
21.     //assigning the value out of array bounds  
22.      a[5]=4;    
23.      }  
24.   
25.     //catch block of inner try block 2  
26.     catch(ArrayIndexOutOfBoundsException e)  
27.     {  
28.        System.out.println(e);  
29.     }    
30.   
31.       
32.     System.out.println("other statement");    
33.   }  
34.   //catch block of outer try block  
35.   catch(Exception e)  
36.   {  
37.     System.out.println("handled the exception (outer catch)");  
38.   }    
39.     
40.   System.out.println("normal flow..");    
41.  }    
42. }  

Output:

When any try block does not have a catch block for a particular exception, then the
catch block of the outer (parent) try block are checked for that exception, and if it
matches, the catch block of outer try block is executed.

If none of the catch block specified in the code is unable to handle the exception, then
the Java runtime system will handle the exception. Then it displays the system generated
message for that exception.
Example 2
Let's consider the following example. Here the try block within nested try block (inner try
block 2) do not handle the exception. The control is then transferred to its parent try
block (inner try block 1). If it does not handle the exception, then the control is
transferred to the main try block (outer try block) where the appropriate catch block
handles the exception. It is termed as nesting.

NestedTryBlock.java

1. public class NestedTryBlock2 {  
2.      
3.     public static void main(String args[])  
4.     {  
5.         // outer (main) try block  
6.         try {  
7.     
8.             //inner try block 1   
9.             try {  
10.     
11.                 // inner try block 2  
12.                 try {  
13.                     int arr[] = { 1, 2, 3, 4 };  
14.   
15.                     //printing the array element out of its bounds  
16.                     System.out.println(arr[10]);  
17.                 }  
18.     
19.                 // to handles ArithmeticException  
20.                 catch (ArithmeticException e) {  
21.                     System.out.println("Arithmetic exception");  
22.                     System.out.println(" inner try block 2");  
23.                 }  
24.             }  
25.     
26.             // to handle ArithmeticException   
27.             catch (ArithmeticException e) {  
28.                 System.out.println("Arithmetic exception");  
29.                 System.out.println("inner try block 1");  
30.             }  
31.         }  
32.     
33.         // to handle ArrayIndexOutOfBoundsException   
34.         catch (ArrayIndexOutOfBoundsException e4) {  
35.             System.out.print(e4);  
36.             System.out.println(" outer (main) try block");  
37.         }  
38.         catch (Exception e5) {  
39.             System.out.print("Exception");  
40.             System.out.println(" handled in main try-block");  
41.         }  
42.     }  
43. }  

Output:

Java finally block


Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the
necessary statements that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.


Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).

Why use Java finally block?


o finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally


Let's see the different cases where Java finally block can be used.

Skip Ad

Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any exception, and the finally block
is executed after the try block.
TestFinallyBlock.java

1. class TestFinallyBlock {    
2.   public static void main(String args[]){    
3.   try{    
4. //below code do not throw any exception  
5.    int data=25/5;    
6.    System.out.println(data);    
7.   }    
8. //catch won't be executed  
9.   catch(NullPointerException e){  
10. System.out.println(e);  
11. }    
12. //executed regardless of exception occurred or not  
13.  finally {  
14. System.out.println("finally block is always executed");  
15. }    
16.     
17. System.out.println("rest of phe code...");    
18.   }    
19. }    

Output:

Case 2: When an exception occurr but not handled by the catch block

Let's see the the fillowing example. Here, the code throws an exception however the catch block cannot
handle it. Despite this, the finally block is executed after the try block and then the program terminates
abnormally.

TestFinallyBlock1.java

1. public class TestFinallyBlock1{    
2.       public static void main(String args[]){   
3.   
4.       try {    
5.   
6.         System.out.println("Inside the try block");  
7.           
8.         //below code throws divide by zero exception  
9.        int data=25/0;    
10.        System.out.println(data);    
11.       }    
12.       //cannot handle Arithmetic type exception  
13.       //can only accept Null Pointer type exception  
14.       catch(NullPointerException e){  
15.         System.out.println(e);  
16.       }   
17.   
18.       //executes regardless of exception occured or not   
19.       finally {  
20.         System.out.println("finally block is always executed");  
21.       }    
22.   
23.       System.out.println("rest of the code...");    
24.       }    
25.     }    

Output:

Case 3: When an exception occurs and is handled by the catch block

Example:

Let's see the following example where the Java code throws an exception and the catch block handles the
exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also
executed normally.

TestFinallyBlock2.java

1. public class TestFinallyBlock2{    
2.       public static void main(String args[]){   
3.   
4.       try {    
5.   
6.         System.out.println("Inside try block");  
7.   
8.         //below code throws divide by zero exception  
9.        int data=25/0;    
10.        System.out.println(data);    
11.       }   
12.   
13.       //handles the Arithmetic Exception / Divide by zero exception  
14.       catch(ArithmeticException e){  
15.         System.out.println("Exception handled");  
16.         System.out.println(e);  
17.       }   
18.   
19.       //executes regardless of exception occured or not   
20.       finally {  
21.         System.out.println("finally block is always executed");  
22.       }    
23.   
24.       System.out.println("rest of the code...");    
25.       }    
26.     }  

Output:

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 the program exits (either by calling System.exit() or by causing a
fatal error that causes the process to abort).

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked at
the compile time instead of runtime and we can create custom exceptions making the
code recovery and debugging easier.

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some


message with it that provides the error description. These exceptions may be related to
user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in this
section.

17.6M

362

Java Try Catch

We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a number
by another number. Here, we just need to set the condition and throw exception using
throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");  

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");   

Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.

TestThrow1.java

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.

1. public class TestThrow1 {   
2.     //function to check if person is eligible to vote or not   
3.     public static void validate(int age) {  
4.         if(age<18) {  
5.             //throw Arithmetic exception if not eligible to vote  
6.             throw new ArithmeticException("Person is not eligible to vote");    
7.         }  
8.         else {  
9.             System.out.println("Person is eligible to vote!!");  
10.         }  
11.     }  
12.     //main method  
13.     public static void main(String args[]){  
14.         //calling the function  
15.         validate(13);  
16.         System.out.println("rest of the code...");    
17.   }    
18. }    

Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked
and user defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.

If we throw a checked exception using throw keyword, it is must to handle the exception
using catch block or the method must declare it using throws declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A
checked exception is everything else under the Throwable class.

TestThrow2.java

1. import java.io.*;  
2.   
3. public class TestThrow2 {   
4.   
5.     //function to check if person is eligible to vote or not   
6.     public static void method() throws FileNotFoundException {  
7.   
8.         FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");  
9.         BufferedReader fileInput = new BufferedReader(file);  
10.   
11.       
12.         throw new FileNotFoundException();  
13.       
14.     }  
15.     //main method  
16.     public static void main(String args[]){  
17.         try  
18.         {  
19.             method();  
20.         }   
21.         catch (FileNotFoundException e)   
22.         {  
23.             e.printStackTrace();  
24.         }  
25.         System.out.println("rest of the code...");    
26.   }    
27. }    

Output:

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.

TestThrow3.java

1. // class represents user-defined exception  
2. class UserDefinedException extends Exception  
3. {  
4.     public UserDefinedException(String str)  
5.     {  
6.         // Calling constructor of parent Exception  
7.         super(str);  
8.     }  
9. }  
10. // Class that uses above MyException  
11. public class TestThrow3  
12. {  
13.     public static void main(String args[])  
14.     {  
15.         try  
16.         {  
17.             // throw an object of user defined exception  
18.             throw new UserDefinedException("This is user-defined exception");  
19.         }  
20.         catch (UserDefinedException ude)  
21.         {  
22.             System.out.println("Caught the exception");  
23.             // Print the message from MyException object  
24.             System.out.println(ude.getMessage());  
25.         }  
26.     }  
27. }   

Output:

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.

Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Exception Propagation Example


TestExceptionPropagation1.java
1. class TestExceptionPropagation1{  
2.   void m(){  
3.     int data=50/0;  
4.   }  
5.   void n(){  
6.     m();  
7.   }  
8.   void p(){  
9.    try{  
10.     n();  
11.    }catch(Exception e){System.out.println("exception handled");}  
12.   }  
13.   public static void main(String args[]){  
14.    TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
15.    obj.p();  
16.    System.out.println("normal flow...");  
17.   }  
18. }  
Test it Now

Output:

exception handled
normal flow...

In the above example exception occurs in the m() method where it is not handled, so it
is propagated to the previous n() method where it is not handled, again it is propagated
to the p() method where exception is handled.

Exception can be handled in any method in call stack either in the main() method, p()
method, n() method or m() method.
Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Exception Propagation Example


TestExceptionPropagation1.java

1. class TestExceptionPropagation2{  
2.   void m(){  
3.     throw new java.io.IOException("device error");//checked exception  
4.   }  
5.   void n(){  
6.     m();  
7.   }  
8.   void p(){  
9.    try{  
10.     n();  
11.    }catch(Exception e){System.out.println("exception handeled");}  
12.   }  
13.   public static void main(String args[]){  
14.    TestExceptionPropagation2 obj=new TestExceptionPropagation2();  
15.    obj.p();  
16.    System.out.println("normal flow");  
17.   }  
18. }  
Test it Now

Output:

Compile Time Error

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to
the programmer that there may occur an exception. So, it is better for the programmer
to provide the exception handling code so that the normal flow of the program can be
maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is
not checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{  
2. //method code  
3. }  

Which exception should be declared?


Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage 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


Let's see the example of Java throws clause which describes that checked exceptions can
be propagated by throws keyword.

Testthrows1.java

1. import java.io.IOException;  
2. class Testthrows1{  
3.   void m()throws IOException{  
4.     throw new IOException("device error");//checked exception  
5.   }  
6.   void n()throws IOException{  
7.     m();  
8.   }  
9.   void p(){  
10.    try{  
11.     n();  
12.    }catch(Exception e){System.out.println("exception handled");}  
13.   }  
14.   public static void main(String args[]){  
15.    Testthrows1 obj=new Testthrows1();  
16.    obj.p();  
17.    System.out.println("normal flow...");  
18.   }  
19. }  
Test it Now

Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.

There are two cases:

1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch
block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the method.

Case 1: Handle Exception Using try-catch block


In case we handle the exception, the code will be executed fine whether exception
occurs during the program or not.

Testthrows2.java

1. import java.io.*;  
2. class M{  
3.  void method()throws IOException{  
4.   throw new IOException("device error");  
5.  }  
6. }  
7. public class Testthrows2{  
8.    public static void main(String args[]){  
9.     try{  
10.      M m=new M();  
11.      m.method();  
12.     }catch(Exception e){System.out.println("exception handled");}     
13.   
14.     System.out.println("normal flow...");  
15.   }  
16. }  
Test it Now

Output:

exception handled
normal flow...

Case 2: Declare Exception


o In case we declare the exception, if exception does not occur, the code will be executed
fine.
o In case we declare the exception and the exception occurs, it will be thrown at runtime
because throws does not handle the exception.
Let's see examples for both the scenario.

A) If exception does not occur

Testthrows3.java

1. import java.io.*;  
2. class M{  
3.  void method()throws IOException{  
4.   System.out.println("device operation performed");  
5.  }  
6. }  
7. class Testthrows3{  
8.    public static void main(String args[])throws IOException{//declare exception  
9.      M m=new M();  
10.      m.method();  
11.   
12.     System.out.println("normal flow...");  
13.   }  
14. }  
Test it Now

Output:

device operation performed


normal flow...

B) If exception occurs

Testthrows4.java

1. import java.io.*;  
2. class M{  
3.  void method()throws IOException{  
4.   throw new IOException("device error");  
5.  }  
6. }  
7. class Testthrows4{  
8.    public static void main(String args[])throws IOException{//declare exception  
9.      M m=new M();  
10.      m.method();  
11.   
12.     System.out.println("normal flow...");  
13.   }  
14. }  
Test it Now

Output:

Difference between throw and throws


Que) Can we rethrow an exception?
Yes, by throwing same exception in catch block.

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of differences


between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used Java throws keyword is used in the
throw an exception method signature to declare an exception
explicitly in the code, inside which might be thrown by the function
the function or the block of while the execution of the code.
code.

2. Type of exception Using Using throws keyword, we


throw keyword, we can can declare both checked
only propagate and unchecked exceptions.
unchecked exception However, the throws
i.e., the checked keyword can be used to
exception cannot be propagate checked
propagated using throw exceptions only.
only.

3. Syntax The throw keyword is The throws keyword is followed by class


followed by an instance of names of Exceptions to be thrown.
Exception to be thrown.

4. Declaration throw is used within the throws is used with the method
method. signature.

5. Internal implementation We are allowed to throw We can declare multiple exceptions using
only one exception at a throws keyword that can be thrown by
time i.e. we cannot throw the method. For example, main() throws
multiple exceptions. IOException, SQLException.

Java throw Example


TestThrow.java

1. public class TestThrow {  
2.     //defining a method  
3.     public static void checkNum(int num) {  
4.         if (num < 1) {  
5.             throw new ArithmeticException("\nNumber is negative, cannot calculate square");  
6.         }  
7.         else {  
8.             System.out.println("Square of " + num + " is " + (num*num));  
9.         }  
10.     }  
11.     //main method  
12.     public static void main(String[] args) {  
13.             TestThrow obj = new TestThrow();  
14.             obj.checkNum(-3);  
15.             System.out.println("Rest of the code..");  
16.     }  
17. }  

Output:

HTML Tutorial

Java throws Example


TestThrows.java

1. public class TestThrows {  
2.     //defining a method  
3.     public static int divideNum(int m, int n) throws ArithmeticException {  
4.         int div = m / n;  
5.         return div;  
6.     }  
7.     //main method  
8.     public static void main(String[] args) {  
9.         TestThrows obj = new TestThrows();  
10.         try {  
11.             System.out.println(obj.divideNum(45, 0));  
12.         }  
13.         catch (ArithmeticException e){  
14.             System.out.println("\nNumber cannot be divided by 0");  
15.         }  
16.           
17.         System.out.println("Rest of the code..");  
18.     }  
19. }  

Output:

Java throw and throws Example


TestThrowAndThrows.java

1. public class TestThrowAndThrows  
2. {  
3.     // defining a user-defined method  
4.     // which throws ArithmeticException  
5.     static void method() throws ArithmeticException  
6.     {  
7.         System.out.println("Inside the method()");  
8.         throw new ArithmeticException("throwing ArithmeticException");  
9.     }  
10.     //main method  
11.     public static void main(String args[])  
12.     {  
13.         try  
14.         {  
15.             method();  
16.         }  
17.         catch(ArithmeticException e)  
18.         {  
19.             System.out.println("caught in main() method");  
20.         }  
21.     }  
22. }  

Output:

Difference between final, finally and finalize


The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these
keywords has a different functionality. The basic difference between final, finally and finalize is that
the final is an access modifier, finally is the block in Exception Handling and finalize is the method of
object class.

Along with this, there are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:

Sr. Key final finally finalize


no.

1. Definition final is the keyword and finally is the block in Java finalize is the method in
access modifier which is Exception Handling to Java which is used to
used to apply execute the important perform clean up
restrictions on a class, code whether the processing just before
method or variable. exception occurs or not. object is garbage
collected.

2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.

3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs
variable becomes important code even if the cleaning activities
constant and cannot be exception occurs or not. with respect to the object
modified. (2) finally block cleans up before its destruction.
(2) final method cannot all the resources used in
be overridden by sub try block
class.
(3) final class cannot be
inherited.

4. Execution Final method is Finally block is executed finalize method is


executed only when we as soon as the try-catch executed just before the
call it. block is executed. object is destroyed.

It's execution is not


dependant on the
exception.

Java final Example


Let's consider the following example where we declare final variable age. Once declared it cannot be
modified.

FinalExampleTest.java

1. public class FinalExampleTest {  
2.     //declaring final variable  
3.     final int age = 18;  
4.     void display() {  
5.       
6.     // reassigning value to age variable   
7.     // gives compile time error  
8.     age = 55;  
9.     }  
10.       
11.     public static void main(String[] args) {  
12.       
13.     FinalExampleTest obj = new FinalExampleTest();  
14.     // gives compile time error  
15.     obj.display();  
16.     }  
17. }  

Output:
In the above example, we have declared a variable final. Similarly, we can declare the methods and classes
final using the final keyword.

Java finally Example


Let's see the below example where the Java code throws an exception and the catch block handles that
exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also
executed normally.

FinallyExample.java

1. public class FinallyExample {    
2.       public static void main(String args[]){   
3.       try {    
4.         System.out.println("Inside try block");  
5.       // below code throws divide by zero exception  
6.        int data=25/0;    
7.        System.out.println(data);    
8.       }   
9.       // handles the Arithmetic Exception / Divide by zero exception  
10.       catch (ArithmeticException e){  
11.         System.out.println("Exception handled");  
12.         System.out.println(e);  
13.       }   
14.       // executes regardless of exception occurred or not   
15.       finally {  
16.         System.out.println("finally block is always executed");  
17.       }    
18.       System.out.println("rest of the code...");    
19.       }    
20.     }    

Output:
Java finalize Example
FinalizeExample.java

1. public class FinalizeExample {    
2.      public static void main(String[] args)     
3.     {     
4.         FinalizeExample obj = new FinalizeExample();        
5.         // printing the hashcode   
6.         System.out.println("Hashcode is: " + obj.hashCode());           
7.         obj = null;    
8.         // calling the garbage collector using gc()   
9.         System.gc();     
10.         System.out.println("End of the garbage collection");     
11.     }     
12.    // defining the finalize method   
13.     protected void finalize()     
14.     {     
15.         System.out.println("Called the finalize() method");     
16.     }     
17. }    

Output:

Exception Handling with Method Overriding in


Java
There are many rules if we talk about method overriding with exception handling.

Some of the rules are listed below:

o If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
o If the superclass method declares an exception
o 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 1: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.

Let's consider following example based on the above rule.

TestExceptionChild.java

SQL CREATE TABLE

1. import java.io.*;    
2. class Parent{   
3.   
4.   // defining the method   
5.   void msg() {  
6.     System.out.println("parent method");  
7.     }    
8. }    
9.     
10. public class TestExceptionChild extends Parent{    
11.   
12.   // overriding the method in child class  
13.   // gives compile time error  
14.   void msg() throws IOException {    
15.     System.out.println("TestExceptionChild");    
16.   }  
17.   
18.   public static void main(String args[]) {    
19.    Parent p = new TestExceptionChild();    
20.    p.msg();    
21.   }    
22. }    

Output:

Rule 2: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.

TestExceptionChild1.java

1. import java.io.*;    
2. class Parent{    
3.   void msg() {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. class TestExceptionChild1 extends Parent{    
9.   void msg()throws ArithmeticException {    
10.     System.out.println("child method");    
11.   }    
12.   
13.   public static void main(String args[]) {    
14.    Parent p = new TestExceptionChild1();    
15.    p.msg();    
16.   }    
17. }   

Output:

If the superclass method declares an exception


Rule 1: If the superclass method declares an exception, subclass overridden method can
declare the same subclass exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent


exception
TestExceptionChild2.java

1. import java.io.*;    
2. class Parent{    
3.   void msg()throws ArithmeticException {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. public class TestExceptionChild2 extends Parent{    
9.   void msg()throws Exception {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]) {    
14.    Parent p = new TestExceptionChild2();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch (Exception e){}   
20.   
21.   }    
22. }     

Output:

Example in case subclass overridden method declares same


exception
TestExceptionChild3.java

1. import java.io.*;    
2. class Parent{    
3.   void msg() throws Exception {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. public class TestExceptionChild3 extends Parent {    
9.   void msg()throws Exception {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]){    
14.    Parent p = new TestExceptionChild3();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch(Exception e) {}    
20.   }    
21. }    

Output:

Example in case subclass overridden method declares subclass


exception
TestExceptionChild4.java

1. import java.io.*;    
2. class Parent{    
3.   void msg()throws Exception {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. class TestExceptionChild4 extends Parent{    
9.   void msg()throws ArithmeticException {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]){    
14.    Parent p = new TestExceptionChild4();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch(Exception e) {}    
20.   }    
21. }    

Output:

Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message. Here, we
have passed a string to the constructor of superclass i.e. Exception class that can be
obtained using getMessage() method on the object we have created.

In this section, we will learn how custom exceptions are implemented and used in Java
programs.

Prime Ministers of India | List of Prime Minister of India (1947-2020)

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

o To catch and provide specific treatment to a subset of existing Java exceptions.


o Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the exact
problem.

In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

1. public class WrongFileNameException extends Exception {  
2.     public WrongFileNameException(String errorMessage) {  
3.     super(errorMessage);  
4.     }  
5. }  

Note: We need to write the constructor that takes the String as the error message and it is
called parent class constructor.

Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor
of InvalidAgeException takes a string as an argument. This string is passed to
constructor of parent class Exception using the super() method. Also the constructor of
Exception class can be called without using a parameter and calling super() method is
not mandatory.

TestCustomException1.java

1. // class representing custom exception  
2. class InvalidAgeException  extends Exception  
3. {  
4.     public InvalidAgeException (String str)  
5.     {  
6.         // calling the constructor of parent Exception  
7.         super(str);  
8.     }  
9. }  
10.     
11. // class that uses custom exception InvalidAgeException  
12. public class TestCustomException1  
13. {  
14.   
15.     // method to check the age  
16.     static void validate (int age) throws InvalidAgeException{    
17.        if(age < 18){  
18.   
19.         // throw an object of user defined exception  
20.         throw new InvalidAgeException("age is not valid to vote");    
21.     }  
22.        else {   
23.         System.out.println("welcome to vote");   
24.         }   
25.      }    
26.   
27.     // main method  
28.     public static void main(String args[])  
29.     {  
30.         try  
31.         {  
32.             // calling the method   
33.             validate(13);  
34.         }  
35.         catch (InvalidAgeException ex)  
36.         {  
37.             System.out.println("Caught the exception");  
38.     
39.             // printing the message from InvalidAgeException object  
40.             System.out.println("Exception occured: " + ex);  
41.         }  
42.   
43.         System.out.println("rest of the code...");    
44.     }  
45. }  

Output:

Multithreading
Multithreading in Java
Multithreading in Java

is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.OOPs Concepts in Ja

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in


a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers

, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate
path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
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.

Note: At a time one thread is executed only.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class
provides constructors

and methods to create and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.

Java Thread Methods

S.N. Modifier and Type Method Description

1) void start() It is used to start the execution


of the thread.

2) void run() It is used to do an action for a


thread.

3) static void sleep() It sleeps a thread for the


specified amount of time.

4) static Thread currentThread() It returns a reference to the


currently executing thread
object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the


thread.

7) void setPriority() It changes the priority of the


thread.

8) String getName() It returns the name of the


thread.
9) void setName() It changes the name of the
thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently


executing thread object to
pause and allow other threads
to execute temporarily.

13) void suspend() It is used to suspend the


thread.

14) void resume() It is used to resume the


suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread


group and all of its subgroups.

17) boolean isDaemon() It tests if the thread is a


daemon thread.

18) void setDaemon() It marks the thread as daemon


or user thread.

19) void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has


been interrupted.

21) static boolean interrupted() It tests whether the current


thread has been interrupted.

22) static int activeCount() It returns the number of active


threads in the current thread's
thread group.

23) void checkAccess() It determines if the currently


running thread has permission
to modify the thread.

24) static boolean holdLock() It returns true if and only if the


current thread holds the
monitor lock on the specified
object.

25) static void dumpStack() It is used to print a stack trace


of the current thread to the
standard error stream.

26) StackTraceElement[] getStackTrace() It returns an array of stack trace


elements representing the stack
dump of the thread.
27) static int enumerate() It is used to copy every active
thread's thread group and its
subgroup into the specified
array.

28) Thread.State getState() It is used to return the state of


the thread.

29) ThreadGroup getThreadGroup() It is used to return the thread


group to which this thread
belongs

30) String toString() It is used to return a string


representation of this thread,
including the thread's name,
priority, and thread group.

31) void notify() It is used to give the


notification for only one thread
which is waiting for a particular
object.

32) void notifyAll() It is used to give the


notification to all waiting
threads of a particular object.

33) void setContextClassLoader It sets the context ClassLoader


() for the Thread.

34) ClassLoader getContextClassLoade It returns the context


r() ClassLoader for the thread.
35) static getDefaultUncaughtEx It returns the default handler
Thread.UncaughtExceptionHandler ceptionHandler() invoked when a thread abruptly
terminates due to an uncaught
exception.

36) static void setDefaultUncaughtEx It sets the default handler


ceptionHandler() invoked when a thread abruptly
terminates due to an uncaught
exception.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the
new state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the other
is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant of
time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving
the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated time
slice is over, the thread voluntarily gives up the CPU to the other thread, so that the
other threads can also run for their slice of time. Whenever such a scenario occurs, all
those threads that are willing to run, waiting for their turn to run, lie in the runnable
state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)


then, either the thread is in the blocked state or is in the waiting state.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.
Implementation of Thread States
In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent the
state of a thread. These constants are:

1. public static final Thread.State NEW  

It represents the first state of a thread that is the NEW state.

1. public static final Thread.State RUNNABLE  
It represents the runnable state.It means a thread is waiting in the queue to run.

1. public static final Thread.State BLOCKED  

It represents the blocked state. In this state, the thread is waiting to acquire a lock.

1. public static final Thread.State WAITING  

It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting
state is waiting for another thread to complete its task.

1. public static final Thread.State TIMED_WAITING  

It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has
the time constraint. A thread invoking the following method reaches the timed waiting
state.

o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos

1. public static final Thread.State TERMINATED  

It represents the final state of a thread that is terminated or dead. A terminated thread
means it has completed its execution.

Java Program for Demonstrating Thread States


The following Java program shows some of the states of a thread defined above.

FileName: ThreadState.java

1. // ABC class implements the interface Runnable  
2. class ABC implements Runnable  
3. {  
4. public void run()  
5. {  
6.   
7. // try-catch block  
8. try  
9. {  
10. // moving thread t2 to the state timed waiting  
11. Thread.sleep(100);  
12. }  
13. catch (InterruptedException ie)  
14. {  
15. ie.printStackTrace();  
16. }  
17.   
18.   
19. System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+ Thr
eadState.t1.getState());  
20.   
21. // try-catch block  
22. try  
23. {  
24. Thread.sleep(200);  
25. }  
26. catch (InterruptedException ie)  
27. {  
28. ie.printStackTrace();  
29. }     
30. }  
31. }  
32.   
33. // ThreadState class implements the interface Runnable  
34. public class ThreadState implements Runnable  
35. {  
36. public static Thread t1;  
37. public static ThreadState obj;  
38.   
39. // main method   
40. public static void main(String argvs[])  
41. {  
42. // creating an object of the class ThreadState  
43. obj = new ThreadState();  
44. t1 = new Thread(obj);  
45.   
46. // thread t1 is spawned   
47. // The thread t1 is currently in the NEW state.  
48. System.out.println("The state of thread t1 after spawning it - " + t1.getState());  
49.   
50. // invoking the start() method on   
51. // the thread t1  
52. t1.start();  
53.   
54. // thread t1 is moved to the Runnable state  
55. System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState
());  
56. }  
57.   
58. public void run()  
59. {  
60. ABC myObj = new ABC();  
61. Thread t2 = new Thread(myObj);  
62.   
63. // thread t2 is created and is currently in the NEW state.  
64. System.out.println("The state of thread t2 after spawning it - "+ t2.getState());  
65. t2.start();  
66.   
67. // thread t2 is moved to the runnable state  
68. System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState()); 
 
69.   
70. // try-catch block for the smooth flow of the  program  
71. try  
72. {  
73. // moving the thread t1 to the state timed waiting   
74. Thread.sleep(200);  
75. }  
76. catch (InterruptedException ie)  
77. {  
78. ie.printStackTrace();  
79. }  
80.   
81. System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState
() );  
82.   
83. // try-catch block for the smooth flow of the  program  
84. try  
85. {  
86. // waiting for thread t2 to complete its execution  
87. t2.join();  
88. }  
89. catch (InterruptedException ie)  
90. {  
91. ie.printStackTrace();  
92. }  
93. System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState()
);  
94. }  
95.   
96. }  

Output:

The state of thread t1 after spawning it - NEW


The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -
TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED

Explanation: Whenever we spawn a new thread, that thread attains the new state.
When the method start() is invoked on a thread, the thread scheduler moves that thread
to the runnable state. Whenever the join() method is invoked on any thread instance,
the current thread executing that statement has to wait for this thread to finish its
execution, i.e., move that thread to the terminated state. Therefore, before the final print
statement is printed on the console, the program invokes the method join() on thread
t2, making the thread t1 wait while the thread t2 finishes its execution and thus, the
thread t2 get to the terminated or dead state. Thread t1 goes to the waiting state
because it is waiting for thread t2 to finish it's execution as it has invoked the method
join() on thread t2.

Java Threads | How to create a thread in Java


There are two ways to create a thread:

1. By extending Thread class


2. 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:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

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().

1. public void run(): is used to perform action for a thread.

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:

C++ vs Java

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


FileName: Multi.java

1. class Multi extends Thread{  
2. public void run(){  
3. System.out.println("thread is running...");  
4. }  
5. public static void main(String args[]){  
6. Multi t1=new Multi();  
7. t1.start();  
8.  }  
9. }  

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface


FileName: Multi3.java

1. class Multi3 implements Runnable{  
2. public void run(){  
3. System.out.println("thread is running...");  
4. }  
5.   
6. public static void main(String args[]){  
7. Multi3 m1=new Multi3();  
8. Thread t1 =new Thread(m1);   // Using the constructor Thread(Runnable r)  
9. t1.start();  
10.  }  
11. }  

Output:
thread is running...

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 the Thread class object. We are passing
the object of your class that implements Runnable so that your class run() method may
execute.

3) Using the Thread Class: Thread(String Name)


We can directly use the Thread class to spawn new threads using the constructors
defined above.

FileName: MyThread1.java

1. public class MyThread1  
2. {  
3. // Main method  
4. public static void main(String argvs[])  
5. {  
6. // creating an object of the Thread class using the constructor Thread(String name)   
7. Thread t= new Thread("My first thread");  
8.   
9. // the start() method moves the thread to the active state  
10. t.start();  
11. // getting the thread name by invoking the getName() method  
12. String str = t.getName();  
13. System.out.println(str);  
14. }  
15. }  

Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)


Observe the following program.

FileName: MyThread2.java
1. public class MyThread2 implements Runnable  
2. {    
3. public void run()  
4. {    
5. System.out.println("Now the thread is running ...");    
6. }    
7.     
8. // main method  
9. public static void main(String argvs[])  
10. {   
11. // creating an object of the class MyThread2  
12. Runnable r1 = new MyThread2();   
13.   
14. // creating an object of the class Thread using Thread(Runnable r, String name)  
15. Thread th1 = new Thread(r1, "My new thread");    
16.   
17. // the start() method moves the thread to the active state  
18. th1.start();   
19.   
20. // getting the thread name by invoking the getName() method  
21. String str = th1.getName();  
22. System.out.println(str);  
23. }    
24. }    

Output:

My new thread
Now the thread is running ...

Thread Scheduler in Java


A component of Java that decides which thread to run or execute and which thread to
wait is called a thread scheduler in Java. In Java, a thread is only chosen by a thread
scheduler if it is in the runnable state. However, if there is more than one thread in the
runnable state, it is up to the thread scheduler to pick one of the threads and ignore the
other ones. There are some criteria that decide which thread will execute first. There are
two factors for scheduling a thread i.e. Priority and Time of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it
means that thread has got a better chance of getting picked up by the thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable state,
then priority cannot be the factor to pick a thread from these two threads. In such a
case, arrival time of thread is considered by the thread scheduler. A thread that arrived
first gets the preference over the other threads.

Thread Scheduler Algorithms


On the basis of the above-mentioned factors, the scheduling algorithm is followed by a
Java thread scheduler.

Difference between JDK, JRE, and JVM

First Come First Serve Scheduling:


In this scheduling algorithm, the scheduler picks the threads thar arrive first in the
runnable queue. Observe the following table:

Threads Time of Arrival

t1 0

t2 1

t3 2

t4 3

In the above table, we can see that Thread t1 has arrived first, then Thread t2, then t3,
and at last t4, and the order in which the threads will be processed is according to the
time of arrival of threads.
Hence, Thread t1 will be processed first, and Thread t4 will be processed last.

Time-slicing scheduling:
Usually, the First Come First Serve algorithm is non-preemptive, which is bad as it may
lead to infinite blocking (also known as starvation). To avoid that, some time-slices are
provided to the threads so that after some time, the running thread has to give up the
CPU. Thus, the other waiting threads also get time to run their job.

In the above diagram, each thread is given a time slice of 2 seconds. Thus, after 2
seconds, the first thread leaves the CPU, and the CPU is then captured by Thread2. The
same process repeats for the other threads too.
Preemptive-Priority Scheduling:
The name of the scheduling algorithm denotes that the algorithm is related to the
priority of the threads.

Suppose there are multiple threads available in the runnable state. The thread scheduler
picks that thread that has the highest priority. Since the algorithm is also preemptive,
therefore, time slices are also provided to the threads to avoid starvation. Thus, after
some time, even if the highest priority thread has not completed its job, it has to release
the CPU because of preemption.

Working of the Java Thread Scheduler


Let's understand the working of the Java thread scheduler. Suppose, there are five
threads that have different arrival times and different priorities. Now, it is the
responsibility of the thread scheduler to decide which thread will get the CPU first.

The thread scheduler selects the thread that has the highest priority, and the thread
begins the execution of the job. If a thread is already in runnable state and another
thread (that has higher priority) reaches in the runnable state, then the current thread is
pre-empted from the processor, and the arrived thread with higher priority gets the CPU
time.

When two threads (Thread 2 and Thread 3) having the same priorities and arrival time,
the scheduling will be decided on the basis of FCFS algorithm. Thus, the thread that
arrives first gets the opportunity to execute first.

Thread.sleep() in Java with Examples


The Java Thread class provides the two variant of the sleep() method. First one accepts
only an arguments, whereas the other variant accepts two arguments. The method
sleep() is being used to halt the working of a thread for a given amount of time. The
time up to which the thread remains in the sleeping state is known as the sleeping time
of the thread. After the sleeping time is over, the thread starts its execution from where
it has left.
The sleep() Method Syntax:
Following are the syntax of the sleep() method.

1. public static void sleep(long mls) throws InterruptedException   
2. public static void sleep(long mls, int n) throws InterruptedException   

The method sleep() with the one parameter is the native method, and the
implementation of the native method is accomplished in another programming
language. The other methods having the two parameters are not the native method.
That is, its implementation is accomplished in Java. We can access the sleep() methods
with the help of the Thread class, as the signature of the sleep() methods contain the
static keyword. The native, as well as the non-native method, throw a checked Exception.
Therefore, either try-catch block or the throws keyword can work here.

The Thread.sleep() method can be used with any thread. It means any other thread or
the main thread can invoke the sleep() method.

10 Sec

Exception Handling in Java - Javatpoint

Parameters:
The following are the parameters used in the sleep() method.

mls: The time in milliseconds is represented by the parameter mls. The duration for
which the thread will sleep is given by the method sleep().

n: It shows the additional time up to which the programmer or developer wants the
thread to be in the sleeping state. The range of n is from 0 to 999999.

The method does not return anything.

Important Points to Remember About the Sleep() Method


Whenever the Thread.sleep() methods execute, it always halts the execution of the
current thread.

Whenever another thread does interruption while the current thread is already in the
sleep mode, then the InterruptedException is thrown.
If the system that is executing the threads is busy, then the actual sleeping time of the
thread is generally more as compared to the time passed in arguments. However, if the
system executing the sleep() method has less load, then the actual sleeping time of the
thread is almost equal to the time passed in the argument.

Example of the sleep() method in Java : on the custom thread


The following example shows how one can use the sleep() method on the custom
thread.

FileName: TestSleepMethod1.java

1. class TestSleepMethod1 extends Thread{    
2.  public void run(){    
3.   for(int i=1;i<5;i++){   
4.   // the thread will sleep for the 500 milli seconds   
5.     try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}    
6.     System.out.println(i);    
7.   }    
8.  }    
9.  public static void main(String args[]){    
10.   TestSleepMethod1 t1=new TestSleepMethod1();    
11.   TestSleepMethod1 t2=new TestSleepMethod1();    
12.      
13.   t1.start();    
14.   t2.start();    
15.  }    
16. }    

Output:

1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time, the thread scheduler picks up another thread and so on.

Example of the sleep() Method in Java : on the main thread


FileName: TestSleepMethod2.java

1. // important import statements  
2. import java.lang.Thread;  
3. import java.io.*;  
4.   
5.   
6. public class TestSleepMethod2  
7. {  
8.     // main method  
9. public static void main(String argvs[])  
10. {  
11.   
12. try {  
13. for (int j = 0; j < 5; j++)  
14. {  
15.   
16. // The main thread sleeps for the 1000 milliseconds, which is 1 sec  
17. // whenever the loop runs  
18. Thread.sleep(1000);  
19.   
20. // displaying the value of the variable  
21. System.out.println(j);  
22. }  
23. }  
24. catch (Exception expn)   
25. {  
26. // catching the exception  
27. System.out.println(expn);  
28. }  
29. }  
30. }  

Output:

0
1
2
3
4

Example of the sleep() Method in Java: When the sleeping time is


-ive
The following example throws the exception IllegalArguementException when the time
for sleeping is negative.

FileName: TestSleepMethod3.java

1. // important import statements  
2. import java.lang.Thread;  
3. import java.io.*;  
4.   
5. public class TestSleepMethod3  
6. {  
7. // main method  
8. public static void main(String argvs[])  
9. {  
10. // we can also use throws keyword followed by  
11. // exception name for throwing the exception  
12. try   
13. {  
14. for (int j = 0; j < 5; j++)   
15. {  
16.   
17. // it throws the exception IllegalArgumentException  
18. // as the time is -ive which is -100  
19. Thread.sleep(-100);  
20.   
21. // displaying the variable's value  
22. System.out.println(j);  
23. }  
24. }  
25. catch (Exception expn)   
26. {  
27.   
28. // the exception iscaught here   
29. System.out.println(expn);  
30. }  
31. }  
32. }  

Output:

java.lang.IllegalArgumentException: timeout value is negative

Can we start a thread twice


No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.

Let's understand it by the example given below:

1. public class TestThreadTwice1 extends Thread{  
2.  public void run(){  
3.    System.out.println("running...");  
4.  }  
5.  public static void main(String args[]){  
6.   TestThreadTwice1 t1=new TestThreadTwice1();  
7.   t1.start();  
8.   t1.start();  
9.  }  
10. }  
Test it Now
Output:

running
Exception in thread "main" java.lang.IllegalThreadStateException

What if we call Java run() method directly


instead start() method?
o Each thread starts in a separate call stack.
o Invoking the run() method from the main thread, the run() method goes onto the current
call stack rather than at the beginning of a new call stack.

FileName: TestCallRun1.java

1. class TestCallRun1 extends Thread{  
2.  public void run(){  
3.    System.out.println("running...");  
4.  }  
5.  public static void main(String args[]){  
6.   TestCallRun1 t1=new TestCallRun1();  
7.   t1.run();//fine, but does not start a separate call stack  
8.  }  
9. }  
Test it Now

Output:

running...
Problem if you direct call run() method

FileName: TestCallRun2.java

Difference between JDK, JRE, and JVM

1. class TestCallRun2 extends Thread{  
2.  public void run(){  
3.   for(int i=1;i<5;i++){  
4.     try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
5.     System.out.println(i);  
6.   }  
7.  }  
8.  public static void main(String args[]){  
9.   TestCallRun2 t1=new TestCallRun2();  
10.   TestCallRun2 t2=new TestCallRun2();  
11.    
12.   t1.run();  
13.   t2.run();  
14.  }  
15. }  
Test it Now

Output:

1
2
3
4
1
2
3
4

As we can see in the above program that there is no context-switching because here t1
and t2 will be treated as normal object not thread object.

Java join() method


The join() method in Java is provided by the java.lang.Thread class that permits one
thread to wait until the other thread to finish its execution. Suppose th be the object the
class Thread whose thread is doing its execution currently, then the th.join(); statement
ensures that th is finished before the program does the execution of the next statement.
When there are more than one thread invoking the join() method, then it leads to
overloading on the join() method that permits the developer or programmer to mention
the waiting period. However, similar to the sleep() method in Java, the join() method is
also dependent on the operating system for the timing, so we should not assume that
the join() method waits equal to the time we mention in the parameters. The following
are the three overloaded join() methods.

Description of The Overloaded join() Method


join(): When the join() method is invoked, the current thread stops its execution and the
thread goes into the wait state. The current thread remains in the wait state until the
thread on which the join() method is invoked has achieved its dead state. If interruption
of the thread occurs, then it throws the InterruptedException.

Syntax:

1. public final void join() throws InterruptedException  

join(long mls): When the join() method is invoked, the current thread stops its
execution and the thread goes into the wait state. The current thread remains in the wait
state until the thread on which the join() method is invoked called is dead or the wait for
the specified time frame(in milliseconds) is over.

10 Sec

OOPs Concepts in Java


Syntax:

1. public final synchronized void join(long mls) throws InterruptedException, where mls is in mill
iseconds  

join(long mls, int nanos): When the join() method is invoked, the current thread stops
its execution and go into the wait state. The current thread remains in the wait state
until the thread on which the join() method is invoked called is dead or the wait for the
specified time frame(in milliseconds + nanos) is over.

Syntax:

1. public final synchronized void join(long mls, int nanos) throws InterruptedException, where 
mls is in milliseconds.  

Example of join() Method in Java


The following program shows the usage of the join() method.

FileName: ThreadJoinExample.java

1. // A Java program for understanding   
2. // the joining of threads  
3.   
4. // import statement  
5. import java.io.*;  
6.   
7. // The ThreadJoin class is the child class of the class Thread  
8. class ThreadJoin extends Thread  
9. {  
10. // overriding the run method  
11. public void run()  
12. {  
13. for (int j = 0; j < 2; j++)  
14. {  
15. try  
16. {  
17. // sleeping the thread for 300 milli seconds  
18. Thread.sleep(300);  
19. System.out.println("The current thread name is: " + Thread.currentThread().getName());  
20. }  
21. // catch block for catching the raised exception  
22. catch(Exception e)  
23. {  
24. System.out.println("The exception has been caught: " + e);  
25. }  
26. System.out.println( j );  
27. }  
28. }  
29. }  
30.   
31. public class ThreadJoinExample  
32. {  
33. // main method  
34. public static void main (String argvs[])  
35. {  
36.   
37. // creating 3 threads  
38. ThreadJoin th1 = new ThreadJoin();  
39. ThreadJoin th2 = new ThreadJoin();  
40. ThreadJoin th3 = new ThreadJoin();  
41.   
42. // thread th1 starts  
43. th1.start();  
44.   
45. // starting the second thread after when  
46. // the first thread th1 has ended or died.  
47. try  
48. {  
49. System.out.println("The current thread name is: "+ Thread.currentThread().getName());  
50.   
51. // invoking the join() method  
52. th1.join();  
53. }  
54.   
55. // catch block for catching the raised exception  
56. catch(Exception e)  
57. {  
58. System.out.println("The exception has been caught " + e);  
59. }  
60.   
61. // thread th2 starts  
62. th2.start();  
63.   
64. // starting the th3 thread after when the thread th2 has ended or died.  
65. try  
66. {  
67. System.out.println("The current thread name is: " + Thread.currentThread().getName());  
68. th2.join();  
69. }  
70.   
71. // catch block for catching the raised exception  
72. catch(Exception e)  
73. {  
74. System.out.println("The exception has been caught " + e);  
75. }  
76.   
77. // thread th3 starts  
78. th3.start();  
79. }  
80. }  

Output:

The current thread name is: main


The current thread name is: Thread - 0
0
The current thread name is: Thread - 0
1
The current thread name is: main
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1

Explanation: The above program shows that the second thread th2 begins after the first
thread th1 has ended, and the thread th3 starts its work after the second thread th2 has
ended or died.

The Join() Method: InterruptedException


We have learnt in the description of the join() method that whenever the interruption of
the thread occurs, it leads to the throwing of InterruptedException. The following
example shows the same.

FileName: ThreadJoinExample1.java

1. class ABC extends Thread  
2. {  
3. Thread threadToInterrupt;  
4. // overriding the run() method  
5. public void run()  
6. {  
7. // invoking the method interrupt  
8. threadToInterrupt.interrupt();  
9. }  
10. }  
11.   
12.   
13. public class ThreadJoinExample1  
14. {  
15. // main method  
16. public static void main(String[] argvs)  
17. {  
18. try  
19. {  
20. // creating an object of the class ABC  
21. ABC th1 = new ABC();  
22.   
23. th1.threadToInterrupt = Thread.currentThread();  
24. th1.start();  
25.   
26. // invoking the join() method leads   
27. // to the generation of InterruptedException  
28. th1.join();  
29. }  
30. catch (InterruptedException ex)  
31. {  
32. System.out.println("The exception has been caught. " + ex);  
33. }  
34. }  
35. }  

Output:

The exception has been caught. java.lang.InterruptedException

Some More Examples of the join() Method


Let' see some other examples.

Filename: TestJoinMethod1.java

1. class TestJoinMethod1 extends Thread{    
2.  public void run(){    
3.   for(int i=1;i<=5;i++){    
4.    try{    
5.     Thread.sleep(500);    
6.    }catch(Exception e){System.out.println(e);}    
7.   System.out.println(i);    
8.   }    
9.  }    
10. public static void main(String args[]){    
11.  TestJoinMethod1 t1=new TestJoinMethod1();    
12.  TestJoinMethod1 t2=new TestJoinMethod1();    
13.  TestJoinMethod1 t3=new TestJoinMethod1();    
14.  t1.start();    
15.  try{    
16.   t1.join();    
17.  }catch(Exception e){System.out.println(e);}    
18.     
19.  t2.start();    
20.  t3.start();    
21.  }    
22. }    

Output:

1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

We can see in the above example, when t1 completes its task then t2 and t3 starts
executing.

join(long miliseconds) Method Example


Filename: TestJoinMethod2.jav

1. class TestJoinMethod2 extends Thread{    
2.  public void run(){    
3.   for(int i=1;i<=5;i++){    
4.    try{    
5.     Thread.sleep(500);    
6.    }catch(Exception e){System.out.println(e);}    
7.   System.out.println(i);    
8.   }    
9.  }    
10. public static void main(String args[]){    
11.  TestJoinMethod2 t1=new TestJoinMethod2();    
12.  TestJoinMethod2 t2=new TestJoinMethod2();    
13.  TestJoinMethod2 t3=new TestJoinMethod2();    
14.  t1.start();    
15.  try{    
16.   t1.join(1500);    
17.  }catch(Exception e){System.out.println(e);}    
18.     
19.  t2.start();    
20.  t3.start();    
21.  }    
22. }    

Output:

1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the above example, when t1 completes its task for 1500 milliseconds(3 times), then t2
and t3 start executing.

Naming Thread and Current Thread


Naming Thread
The Thread class provides methods to change and get the name of a thread. By default,
each thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name
of the thread by using the setName() method. The syntax of setName() and getName()
methods are given below:

1. public String getName(): is used to return the name of a thread.  
2. public void setName(String name): is used to change the name of a thread.  

We can also set the name of a thread directly when we create a new thread using the
constructor of the class.

Example of naming a thread : Using setName() Method


FileName: TestMultiNaming1.java

1. class TestMultiNaming1 extends Thread{  
2.   public void run(){  
3.    System.out.println("running...");  
4.   }  
5.  public static void main(String args[]){  
6.   TestMultiNaming1 t1=new TestMultiNaming1();  
7.   TestMultiNaming1 t2=new TestMultiNaming1();  
8.   System.out.println("Name of t1:"+t1.getName());  
9.   System.out.println("Name of t2:"+t2.getName());  
10.    
11.   t1.start();  
12.   t2.start();  
13.   
14.   t1.setName("Sonoo Jaiswal");  
15.   System.out.println("After changing name of t1:"+t1.getName());  
16.  }  
17. }  
Test it Now

Output:

Prime Ministers of India | List of Prime Minister of India (1947-2020)

Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:Sonoo Jaiswal
running...
running...

Example of naming a thread : Without Using setName() Method


One can also set the name of a thread at the time of the creation of a thread, without
using the setName() method. Observe the following code.

FileName: ThreadNamingExample.java

1. // A Java program that shows how one can   
2. // set the name of a thread at the time  
3. // of creation of the thread  
4.   
5. // import statement  
6. import java.io.*;  
7.   
8. // The ThreadNameClass is the child class of the class Thread  
9. class ThreadName extends Thread  
10. {  
11.   
12. // constructor of the class  
13. ThreadName(String threadName)  
14. {  
15. // invoking the constructor of  
16. // the superclass, which is Thread class.  
17. super(threadName);  
18. }  
19.   
20. // overriding the method run()  
21. public void run()  
22. {  
23. System.out.println(" The thread is executing....");  
24. }  
25. }  
26.   
27. public class ThreadNamingExample  
28. {  
29. // main method  
30. public static void main (String argvs[])  
31. {  
32. // creating two threads and settting their name  
33. // using the contructor of the class  
34. ThreadName th1 = new ThreadName("JavaTpoint1");  
35. ThreadName th2 = new ThreadName("JavaTpoint2");  
36.   
37. // invoking the getName() method to get the names  
38. // of the thread created above  
39. System.out.println("Thread - 1: " + th1.getName());  
40. System.out.println("Thread - 2: " + th2.getName());  
41.   
42.   
43. // invoking the start() method on both the threads  
44. th1.start();  
45. th2.start();  
46. }  
47. }  

Output:

Thread - 1: JavaTpoint1
Thread - 2: JavaTpoint2
The thread is executing....
The thread is executing....
Current Thread
The currentThread() method returns a reference of the currently executing thread.

1. public static Thread currentThread()    

Example of currentThread() method


FileName: TestMultiNaming2.java

1. class TestMultiNaming2 extends Thread{  
2.  public void run(){  
3.   System.out.println(Thread.currentThread().getName());  
4.  }  
5.  public static void main(String args[]){  
6.   TestMultiNaming2 t1=new TestMultiNaming2();  
7.   TestMultiNaming2 t2=new TestMultiNaming2();  
8.   
9.   t1.start();  
10.   t2.start();  
11.  }  
12. }  
Test it Now

Output:

Thread-0
Thread-1

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority


Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the


priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority()


method updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).

Keep Watching

Competitive questions on Structures in Hindi


00:00/03:34

Competitive questions on Structures in Hindi

Keep Watching
Competitive questions on Structures in Hindi

Keep Watching

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


FileName: ThreadPriorityExample.java

1. // Importing the required classes  
2. import java.lang.*;  
3.   
4. public class ThreadPriorityExample extends Thread   
5. {  
6.   
7. // Method 1  
8. // Whenever the start() method is called by a thread  
9. // the run() method is invoked  
10. public void run()  
11. {  
12. // the print statement  
13. System.out.println("Inside the run() method");  
14. }  
15.   
16. // the main method  
17. public static void main(String argvs[])  
18. {  
19. // Creating threads with the help of ThreadPriorityExample class  
20. ThreadPriorityExample th1 = new ThreadPriorityExample();  
21. ThreadPriorityExample th2 = new ThreadPriorityExample();  
22. ThreadPriorityExample th3 = new ThreadPriorityExample();  
23.   
24. // We did not mention the priority of the thread.  
25. // Therefore, the priorities of the thread is 5, the default value  
26.   
27. // 1st Thread  
28. // Displaying the priority of the thread  
29. // using the getPriority() method  
30. System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
31.   
32. // 2nd Thread   
33. // Display the priority of the thread  
34. System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
35.   
36. // 3rd Thread   
37. // // Display the priority of the thread  
38. System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
39.   
40. // Setting priorities of above threads by  
41. // passing integer arguments  
42. th1.setPriority(6);  
43. th2.setPriority(3);  
44. th3.setPriority(9);  
45.   
46. // 6  
47. System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
48.   
49. // 3  
50. System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
51.   
52. // 9  
53. System.out.println("Priority of the thread th3 is : " + th3.getPriority());  
54.   
55. // Main thread  
56.   
57. // Displaying name of the currently executing thread   
58. System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());  
59.   
60. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
61.   
62. // Priority of the main thread is 10 now  
63. Thread.currentThread().setPriority(10);  
64.   
65. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
66. }  
67. }  

Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

We know that a thread with high priority will get preference over lower priority threads
when it comes to the execution of threads. However, there can be other scenarios where
two threads can have the same priority. All of the processing, in order to look after the
threads, is done by the Java thread scheduler. Refer to the following example to
comprehend what will happen if two threads have the same priority.

FileName: ThreadPriorityExample1.java

1. // importing the java.lang package  
2. import java.lang.*;  
3.   
4. public class ThreadPriorityExample1 extends Thread   
5. {  
6.   
7. // Method 1  
8. // Whenever the start() method is called by a thread  
9. // the run() method is invoked  
10. public void run()  
11. {  
12. // the print statement  
13. System.out.println("Inside the run() method");  
14. }  
15.   
16.   
17. // the main method  
18. public static void main(String argvs[])  
19. {  
20.   
21. // Now, priority of the main thread is set to 7  
22. Thread.currentThread().setPriority(7);  
23.   
24. // the current thread is retrieved  
25. // using the currentThread() method  
26.   
27. // displaying the main thread priority  
28. // using the getPriority() method of the Thread class  
29. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
30.   
31. // creating a thread by creating an object of the class ThreadPriorityExample1  
32. ThreadPriorityExample1 th1 = new ThreadPriorityExample1();  
33.   
34. // th1 thread is the child of the main thread  
35. // therefore, the th1 thread also gets the priority 7  
36.   
37. // Displaying the priority of the current thread  
38. System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
39. }  
40. }  

Output:

Priority of the main thread is : 7


Priority of the thread th1 is : 7

Explanation: If there are two threads that have the same priority, then one can not
predict which thread will get the chance to execute first. The execution then is
dependent on the thread scheduler's algorithm (First Come First Serve, Round-Robin,
etc.)

Example of IllegalArgumentException
We know that if the value of the parameter newPriority of the method getPriority() goes
out of the range (1 to 10), then we get the IllegalArgumentException. Let's observe the
same with the help of an example.

FileName: IllegalArgumentException.java

1. // importing the java.lang package  
2. import java.lang.*;  
3.   
4. public class IllegalArgumentException extends Thread   
5. {  
6.   
7. // the main method  
8. public static void main(String argvs[])  
9. {  
10.   
11. // Now, priority of the main thread is set to 17, which is greater than 10  
12. Thread.currentThread().setPriority(17);  
13.   
14. // The current thread is retrieved  
15. // using the currentThread() method  
16.   
17. // displaying the main thread priority  
18. // using the getPriority() method of the Thread class  
19. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
20.   
21. }  
22. }  

When we execute the above program, we get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException


at java.base/java.lang.Thread.setPriority(Thread.java:1141)
at IllegalArgumentException.main(IllegalArgumentException.java:12)

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.

You can see all the detail by typing the jconsole in the command prompt. The jconsole
tool provides information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java


o It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user


thread?
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.

C++ vs Java

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as daemon thread or use
status) thread.

2) public boolean isDaemon() is used to check that current is daemon.

Simple example of Daemon thread in java


File: MyThread.java

1. public class TestDaemonThread1 extends Thread{  
2.  public void run(){  
3.   if(Thread.currentThread().isDaemon()){//checking for daemon thread  
4.    System.out.println("daemon thread work");  
5.   }  
6.   else{  
7.   System.out.println("user thread work");  
8.  }  
9.  }  
10.  public static void main(String[] args){  
11.   TestDaemonThread1 t1=new TestDaemonThread1();//creating thread  
12.   TestDaemonThread1 t2=new TestDaemonThread1();  
13.   TestDaemonThread1 t3=new TestDaemonThread1();  
14.   
15.   t1.setDaemon(true);//now t1 is daemon thread  
16.     
17.   t1.start();//starting threads  
18.   t2.start();  
19.   t3.start();  
20.  }  
21. }  
Test it Now

Output:

daemon thread work


user thread work
user thread work

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.

File: MyThread.java

1. class TestDaemonThread2 extends Thread{  
2.  public void run(){  
3.   System.out.println("Name: "+Thread.currentThread().getName());  
4.   System.out.println("Daemon: "+Thread.currentThread().isDaemon());  
5.  }  
6.   
7.  public static void main(String[] args){  
8.   TestDaemonThread2 t1=new TestDaemonThread2();  
9.   TestDaemonThread2 t2=new TestDaemonThread2();  
10.   t1.start();  
11.   t1.setDaemon(true);//will throw exception here  
12.   t2.start();  
13.  }  
14. }  
Test it Now

Output:

exception in thread main: java.lang.IllegalThreadStateException

Java Thread Pool


Java Thread pool represents a group of worker threads that are waiting for the job and
reused many times.

In the case of a thread pool, a group of fixed-size threads is created. A thread from the
thread pool is pulled out and assigned a job by the service provider. After completion of
the job, the thread is contained in the thread pool again.

Thread Pool Methods


newFixedThreadPool(int s): The method creates a thread pool of the fixed size s.

newCachedThreadPool(): The method creates a new thread pool that creates the new
threads when needed but will still use the previously created thread whenever they are
available to use.

21.7M

473

C++ vs Java

newSingleThreadExecutor(): The method creates a new thread.

Advantage of Java Thread Pool


Better performance It saves time because there is no need to create a new thread.

Real time usage


It is used in Servlet and JSP where the container creates a thread pool to process the
request.
Example of Java Thread Pool
Let's see a simple example of the Java thread pool using ExecutorService and Executors.

File: WorkerThread.java

1. import java.util.concurrent.ExecutorService;  
2. import java.util.concurrent.Executors;  
3. class WorkerThread implements Runnable {  
4.     private String message;  
5.     public WorkerThread(String s){  
6.         this.message=s;  
7.     }  
8.      public void run() {  
9.         System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);  
10.         processmessage();//call processmessage method that sleeps the thread for 2 seconds  
11.         System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name  
12.     }  
13.     private void processmessage() {  
14.         try {  Thread.sleep(2000);  } catch (InterruptedException e) { e.printStackTrace(); }  
15.     }  
16. }  

File: TestThreadPool.java

1. public class TestThreadPool {  
2.      public static void main(String[] args) {  
3.         ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads 
 
4.         for (int i = 0; i < 10; i++) {  
5.             Runnable worker = new WorkerThread("" + i);  
6.             executor.execute(worker);//calling execute method of ExecutorService  
7.           }  
8.         executor.shutdown();  
9.         while (!executor.isTerminated()) {   }  
10.   
11.         System.out.println("Finished all threads");  
12.     }  
13.  }  

Output:

pool-1-thread-1 (Start) message = 0


pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
download this example

Thread Pool Example: 2


Let's see another example of the thread pool.

FileName: ThreadPoolExample.java

1. // important import statements  
2. import java.util.Date;  
3. import java.util.concurrent.ExecutorService;  
4. import java.util.concurrent.Executors;  
5. import java.text.SimpleDateFormat;  
6.   
7.   
8. class Tasks implements Runnable  
9. {  
10. private String taskName;  
11.   
12. // constructor of the class Tasks  
13. public Tasks(String str)  
14. {  
15. // initializing the field taskName   
16. taskName = str;  
17. }  
18.   
19. // Printing the task name and then sleeps for 1 sec  
20. // The complete process is getting repeated five times  
21. public void run()  
22. {  
23. try  
24. {  
25. for (int j = 0; j <= 5; j++)  
26. {  
27. if (j == 0)  
28. {  
29. Date dt = new Date();  
30. SimpleDateFormat sdf = new SimpleDateFormat("hh : mm : ss");  
31.   
32. //prints the initialization time for every task  
33. System.out.println("Initialization time for the task name: "+ taskName + " = " + sdf.format(dt));  
34.   
35. }  
36. else  
37. {  
38. Date dt = new Date();  
39. SimpleDateFormat sdf = new SimpleDateFormat("hh : mm : ss");  
40.   
41. // prints the execution time for every task  
42. System.out.println("Time of execution for the task name: " + taskName + " = " +sdf.format(dt));  
43.   
44. }  
45.   
46. // 1000ms = 1 sec  
47. Thread.sleep(1000);  
48. }  
49.   
50. System.out.println(taskName + " is complete.");  
51. }  
52.   
53. catch(InterruptedException ie)  
54. {  
55. ie.printStackTrace();  
56. }  
57. }  
58. }  
59.   
60. public class ThreadPoolExample  
61. {  
62. // Maximum number of threads in the thread pool  
63. static final int MAX_TH = 3;              
64.   
65. // main method  
66. public static void main(String argvs[])  
67. {  
68. // Creating five new tasks  
69. Runnable rb1 = new Tasks("task 1");  
70. Runnable rb2 = new Tasks("task 2");  
71. Runnable rb3 = new Tasks("task 3");  
72. Runnable rb4 = new Tasks("task 4");  
73. Runnable rb5 = new Tasks("task 5");   
74.   
75. // creating a thread pool with MAX_TH number of  
76. // threads size the pool size is fixed  
77. ExecutorService pl = Executors.newFixedThreadPool(MAX_TH);  
78.   
79. // passes the Task objects to the pool to execute (Step 3)  
80. pl.execute(rb1);  
81. pl.execute(rb2);  
82. pl.execute(rb3);  
83. pl.execute(rb4);  
84. pl.execute(rb5);  
85.   
86. // pool is shutdown  
87. pl.shutdown();    
88. }  
89. }  

Output:

Initialization time for the task name: task 1 = 06 : 13 : 02


Initialization time for the task name: task 2 = 06 : 13 : 02
Initialization time for the task name: task 3 = 06 : 13 : 02
Time of execution for the task name: task 1 = 06 : 13 : 04
Time of execution for the task name: task 2 = 06 : 13 : 04
Time of execution for the task name: task 3 = 06 : 13 : 04
Time of execution for the task name: task 1 = 06 : 13 : 05
Time of execution for the task name: task 2 = 06 : 13 : 05
Time of execution for the task name: task 3 = 06 : 13 : 05
Time of execution for the task name: task 1 = 06 : 13 : 06
Time of execution for the task name: task 2 = 06 : 13 : 06
Time of execution for the task name: task 3 = 06 : 13 : 06
Time of execution for the task name: task 1 = 06 : 13 : 07
Time of execution for the task name: task 2 = 06 : 13 : 07
Time of execution for the task name: task 3 = 06 : 13 : 07
Time of execution for the task name: task 1 = 06 : 13 : 08
Time of execution for the task name: task 2 = 06 : 13 : 08
Time of execution for the task name: task 3 = 06 : 13 : 08
task 2 is complete.
Initialization time for the task name: task 4 = 06 : 13 : 09
task 1 is complete.
Initialization time for the task name: task 5 = 06 : 13 : 09
task 3 is complete.
Time of execution for the task name: task 4 = 06 : 13 : 10
Time of execution for the task name: task 5 = 06 : 13 : 10
Time of execution for the task name: task 4 = 06 : 13 : 11
Time of execution for the task name: task 5 = 06 : 13 : 11
Time of execution for the task name: task 4 = 06 : 13 : 12
Time of execution for the task name: task 5 = 06 : 13 : 12
Time of execution for the task name: task 4 = 06 : 13 : 13
Time of execution for the task name: task 5 = 06 : 13 : 13
Time of execution for the task name: task 4 = 06 : 13 : 14
Time of execution for the task name: task 5 = 06 : 13 : 14
task 4 is complete.
task 5 is complete.

Explanation: It is evident by looking at the output of the program that tasks 4 and 5 are
executed only when the thread has an idle thread. Until then, the extra tasks are put in
the queue.

The takeaway from the above example is when one wants to execute 50 tasks but is not
willing to create 50 threads. In such a case, one can create a pool of 10 threads. Thus, 10
out of 50 tasks are assigned, and the rest are put in the queue. Whenever any thread out
of 10 threads becomes idle, it picks up the 11 th task. The other pending tasks are treated
the same way.

Risks involved in Thread Pools


The following are the risk involved in the thread pools.

Deadlock: It is a known fact that deadlock can come in any program that involves
multithreading, and a thread pool introduces another scenario of deadlock. Consider a
scenario where all the threads that are executing are waiting for the results from the
threads that are blocked and waiting in the queue because of the non-availability of
threads for the execution.

Thread Leakage: Leakage of threads occurs when a thread is being removed from the
pool to execute a task but is not returning to it after the completion of the task. For
example, when a thread throws the exception and the pool class is not able to catch this
exception, then the thread exits and reduces the thread pool size by 1. If the same thing
repeats a number of times, then there are fair chances that the pool will become empty,
and hence, there are no threads available in the pool for executing other requests.
Resource Thrashing: A lot of time is wasted in context switching among threads when
the size of the thread pool is very large. Whenever there are more threads than the
optimal number may cause the starvation problem, and it leads to resource thrashing.

Points to Remember
Do not queue the tasks that are concurrently waiting for the results obtained from the
other tasks. It may lead to a deadlock situation, as explained above.

Care must be taken whenever threads are used for the operation that is long-lived. It
may result in the waiting of thread forever and will finally lead to the leakage of the
resource.

In the end, the thread pool has to be ended explicitly. If it does not happen, then the
program continues to execute, and it never ends. Invoke the shutdown() method on the
thread pool to terminate the executor. Note that if someone tries to send another task
to the executor after shutdown, it will throw a RejectedExecutionException.

One needs to understand the tasks to effectively tune the thread pool. If the given tasks
are contrasting, then one should look for pools for executing different varieties of tasks
so that one can properly tune them.

To reduce the probability of running JVM out of memory, one can control the maximum
threads that can run in JVM. The thread pool cannot create new threads after it has
reached the maximum limit.

A thread pool can use the same used thread if the thread has finished its execution.
Thus, the time and resources used for the creation of a new thread are saved.

Tuning the Thread Pool


The accurate size of a thread pool is decided by the number of available processors and
the type of tasks the threads have to execute. If a system has the P processors that have
only got the computation type processes, then the maximum size of the thread pool of
P or P + 1 achieves the maximum efficiency. However, the tasks may have to wait for
I/O, and in such a scenario, one has to take into consideration the ratio of the waiting
time (W) and the service time (S) for the request; resulting in the maximum size of the
pool P * (1 + W / S) for the maximum efficiency.

Conclusion
A thread pool is a very handy tool for organizing applications, especially on the server-
side. Concept-wise, a thread pool is very easy to comprehend. However, one may have
to look at a lot of issues when dealing with a thread pool. It is because the thread pool
comes with some risks involved it (risks are discussed above).

ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such a
way, we can suspend, resume or interrupt a group of threads by a single method call.

Note: Now suspend(), resume() and stop() methods are deprecated.

Java thread group is implemented by java.lang.ThreadGroup class.

A ThreadGroup represents a set of threads. A thread group can also include the other
thread group. The thread group creates a tree in which every thread group except the
initial thread group has a parent.

A thread is allowed to access information about its own thread group, but it cannot
access the information about its thread group's parent thread group or any other thread
groups.

Skip Ad

Constructors of ThreadGroup class


There are only two constructors of ThreadGroup class.

No. Constructor Description

1) ThreadGroup(String name) creates a thread group with given name.

2) ThreadGroup(ThreadGroup parent, String creates a thread group with a given parent group an
name) name.

Methods of ThreadGroup class


There are many methods in ThreadGroup class. A list of ThreadGroup methods is given
below.

S.N Modifier and Method Description


. Type

1) void checkAccess() This method determines if the currently running threa


has permission to modify the thread group.

2) int activeCount() This method returns an estimate of the number o


active threads in the thread group and its subgroups.

3) int activeGroupCount() This method returns an estimate of the number o


active groups in the thread group and its subgroups.

4) void destroy() This method destroys the thread group and all of it
subgroups.

5) int enumerate(Thread[] list) This method copies into the specified array every activ
thread in the thread group and its subgroups.

6) int getMaxPriority() This method returns the maximum priority of the threa
group.

7) String getName() This method returns the name of the thread group.

8) ThreadGroup getParent() This method returns the parent of the thread group.

9) void interrupt() This method interrupts all threads in the thread group.

10) boolean isDaemon() This method tests if the thread group is a daemo
thread group.
11) void setDaemon(boolean This method changes the daemon status of the threa
daemon) group.

12) boolean isDestroyed() This method tests if this thread group has bee
destroyed.

13) void list() This method prints information about the thread grou
to the standard output.

14) boolean parentOf(ThreadGroup g This method tests if the thread group is either th
thread group argument or one of its ancestor threa
groups.

15) void suspend() This method is used to suspend all threads in th


thread group.

16) void resume() This method is used to resume all threads in the threa
group which was suspended using suspend() method.

17) void setMaxPriority(int pri) This method sets the maximum priority of the group.

18) void stop() This method is used to stop all threads in the threa
group.

19) String toString() This method returns a string representation of th


Thread group.

Let's see a code to group multiple threads.

1. ThreadGroup tg1 = new ThreadGroup("Group A");   
2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");     
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");     
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");    
Now all 3 threads belong to one group. Here, tg1 is the thread group name,
MyRunnable is the class that implements Runnable interface and "one", "two" and
"three" are the thread names.

Now we can interrupt all threads by a single line of code only.

1. Thread.currentThread().getThreadGroup().interrupt();  

ThreadGroup Example
File: ThreadGroupDemo.java

1. public class ThreadGroupDemo implements Runnable{    
2.     public void run() {    
3.           System.out.println(Thread.currentThread().getName());    
4.     }    
5.    public static void main(String[] args) {    
6.       ThreadGroupDemo runnable = new ThreadGroupDemo();    
7.           ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");    
8.               
9.           Thread t1 = new Thread(tg1, runnable,"one");    
10.           t1.start();    
11.           Thread t2 = new Thread(tg1, runnable,"two");    
12.           t2.start();    
13.           Thread t3 = new Thread(tg1, runnable,"three");    
14.           t3.start();    
15.                  
16.           System.out.println("Thread Group Name: "+tg1.getName());    
17.          tg1.list();    
18.     
19.     }    
20.    }    

Output:

one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]

Thread Pool Methods Example: int activeCount()


Let's see how one can use the method activeCount().

FileName: ActiveCountExample.java

1. // code that illustrates the activeCount() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the  class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 1000; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered " + e);  
29. }  
30. }  
31. }  
32. }  
33.   
34. public class ActiveCountExample  
35. {  
36. // main method  
37. public static void main(String argvs[])  
38. {  
39. // creating the thread group  
40. ThreadGroup tg = new ThreadGroup("The parent group of threads");  
41.   
42. ThreadNew th1 = new ThreadNew("first", tg);  
43. System.out.println("Starting the first");  
44.   
45. ThreadNew th2 = new ThreadNew("second", tg);  
46. System.out.println("Starting the second");  
47.   
48. // checking the number of active thread by invoking the activeCount() method  
49. System.out.println("The total number of active threads are: " + tg.activeCount());  
50. }  
51. }  

Output:

Starting the first


Starting the second
The total number of active threads are: 2

Thread Pool Methods Example: int activeGroupCount()


Now, we will learn how one can use the activeGroupCount() method in the code.
FileName: ActiveGroupCountExample.java

1. // Java code illustrating the activeGroupCount() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the  class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered " + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class ActiveGroupCountExample  
38. {  
39. // main method  
40. public static void main(String argvs[])  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("The parent group of threads");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. // checking the number of active thread by invoking the activeGroupCount() method  
54. System.out.println("The total number of active thread groups are: " + tg.activeGroupCount());  
55. }  
56. }  

Output:

Starting the first


Starting the second
The total number of active thread groups are: 1
the second thread has finished executing
the first thread has finished executing

Thread Pool Methods Example: void destroy()


Now, we will learn how one can use the destroy() method in the code.
FileName: DestroyExample.java

1. // Code illustrating the destroy() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the  class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered " + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class DestroyExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. // waiting until the other threads has been finished  
54. th1.join();  
55. th2.join();  
56.   
57. // destroying the child thread group  
58. tg1.destroy();  
59. System.out.println(tg1.getName() + " is destroyed.");  
60.   
61. // destroying the parent thread group  
62. tg.destroy();  
63. System.out.println(tg.getName() + " is destroyed.");  
64. }  
65. }  
Output:

Starting the first


Starting the second
the first thread has finished executing
the second thread has finished executing
the child group is destroyed.
the parent group is destroyed.

Thread Pool Methods Example: int enumerate()


Now, we will learn how one can use the enumerate() method in the code.

FileName: EnumerateExample.java

1. // Code illustrating the enumerate() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered " + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class EnumerateExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. // returning the number of threads kept in this array  
54. Thread[] grp = new Thread[tg.activeCount()];  
55. int cnt = tg.enumerate(grp);  
56. for (int j = 0; j < cnt; j++)   
57. {  
58. System.out.println("Thread " + grp[j].getName() + " is found.");  
59. }  
60. }  
61. }  

Output:

Starting the first


Starting the second
Thread the first is found.
Thread the second is found.
the first thread has finished executing
the second thread has finished executing

Thread Pool Methods Example: int getMaxPriority()


The following code shows the working of the getMaxPriority() method.

FileName: GetMaxPriorityExample.java

1. // Code illustrating the getMaxPriority() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered " + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class GetMaxPriorityExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. int priority = tg.getMaxPriority();  
54.   
55. System.out.println("The maximum priority of the parent ThreadGroup: " + priority);  
56.   
57.   
58. }  
59. }  

Output:

Starting the first


Starting the second
The maximum priority of the parent ThreadGroup: 10
the first thread has finished executing
the second thread has finished executing

Thread Pool Methods Example: ThreadGroup


getParent()
Now, we will learn how one can use the getParent() method in the code.

FileName: GetParentExample.java

1. // Code illustrating the getParent() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered" + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class GetMaxPriorityExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. // printing the parent ThreadGroup   
54. // of both child and parent threads  
55. System.out.println("The ParentThreadGroup for " + tg.getName() + " is " + tg.getParent().getNa
me());  
56. System.out.println("The ParentThreadGroup for " + tg1.getName() + " is " + tg1.getParent().getN
ame());  
57.   
58.   
59. }  
60. }  

Output:

Starting the first


Starting the second
The ParentThreadGroup for the parent group is main
The ParentThreadGroup for the child group is the parent group
the first thread has finished executing
the second thread has finished executing

Thread Pool Methods Example: void interrupt()


The following program illustrates how one can use the interrupt() method.

FileName: InterruptExample.java

1. // Code illustrating the interrupt() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered " + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class InterruptExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. // invoking the interrupt method  
54. tg.interrupt();  
55.   
56. }  
57. }  

Output:

Starting the first


Starting the second
The exception has been encountered java.lang.InterruptedException: sleep
interrupted
The exception has been encountered java.lang.InterruptedException: sleep
interrupted
the second thread has finished executing
the first thread has finished executing

Thread Pool Methods Example: boolean isDaemon()


The following program illustrates how one can use the isDaemon() method.

FileName: IsDaemonExample.java

1. // Code illustrating the isDaemon() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered" + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class IsDaemonExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. if (tg.isDaemon() == true)  
54. {  
55. System.out.println("The group is a daemon group.");  
56. }  
57. else  
58. {  
59. System.out.println("The group is not a daemon group.");  
60. }  
61.   
62. }  
63. }  

Output:

Starting the first


Starting the second
The group is not a daemon group.
the second thread has finished executing
the first thread has finished executing
Thread Pool Methods Example: boolean isDestroyed()
The following program illustrates how one can use the isDestroyed() method.

FileName: IsDestroyedExample.java

1. // Code illustrating the isDestroyed() method  
2.   
3. // import statement  
4. import java.lang.*;  
5.   
6.   
7. class ThreadNew extends Thread  
8. {  
9. // constructor of the class  
10. ThreadNew(String tName, ThreadGroup tgrp)  
11. {  
12. super(tgrp, tName);  
13. start();  
14. }  
15.   
16. // overriding the run() method  
17. public void run()  
18. {  
19.   
20. for (int j = 0; j < 100; j++)  
21. {  
22. try  
23. {  
24. Thread.sleep(5);  
25. }  
26. catch (InterruptedException e)  
27. {  
28. System.out.println("The exception has been encountered" + e);  
29. }  
30.   
31. }  
32.   
33. System.out.println(Thread.currentThread().getName() + " thread has finished executing");  
34. }  
35. }  
36.   
37. public class IsDestroyedExample   
38. {  
39. // main method  
40. public static void main(String argvs[]) throws SecurityException, InterruptedException  
41. {  
42. // creating the thread group  
43. ThreadGroup tg = new ThreadGroup("the parent group");  
44.   
45. ThreadGroup tg1 = new ThreadGroup(tg, "the child group");  
46.   
47. ThreadNew th1 = new ThreadNew("the first", tg);  
48. System.out.println("Starting the first");  
49.   
50. ThreadNew th2 = new ThreadNew("the second", tg);  
51. System.out.println("Starting the second");  
52.   
53. if (tg.isDestroyed() == true)  
54. {  
55. System.out.println("The group has been destroyed.");  
56. }  
57. else  
58. {  
59. System.out.println("The group has not been destroyed.");  
60. }  
61.   
62. }  
63. }  
Output:

Starting the first


Starting the second
The group has not been destroyed.
the first thread has finished executing
the second thread has finished executing

Java Shutdown Hook


A special construct that facilitates the developers to add some code that has to be run
when the Java Virtual Machine (JVM) is shutting down is known as the Java shutdown
hook. The Java shutdown hook comes in very handy in the cases where one needs to
perform some special cleanup work when the JVM is shutting down. Note that handling
an operation such as invoking a special method before the JVM terminates does not
work using a general construct when the JVM is shutting down due to some external
factors. For example, whenever a kill request is generated by the operating system or
due to resource is not allocated because of the lack of free memory, then in such a case,
it is not possible to invoke the procedure. The shutdown hook solves this problem
comfortably by providing an arbitrary block of code.

Taking at a surface level, learning about the shutdown hook is straightforward. All one
has to do is to derive a class using the java.lang.Thread class, and then provide the code
for the task one wants to do in the run() method when the JVM is going to shut down.
For registering the instance of the derived class as the shutdown hook, one has to
invoke the method Runtime.getRuntime().addShutdownHook(Thread), whereas for
removing the already registered shutdown hook, one has to invoke the
removeShutdownHook(Thread) method.

In nutshell, the shutdown hook can be used to perform cleanup resources or save the
state when JVM shuts down normally or abruptly. Performing clean resources means
closing log files, sending some alerts, or something else. So if you want to execute some
code before JVM shuts down, use the shutdown hook.

When does the JVM shut down?


The JVM shuts down when:

22.7M

524

Features of Java - Javatpoint


o user presses ctrl+c on the command prompt
o System.exit(int) method is invoked
o user logoff
o user shutdown etc.

The addShutdownHook(Thread hook) method


The addShutdownHook() method of the Runtime class is used to register the thread
with the Virtual Machine.

Syntax:

1. public void addShutdownHook(Thread hook){}  

The object of the Runtime class can be obtained by calling the static factory method
getRuntime(). For example:

1. Runtime r = Runtime.getRuntime();  

The removeShutdownHook(Thread hook) method


The removeShutdownHook() method of the Runtime class is invoked to remove the
registration of the already registered shutdown hooks.

Syntax:

1. public boolean removeShutdownHook(Thread hook){ }    

True value is returned by the method, when the method successfully de-register the
registered hooks; otherwise returns false.

Factory method
The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook


FileName: MyThread.java

1. class MyThread extends Thread{    
2.     public void run(){    
3.         System.out.println("shut down hook task completed..");    
4.     }    
5. }    
6.     
7. public class TestShutdown1{    
8. public static void main(String[] args)throws Exception {    
9.     
10. Runtime r=Runtime.getRuntime();    
11. r.addShutdownHook(new MyThread());    
12.         
13. System.out.println("Now main sleeping... press ctrl+c to exit");    
14. try{Thread.sleep(3000);}catch (Exception e) {}    
15. }    
16. }    

Output:

Now main sleeping... press ctrl+c to exit


shut down hook task completed.

Same example of Shutdown Hook by anonymous class:


FileName: TestShutdown2.java

1. public class TestShutdown2{  
2. public static void main(String[] args)throws Exception {  
3.   
4. Runtime r=Runtime.getRuntime();  
5.   
6. r.addShutdownHook(new Thread(){  
7. public void run(){  
8.     System.out.println("shut down hook task completed..");  
9.     }  
10. }  
11. );  
12.       
13. System.out.println("Now main sleeping... press ctrl+c to exit");  
14. try{Thread.sleep(3000);}catch (Exception e) {}  
15. }  
16. }  

Output:

Now main sleeping... press ctrl+c to exit


shut down hook task completed.

Java Runtime class


Java Runtime class is used to interact with java runtime environment. Java Runtime class
provides methods to execute a process, invoke GC, get total and free memory etc. There
is only one instance of java.lang.Runtime class is available for one java application.

The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Important methods of Java Runtime class

No Method Description
.

1) public static Runtime getRuntime() returns the instance of Runtime class.

2) public void exit(int status) terminates the current virtual machine.

3) public void addShutdownHook(Thread hook) registers new hook thread.

4) public Process exec(String command)throws executes given command in a separat


IOException process.

5) public int availableProcessors() returns no. of available processors.

6) public long freeMemory() returns amount of free memory in JVM.

7) public long totalMemory() returns amount of total memory in JVM.

Java Runtime exec() method


1. public class Runtime1{  
2.  public static void main(String args[])throws Exception{  
3.   Runtime.getRuntime().exec("notepad");//will open a new notepad  
4.  }  
5. }  

How to shutdown system in Java


You can use shutdown -s command to shutdown system. For windows OS, you need to
provide full path of shutdown command e.g. c:\\Windows\\System32\\shutdown.

Here you can use -s switch to shutdown system, -r switch to restart system and -t switch
to specify time delay.

21.7M
473
C++ vs Java

1. public class Runtime2{  
2.  public static void main(String args[])throws Exception{  
3.   Runtime.getRuntime().exec("shutdown -s -t 0");  
4.  }  
5. }  

How to shutdown windows system in Java


1. public class Runtime2{  
2.  public static void main(String args[])throws Exception{  
3.   Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -s -t 0");  
4.  }  
5. }  

How to restart system in Java


1. public class Runtime3{  
2.  public static void main(String args[])throws Exception{  
3.   Runtime.getRuntime().exec("shutdown -r -t 0");  
4.  }  
5. }  
Java Runtime availableProcessors()
1. public class Runtime4{  
2.  public static void main(String args[])throws Exception{  
3.   System.out.println(Runtime.getRuntime().availableProcessors());  
4.  }  
5. }  

Java Runtime freeMemory() and totalMemory() method


In the given program, after creating 10000 instance, free memory will be less than the
previous free memory. But after gc() call, you will get more free memory.

1. public class MemoryTest{  
2.  public static void main(String args[])throws Exception{  
3.   Runtime r=Runtime.getRuntime();  
4.   System.out.println("Total Memory: "+r.totalMemory());  
5.   System.out.println("Free Memory: "+r.freeMemory());  
6.     
7.   for(int i=0;i<10000;i++){  
8.    new MemoryTest();  
9.   }  
10.   System.out.println("After creating 10000 instance, Free Memory: "+r.freeMemory());  
11.   System.gc();  
12.   System.out.println("After gc(), Free Memory: "+r.freeMemory());  
13.  }  
14. }  
Total Memory: 100139008
Free Memory: 99474824
After creating 10000 instance, Free Memory: 99310552
After gc(), Free Memory: 100182832

You might also like