Java Yesterday and Today Class Notes
Java Yesterday and Today Class Notes
x.clone() != x
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)
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.
publicclassObjectClass {
publicstaticvoidmain(String[] args) {
Datedate=newDate();
System.out.println(date.toString());
Date date2 = (Date) date.clone();
System.out.println(date2.toString());
}
}
Output:
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+"]";
}
System.out.println(person.toString());
System.out.println(person2.toString());
}
}
Output:
@Override
publicObjectclone() throws CloneNotSupportedException {
Personperson= (Person) super.clone();
return person;
}
Output:
false
true
@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;
}
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+"]";
}
booleanhasEqual=person.equals(person1);
System.out.println("Both objects equal :: "+hasEqual);
}
}
Output:
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.
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;
}
@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.
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
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.
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());
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.
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<>());
}
System.out.println("List is empty...");
synchedList.wait();
System.out.println("Waiting...");
}
String element =synchedList.remove(0);
return element;
}
}
synchedList.notifyAll();
System.out.println("notifyAll called!");
}
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.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!
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 −
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:
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.
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.
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
Output:
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
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:
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:
Method Description
Math.pow() It returns the value of first argument raised to the power to second argum
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.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
Method Description
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.
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.
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
Method Description
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.
By string literal
By new keyword
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
It's simple, to make Java more memory efficient (because no new objects are created if it exists
already in string constant pool).
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:
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).
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 s =newString();
charchars[] = {
'a',
'b',
'c'
}
;
String s =newString(chars);
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);
4. We can construct a String object that contains the same character sequence as
another String object using this constructor:
String(StringstrObj)
5. String class provides constructors that initialize a string when given a byte
array. Two forms are shown here:
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:
ABCDEF CDE
String(StringBufferstrBufObj) String(StringBuilderstrBuildObj)
Examples:
Stringstring=newString(newStringBuffer("JavaGuides"));
System.out.println(string);
String string2 =newString(newStringBuilder("JavaGuides"));
System.out.println(string2);
Output:
JavaGuidesJavaGuides
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.
Output:
Output:
Example 3: How to get the first and last character of the string
Output;
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.
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.
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.
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:
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:
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.
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:
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)
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:
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()
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:
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
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.
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.
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:
Example 3:
publicclassEqualsIgnoreCaseExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
boolean equal =str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: "+ equal);
}
}
Output:
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.
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);
}
}
}
If you need to extract more than one character at a time, you can use the getChars() method.
It has this general form:
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.
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);
}
}
demo
hashCode()
Returns a hash code for this string. The hash code for a String object is computed as
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:
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()
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
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()
publicclassLengthExample {
publicstaticvoidmain(String[] args) {
String str =newString("Java Guides");
int length =str.length();
System.out.println(" length of the string '"+ str +"' is :: "+ length);
}
}
Output:
regionMatches() methods
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,
The second form of replace() replaces one character sequence with another. It has this
general form:
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
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
Replaces the first substring of this string that matches the given regular expression with the
given replacement.
publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}
Output:
javaavaguides
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.
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:
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:
str.subSequence(begin, end)
str.substring(begin, end)
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:
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()
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
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.
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()
Output:
javaguides
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.
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:
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:
StringBuffer
StringBuffer Constructors
StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
StringBuffer()
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:
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:
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:
// 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);
Output:
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.
publicclassCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuffer builder =newStringBuffer("javaguides");
int capacity =builder.capacity();
// inital capacity
System.out.println(newStringBuffer().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.
Example 1: Returns the char value at the specified index of this string. The first char value is at
index 0.
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
publicstaticvoid charAtExample2() {
StringBuffer builder =newStringBuffer("Java Guides");
char ch1 =builder.charAt(builder.length());
System.out.println("character :: "+ ch1);
Output:
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:
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;
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.
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.
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:
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");
Output:
deleteCharAt(int index)
This method removes the char at the specified position in this sequence. This sequence is
shortened by one char.
Example: Example to delete character 'g' from string 'javaguides' using deleteCharAt() method.
Output:
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:
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
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);
Output:
j
a
v
a
g
u
i
d
e
s
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.
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
publicclassInsertExample {
publicstaticvoidmain(String[] args) {
CharSequencecharSequence=newStringBuilder("J2EE/");
builder =newStringBuffer("javaguides").insert(0, charSequence);
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.
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:
length()
Example:
publicclassLengthExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
int length =buffer.length();
System.out.println(" length of the string '"+ buffer +"' is :: "+ length);
}
}
Output:
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");
System.out.println(subBuffer);
}
}
Output:
javaguides
reverse()
publicclassReverseExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
StringBuffer reverse =buffer.reverse();
System.out.println("Reversed string :"+ reverse);
}
}
Output:
publicclassSetCharExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
buffer.setCharAt(0, 'J');
System.out.println(buffer.toString());
}
}
Output;
Javaguides
setLength(int newLength)
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:
substring() methods
publicclassSubStringExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
// print java
System.out.println(buffer.substring(0, 4));
// print guides
System.out.println(buffer.substring(4, buffer.length()));
}
}
Output:
toString()
Example:
publicclassToStringExample {
publicstaticvoidmain(String[] args) {
StringBuffer buffer =newStringBuffer("javaguides");
System.out.println(buffer.toString());
}
}
Output:
javaguides
trimToSize()
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
StringBuilder Constructors
StringBuilder defines these four constructors:
StringBuilder()
StringBuilder(String str)
StringBuilder(int capacity)
StringBuilder(CharSequence seq)
StringBuilder()
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:
Output:
26
StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by the
capacity argument.
Example:
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:
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);
}
}
Output:
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.
publicclassCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuilderbuilder=newStringBuilder("javaguides");
int capacity =builder.capacity();
// inital capacity
System.out.println(newStringBuilder().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.
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:
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:
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.
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;
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
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.
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:
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");
Output:
This method removes the char at the specified position in this sequence. This sequence is
shortened by one char.
Example: Example to delete character 'g' from string 'javaguides' using deleteCharAt() method.
Output:
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:
publicclassEnsureCapacityExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder();
builder.ensureCapacity(11);
System.out.println(builder.capacity());
}
}
Output:
16
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);
Output:
j
a
v
a
g
u
i
d
e
s
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:
publicclassInsertExample {
publicstaticvoidmain(String[] args) {
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());
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.
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:
length()
Example:
publicclassLengthExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
int length =builder.length();
System.out.println(" length of the string '"+ builder +"' is :: "+ length);
}
}
Output:
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()
publicclassReverseExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
StringBuilder reverse =builder.reverse();
System.out.println("Reversed string :"+ reverse);
}
}
Output:
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)
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:
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:
toString()
Example:
publicclassToStringExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
System.out.println(builder.toString());
}
}
Output:
javaguides
trimToSize()
Example:
publicclassTrimToSizeExample {
publicstaticvoidmain(String[] args) {
StringBuilder builder =newStringBuilder("javaguides");
System.out.println(builder.capacity());
builder.trimToSize();
System.out.println(builder.capacity());
}
}
Output:
27
11
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.
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.
privatestaticvoidstringPool(){
String s1 ="Helloworld";
String s2 ="Helloworld";
String s3 ="Greeting";
String s4 =newString("Greeting");
String s5 ="Helloworld";
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");
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");
}
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.
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.
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
StringBuffer acts like StringBuilder, as it has the same methods except they are synchronized.
That means StringBuffer should be used in multi-threading context.
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:
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.
publicclassStringEqualsTest{
publicstaticvoidmain(String []args){
String s1 ="string";
String s2 ="string";
String s3 =newString("string");
Output:
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
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.
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.
I have created my own String Utility classes and have used in tons of projects.
You should refer these utility classes or methods:
Example:
privatevoidbar() {
String howdy="Howdy"
buz(howdy);
buz(howdy);
}
privatevoidbuz(String x) {}
// Better
privatestaticfinalStringHOWDY="Howdy";
privatevoidbar() {
buz(HOWDY);
buz(HOWDY);
}
privatevoidbuz(String x) {}
Example:
StringBuffer sb =newStringBuffer();
sb.append("a"); // avoid this
StringBuffer sb =newStringBuffer();
sb.append('a'); // use this instead
Example:
StringBufferbuf=newStringBuffer();
buf.append("Hello").append(foo).append("World"); // good
publicclassFoo {
privateStringBuffer buffer;
// potential memory leak as an instance variable;
}
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.
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.
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:
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:
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:
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:
four: 22
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:
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;
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);
}
}
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)
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.
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)
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.
publicclassEqualsIgnoreCaseExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
boolean equal =str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: "+ equal);
}
}
Output:
regionMatches() methods
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
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);
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.
// 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:
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.
intcompareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is
returned as values meaning:
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]);
}
}
}
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.
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";
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:
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.
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.
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
Output:
Output;
getChars()
If you need to extract more than one character at a time, you can use the getChars( ) method. It
has this general form:
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);
}
}
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.
publicclassGetBytesExamples {
publicstaticvoidmain(String[] args) throwsUnsupportedEncodingException {
String str ="javaguides";
// 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()
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
intindexOf(intch)
intlastIndexOf(intch)
intindexOf(String str)
intlastIndexOf(String str)
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:
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
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.
publicclassIndexOfExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
// method 1
int index =str.indexOf("java");
System.out.println(index);
// 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
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
In this post, we will discuss below methods for modifying a String objects.
substring()
concat()
replace()
replaceAll()
replaceFirst()
trim()
We can extract a substring using substring( ) methods. There are two forms of substring()
methods.
subStr=str.substring(4);
System.out.println("Sub string starts from index 4 :"+subStr);
System.out.println("unhappy".substring(2));
System.out.println("Harbison".substring(3));
System.out.println("emptiness".substring(8));
}
}
Output:
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:
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:
Here, original specifies the character to be replaced by the character specified by replacement.
The resulting string is returned. For example,
The second form of replace( ) replaces one character sequence with another. It has this general
form:
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
Replaces each substring of this string that matches the given regular expression with the given
replacement.
publicclassReplaceExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.replaceAll("[a-z]", "java");
System.out.println(subStr);
}
}
Output:
javajavajavajavajavajavajavajavajavajava
Replaces the first substring of this string that matches the given regular expression with the
given replacement.
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:
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.
publicclassTrimExample {
publicstaticvoidmain(String[] args) {
String str ="javaguides";
StringsubStr=str.trim();
System.out.println("trim the space from given string :"+subStr);
}
}
Output:
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:
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
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:
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.
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;
Do You Know?
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
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.
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.
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:
1. int a=50/0;//ArithmeticException
variable that has characters; converting this variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
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.
1. try{
2. //code that may throw an exception
3. }finally{}
The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
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:
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.
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:
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:
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:
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:
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.
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
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:
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:
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:
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
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.
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 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.
Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Skip Ad
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:
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).
17.6M
362
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.
1. throw new exception_class("error message");
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.
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.
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:
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:
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).
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:
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.
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.
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.
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...
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:
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:
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.
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.
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
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:
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:
Along with this, there are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
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.
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.
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:
TestExceptionChild.java
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:
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:
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:
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:
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.
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
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
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 methods to create and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
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.
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
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.
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:
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.
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.
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().
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
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...
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.
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
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 ...
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.
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.
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.
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
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.
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.
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.
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
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:
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
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
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.
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
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.
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:
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.
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:
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.
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.
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.
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:
Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:Sonoo Jaiswal
running...
running...
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()
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
Keep Watching
Keep Watching
Competitive questions on Structures in Hindi
Keep Watching
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:
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:
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. }
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.
C++ vs Java
1) public void setDaemon(boolean is used to mark the current thread as daemon thread or use
status) thread.
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:
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:
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.
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
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:
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:
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.
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.
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.
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
2) ThreadGroup(ThreadGroup parent, String creates a thread group with a given parent group an
name) name.
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.
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.
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.
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]
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:
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:
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:
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:
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:
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:
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:
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:
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:
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.
22.7M
524
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();
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.
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:
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:
No Method Description
.
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. }
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