0% found this document useful (0 votes)
6 views

Module III 22ise43

This document provides an overview of string manipulation and exception handling in Java. It explains the concept of strings as objects, their immutability, and various methods for creating and manipulating string objects, including string literals, the new keyword, and character arrays. Additionally, it discusses memory management related to strings, particularly the Java String Pool, and includes examples of string operations and constructors.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module III 22ise43

This document provides an overview of string manipulation and exception handling in Java. It explains the concept of strings as objects, their immutability, and various methods for creating and manipulating string objects, including string literals, the new keyword, and character arrays. Additionally, it discusses memory management related to strings, particularly the Java String Pool, and includes examples of string operations and constructors.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 214

Module-III

String Manipulation
&
Exception handling
Prepared by Ms. J Karthiyayini J
String Manipulation
• In Java, a string is a sequence of characters. For example, "hello" is a
string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
• We use double quotes to represent a string in Java. For example,
// create a string
String type = "Java programming";
• Here, we have created a string variable named type.
• The variable is initialized with the string in Java Programming.
• The java.lang.String class is used to create a Java string object.
• Generally, a string is a sequence of characters. In C/C++ programming
languages, it represents an array of characters, where the last
character will be the null character (\0) that represents the end of the
string.
• But in Java, String is an object of String class that represents a string of
characters. For example, “Pencil” is a string of 6 characters.
Note: Strings in Java are not primitive types (like int, char,
etc). Instead, all strings are objects of a predefined
class named String.
• And, all string variables are instances of
the String class.
• The String Class Java extends the Object class.
• String class is used to create a string object. It is a
predefined immutable class that is present in java.lang
package.
• But in Java, all classes are also considered as a data
type. So, you can also consider a string as a data type.
Immutable means it cannot be changed.
• Whenever a string gets repeated it does not allocate
the new memory for that string. It uses the same string
by pointing a reference to it for saving memory.
• Basically, memory in Java is divided into three
parts such as heap, stack, and String Pool. The
string is so important in Java that it has a
dedicated memory location.
What string pool does it?
• Java String Pool: Java String pool refers to
collection of Strings which are stored in heap
memory. In this, whenever a new object is
created, String pool first checks whether the
object is already present in the pool or not. If
it is present, then same reference is returned
to the variable else new object will be created
in the String pool and the respective reference
will be returned.
• In the above image, two Strings are created using literal
i.e “Apple” and “Mango”. Now, when third String is
created with the value “Apple”, instead of creating a new
object, the already present object reference is
returned. That’s the reason Java String pool came into
the picture.
• One key point I would like to add that unlike other data
types in Java, Strings are immutable. By immutable, we
mean that Strings are constant, their values cannot be
changed after they are created. Because String objects
are immutable, they can be shared. For example:
String str =”abc”;
is equivalent to:
char data[] = {‘a’, ‘b’, ‘c’};
String str = new String(data);
How to create String object in Java?

• To handle string data in Java, we need an


object of string class. Basically, there are three
ways to create a String object in Java.
• By string literal.
• By new keyword.
• By converting character arrays into strings
String literal in Java

• String literal in Java is created by using double


quotes.
For example:
String s = "Hello";
• The string literal is always created in the string
constant pool. In Java, String constant pool is a
special area that is used for storing string
objects.
• Internally, String class uses a string constant pool (SCP). This
SCP area is part of the method area (Permgen) until Java 1.6
version.From Java 1.7 onwards, SCP area is moved in the heap
memory because SCP is a fixed size in the method area but in
the heap memory, SCP can be expandable.
• Therefore, the string constant pool has been moved to heap
area for memory utilization only.
• Whenever we create a string literal in Java, JVM checks string
constant pool first. If the string already exists in string
constant pool, no new string object will be created in the
string pool by JVM.
• JVM uses the same string object by pointing a reference to it
to save memory. But if string does not exist in the string pool,
JVM creates a new string object and placed in the pool.
• For example:
String s1 = "Hello";
String s2 = "Hello";
• In the above example, when JVM will execute the first statement, it
will not find any string with value “Hello” in the string constant
pool.
• So, it will create an object in string pool and store string “Hello” in
that object as shown in the above figure.
• This object is referenced by the reference variable s1. In other
words, if literal is not available in the pool, a new object will be
created in the pool and the address of that object will be assigned
to a reference variable s1.
• When JVM will execute the second statement, it will first check to
string constant pool to know whether string object with the same
content is already available there or not. Since string with value
“Hello” is already available in the string pool.
• So, JVM will not create a new string object in the pool, and the
address of the available object will assign to reference variable s2.
That is, it will point a reference variable s2 to the old existing object
Key points:
1. Remember that creating an object means allocating memory for
storing data.
2. A string object is created for every string literal.
Creating String Object by new
Keyword
• The second way of creating an object to string
class is by using new operator. It is just like
creating an object of any class.
String s = new String("Hello");
• Whenever we will create an object of string class
using the new operator, JVM will create two
objects. First, it will create an object in the heap
area and store string “Hello” into the object.
• After storing data into memory, JVM will point a
reference variable s to that object in the heap.
Now JVM will create the second object as a copy for literal “Hello” in string constant
pool for future purpose. There is no explicit reference variable pointing to the copy
object in the pool but internally, JVM maintains the reference variable implicitly.
Remember that the object created in the SCP area is not eligible for garbage
collection because implicitly, the reference variable will be maintained by JVM itself.
Key point:
1. For every string literal, one copy will be created in the SCP area.
By converting Character Arrays into
String
• The third way to create strings is by converting the character
arrays into string. Let’s take a character type array: arr[ ] with
some characters as given below
char arr[ ] = {'j','a','v','a'};
• Now create a string object by passing array name to string
constructor like this:
String s = new String(arr);
• Now string object ‘s’ contains string “java”. It means that all
the characters of the array are copied into string.
• If you do not want all the characters of the array into string
then you can also mention which character you need, like this:
String s = new String(arr, 1,3);
• From the above statement, total three
characters will be copied into string s. Since
the original characters are j-a-v-a. So, the
counting will start from 0 i.e 0th character in
the array is ‘j’ and the first character is ‘a’.
Starting from ‘a’, total of three characters ‘ava’
will copy into string s.
How many total objects will be created in
memory for following string objects?
• String s1 = new String("Scientech");
• String s2 = new String("Scientech");
• String s3 = "Scientech";
• String s4 = "Scientech";
1. During the execution of first statement using new operator,
JVM will create two objects, one with content in heap area
and another as a copy for literal “Scientech” in the SCP area
for future purposes as shown in the figure.
The reference variable s1 is pointing to the first object in the
heap area.
2. When the second statement will be executed, for every new
operation, JVM will create again one new object with content
“Scientech” in the heap area.
But in the SCP area, no new object for literal will be created by
JVM because it is already available in the SCP area. The s2 is
pointing to the object in the heap area as shown in the figure.
3. During the execution of third and fourth statements, JVM will
not create a new object with content “Scientech” in the SCP
area because it is already available in string constant pool.
• It simply points the reference variables s3 and s4 to the same
object in the SCP. They are shown in the above figure.
• Thus, a total of three objects is created, two in the heap area
and one in string constant pool.
Key points
1. When we create a String object, we are creating a
string that cannot be changed. In other words, once a
String object has been created, we cannot change any
characters in string. Therefore, string object is
immutable in Java.
2. The number of characters in a string is called length of
string. For example, the length of “Hello” is 5.
3. String class in Java has numerous methods for string
manipulation.
4. String is not a primitive data type. It is a reference data
type.
Why String objects are immutable in
Java?
• String objects are immutable in Java because Java uses
the concept of string constant pool. Suppose there are
6 reference variables, and pointing to the same object
“Hello world”.
• If one reference variable of them changes the value of
object from “Hello world” to “Hello”, with this change,
all the reference variables will be affected. That’s why
string objects are immutable in Java.
• The main advantage of string immutability is that Java
compiler can save space in the memory by sharing
strings.
public class ImmutabilityTest
{
public static void main(String[] args)
{
String s = "hello";
s.concat("world"); // concat() method adds string at the end.
System.out.println(s); // It will print "hello" because string is immutable
object.

}
}
String Constructor in Java
• The most commonly used constructors of String class are as
follows:

1. String(): To create an empty String, we will call a default


constructor.
For example:
String s = new String();
It will create a string object in the heap area with no value.

2. String(String str): It will create a string object in the heap area


and stores the given value in it.
For example:
String s2 = new String(“Hello Java“);
Now, the object str contains Hello Java.
3. String(char chars[ ]): It will create a string
object and stores the array of characters in it.
For example:
char chars[ ] = { ‘a’, ‘b’, ‘c’, ‘d’ };
String s3 = new String(chars);
The object reference variable s3 contains the
address of the value stored in the heap area.
4. String(char chars[ ], int startIndex, int count): It will
create and initializes a string object with a subrange of
a character array. The argument startIndex specifies
the index at which the subrange begins
and count specifies the number of characters to be
copied.
For example:
char chars[ ] = { ‘w’, ‘i’, ‘n’, ‘d’, ‘o’, ‘w’, ‘s’ };
String str = new String(chars, 2, 3);
The object str contains the address of the value ”ndo”
stored in the heap area because the starting index is 2
and the total number of characters to be copied is 3.
package stringPrograms;
public class Windows
{
public static void main(String[] args)
{
char chars[] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' };
String s = new String(chars, 0,4);
System.out.println(s);
}
}
5. String(byte byteArr[ ]): It constructs a new
string object by decoding the given array of
bytes (i.e, by decoding ASCII values into the
characters) according to the system’s default
character set.
package stringPrograms;
public class ByteArray
{
public static void main(String[] args)
{
byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127.
// These byte values will be converted into corresponding characters.
String s = new String(b);
System.out.println(s);
}
}
Key points:
1. 97 is the Unicode value of a, 98 ➨ b, 99 ➨
c, 100 ➨ d.
2. 65 is the Unicode value of A.
6. String(byte byteArr[ ], int startIndex, int
count): This constructor also creates a new
string object by decoding the ASCII values
using the system’s default character set.
package stringPrograms;
public class ByteArray
{
public static void main(String[] args)
{
byte b[] = { 65, 66, 67, 68, 69, 70 }; // Range of bytes: -128 to
127.
String s = new String(b, 2, 4); // CDEF
System.out.println(s);
}
}
Length Operations
• To find the length of a string, we use the length() method of
the String.
• The basic syntax of this method is <string variable>.length();
class Main
{
public static void main(String[] args)
{ // create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length);
}}
Example-2
class Main
{
public static void main(String[] args)
{
String str1 = "Java";
String str2 = "";
System.out.println(str1.length());
System.out.println(str2.length()); System.out.println("Java".length());
System.out.println("Java\n".length());
System.out.println("Java\ n".length());
System.out.println("Java/ n".length());
System.out.println("Learn Java".length());
}}
Character Extraction
i)charAt()

charAt() method is used to extract a single character at an


index. It has following syntax.
char charAt(int index);
Example
class temp
{
public static void main(String args[])
{
String str="Hello";
char ch=str.charAt(2);
System.out.println(ch);
}
}
ii) getChars()

• It is used to extract more than one character. getChars() has


following syntax.
void getChars(int stringStart, int stringEnd, char arr[], int arrStart) ;
• Here stringStart and stringEnd is the starting and ending index
of the substring. arr is the character array that will contain the
substring. It will contain the characters starting from
stringStart to stringEnd-1. arrStart is the index inside arr at
which substring will be copied. The arr array should be large
enough to store the substring.
Example
class temp
{
public static void main(String args[])
{
String str="Hello World";
char ch[]=new char[4];
str.getChars(1,5,ch,0);
System.out.println(ch);
}
}
iii)getBytes()

• getBytes() extract characters from String object and then


convert the characters in a byte array.
• The Java String getBytes() method encodes the string into a
sequence of bytes and stores it in a byte array.
• It has following syntax.
byte [] getBytes();
• Example

String str="Hello";
byte b[]=str.getBytes();
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
String str = "Java";
byte[] byteArray; // convert the string to a byte array
// using platform's default charset
byteArray = str.getBytes();
System.out.println(Arrays.toString(byteArray));
//System.out.println(byteArray);
}}
Note: We have used the Arrays class in the above example to print the
byte array in a readable form. It has nothing to do with getBytes().
iv) toCharArray()

• It is an alternative of getChars() method. toCharArray()


convert all the characters in a String object into an array of
characters. It is the best and easiest way to convert string to
character array.
• It has following syntax.
char [] toCharArray();
Example
class demo {
public static void main(String args[])
{
String str = "Java Programming";
char arr[] = new char[20];
arr = str.toCharArray();
System.out.println(arr);
}
}
v) subString() Method

• This method returns a sub string of the specified


string. This method has two forms.
• public String substring(int beginIndex) –> This
form returns sub string starting
from ‘beginIndex’ to the end of the specified
string.
• public String substring(int beginIndex, int
endIndex) –> This form returns sub string starting
from ‘beginIndex’ to ‘endIndex’ of the specified
string.
public class StringExamples
{
public static void main(String[] args)
{
String s = "Java Concept OfThe Day";

String subString1 = s.substring(11);

System.out.println(subString1); //Output : t Of The Day

String subString2 = s.substring(5, 15);

System.out.println(subString2); //Output : Concept Of


}
}
String Comparison
• In Java, two strings can be compared on the basis of
content and reference. We cannot compare two
strings by using relational operators like >, <, >=,<=,
and !=.
• Basically, Java provides us three general ways by
which we can compare between two strings.
1. By equals() method
2. By = = operator (double equal operators)
3. By compareTo() method.
String Compare by equals() method in
Java
• The string equals() method is used to compare the
original content of string. It compares two strings for
equality. If any character is not matching, it returns
false.
• If all the characters are the same, it will return true.
The string class overrides the equals() method of the
object class.
• Java String class provides two general methods for
comparing two strings. They are as follows:
• equals() method
• equalsIgnoreCase() method
1. public boolean equals(Object str)
• Here, str is a specified string object in the method argument
being compared with the calling string object. If strings
contain the same characters in the same order, it will return
true otherwise false.
For example:
String str = "Hello Java";
boolean result = str.equals("Hello Java");
The result will be true because both are having the same set of
string characters and in the same order.
2. public boolean equalsIgnoreCase(String str)
• This method performs the comparsion between two strings by
ignoring case differences. It only checks the content
characters.
• When it compares two strings, it considers the uppercase (A-
Z) to be the same as the lowercase (a-z). If any character is not
matched, it returns false otherwise, it returns true.
For example:
String str = "HELLO JAVA";
boolean result = str.equalsignorecase("hello java");
• The result will be true because both are having the same set
of string characters due to ignoring case differences and in the
same order.
Example-1
public class EqualsMethodTest {
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Good bye");
String s4 = new String("Hello");

System.out.println(s1.equals(s2)); // true because content and case is same.


System.out.println(s1.equals(s3)); // false because content is different.
System.out.println(s1.equals(args)); // false.
System.out.println(s1.equals(null)); // false.

if (s2.equals(s4))
{
System.out.println("Both strings are equal");
}
else {
System.out.println("Both strings are unequal");
}
}
Example-2(equalsIgnoreCase()
method)
package stringPrograms;
public class EqualsIgnoreCaseTest {
public static void main(String args[])
{
String s1 = "GOOD BYE";
String s2 = new String("Good bye");

System.out.println(s1.equals(s2)); // false because


content is same but case is different.
System.out.println(s1.equalsIgnoreCase(s2)); // true.
}
}
String Compare by = = Operator in
Java
• The = = operator (double equal operator)
compares two object references, not characters.
i.e, it compares the memory address of object
references.
• If both references are pointing to the same object
then it will return true. But if they are pointing to
the different objects, it will automatically return
false.
Example
package stringPrograms;
public class DoubleEqualOperatorTest
{
public static void main(String args[])
{
String s1 = "Cricket";
String s2 = "Cricket";
String s3 = new String("Cricket");
System.out.println(s1==s2); // true
System.out.println(s1==s3); // false
}
}
Explanation of allotting memory for storing objects
1. Let us take the first statement: String s1 = “Cricket”;
When JVM executes the first statement, it will create an object in the
string constant pool and store “Cricket” in it. The reference variable s1
which contains the address of object says 365a25 is allocated to this
object in the memory.
2. When the second statement String s2 = “Cricket”; will be executed by
JVM, it will search in the SCP area to know whether the object with the
same content is already available there or not.
Since the same object is already present in the pool, it will simply create
another reference variable s2 and copies the address of reference
variable s1 into s2. That’s why s2 will also point to the same object.
3. During the execution of the third statement String s3 = new
String(“Cricket”); JVM will create another object in the heap area and
allocate another address of the reference variable s3 says 19821f.
Since we know that for every string literal, JVM also creates one copy of
the object in the string constant pool. But the object “Cricket” is
already available in the pool. Therefore, it will not create another copy
of the object.
Java String Compare by compareTo method
• The string compareTo() method compares the current string object
with specified string object in the method argument
lexicographically and returns an integer value.
• Basically, it compares two strings on the basis of the Unicode value
of each character in the string. Each character of both strings is
converted into a Unicode value for comparison.
• The general form of this method is given below:
public int compareTo(String str)
------------Here, str is a specified string object being compared with
calling string object.
For example:
1. s1.compareTo(s2); where s1 and s2 are two reference variables of
string literals.
 If s1 = = s2, this method returns zero. It means that two strings
are equal.
 If s1 > s2, +ve value. It means that first string is
lexicographically greater than second string.
 If s1 < s2, -ve value. It means that first string is
lexicographically less than second string.
2: s1.compareTo(“Hello Java”); where s1 is a string literal and its
value is compared with string specified in the method
argument.
Example
package stringPrograms;
public class CompareToMethodTest
{
public static void main(String args[])
{
String s1 = "mumbai";
String s2 = "mumbai";
String s3 = "ranchi";
String s4 = "pune";
String s5 = “"; // Empty string.

System.out.println(s1.compareTo(s2)); // 0 because both are equal.


System.out.println(s1.compareTo(s3)); // -5 because 'm' is 5 times lower than ‘r'.
System.out.println(s1.compareTo(s4)); // -3 because 'm' is 3 times lower than 'p'.
System.out.println(s3.compareTo(s4)); // 2 because 'r' is 2 times greater than 'p'.
System.out.println(s4.compareTo(s5)); // 4 because there is 4 characters in pune
whereas empty string has no characters.

}
}
Difference between ==and equals()
while comparing strings
== operator compares references of the string
objects. It does not compare contents of string
objects whereas, equals() method compares
the contents of objects.
Searching
• The String class provides 2 methods for searching a string.
They are :indexOf() : Searches for the first occurrence of a
character or substring.
• lastIndexOf() : Searches for the last occurrence of a character
or substring.
• These methods return the starting index of character or a
substring on a successful search else they return -1.
Syntax Explanation
int indexOf(char ch) This method will return the index of the
first occurrence of a character
variable ch in the invoked string.
int lastIndexOf(char ch) This method will return the index of the last
occurrence of a character variable ch in
the invoked string.
int indexOf(String st) This method will return the index of the
first occurrence of a substring st in the
invoked string.
int lastIndexOf(String st) This method will return the index of the last
occurrence of a substring st in the invoked
string.
int indexOf(char ch, int startIndex) Here startIndex specifies the starting point
int indexOf(String st, int startIndex) of search. The search runs
from startIndexto end of the String.
int lastIndexOf(char ch, int Here startIndex specifies the starting point
startIndex) of search. The search runs
int lastIndexOf(String st, int from startIndex to zero.
startIndex)
Example program elaborates these methods
class StringSearchDemo
{
public static void main(String arg[])
{
String str = "The Sun rises in the east and sets in the west.";
System.out.println("Length of str : " + str.length());
System.out.println("indexOf(i) : " + str.indexOf('i')); // LINE A
System.out.println("lastIndexOf(i) : " + str.lastIndexOf('i')); // LINE B
System.out.println("indexOf(st) : " + str.indexOf("st")); // LINE C
System.out.println("lastIndexOf(st) : " + str.lastIndexOf("st")); // LINE D
System.out.println("indexOf(e, 2) : " + str.indexOf('e', 2)); // LINE E
System.out.println("lastIndexOf(e, 46) : " + str.lastIndexOf('e', 46)); // LINE F
System.out.println("indexOf(st, 2) : " + str.indexOf("st", 2)); // LINE G
System.out.println("lastIndexOf(st, 46) : " + str.lastIndexOf("st", 46)); // LINE H
}}
OUTPUT
Length of str : 47
indexOf(i) : 9
lastIndexOf(i) : 35
indexOf(st) : 23
lastIndexOf(st) : 44
indexOf(e, 2) : 2
lastIndexOf(e, 46) : 43
indexOf(st, 2) : 23
lastIndexOf(st, 46) : 44
DESCRIPTION
LINE A is the display of index of first occurrence of character 'i'. LINE
B is the display of index of last occurrence of character 'i'. LINE C is
the display of index of first occurrence of substring "st". LINE Dis the
display of index of last occurrence of substring "st".
LINE E is the display of index of first occurrence of character 'e'
while the search starts at index 2 and continues till the end of String
str. LINE F is the display of index of first occurrence of character 'e'
while the search runs from index 46 to zero of String str.
LINE G is the display of index of first occurrence of substring "st"
while the search starts at index 2 and continues till the end of String
str. LINE H is the display of index of first occurrence of substring "st"
while the search runs from index 46 to zero of String str.
Modifying a String
• The substring method can be used to extract some characters
from the String. These substrings can be obtained using
indices.
• This method comes in two forms:
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The
substring begins with the character at the beginIndex and
extends to the end of this string.
public String substring(int beginIndex, int endIndex)
This returns a new string that is a substring of this string. The
substring begins at the specified beginIndex and extends to
the character at index (endIndex - 1).
class Substring
{
public static void main(String arg[])
{
String s1 = "Welcome to Merit Campus";
String s2 = s1.substring(11); // LINE A
System.out.println(s2);
String s3 = s1.substring(11, 17); // LINE B
System.out.println(s3);
}
}
OUTPUT
Merit Campus
Merit
concat() method
• string concat() method concatenates or joins the specified
string to the end of current string and creates a new string
object. The general syntax for concat() method is as follows:
public String concat(String str)
• Here, ‘concat’ is a method name and return type of this
method is string object.
• ‘String str’ in the parenthesis represents that we are passing
another string object or string values to concat() method
while it is called.

• Example
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Example
package stringPrograms;
public class StringConcatenationTest1
{
public static void main(String[] args)
{
String s1 = "Hello";
s1.concat("Java");
System.out.println(s1);
}
}
1. When line 6 is executed by JVM, a string object will create in
the string constant pool and stores “Hello” in it. The
0
reference variable s1 is pointing to that object.
2. As you know that once we create a string object, we are not
allowed to perform any changes in that object. If we will try to
change, a new object will be created with these changes in
the heap area.When the statement s1.concat(“Java”); will be
executed, JVM will be added at the end of “Hello” and it will
become “Hello Java”.
Since we performed changes in the existing object. That’s why a
new object will be created in the heap area and stores “Hello
Java” in it.
But we did not assign any reference variable to this new object,
therefore, it will be removed from the memory by the garbage
collector.
3. When line 6 will be executed, for every string literal, one copy
of object will also be created in the string constant pool for
further usability and stores “Java” in it.
As you can observe in the above figure, still ‘s’ is pointing to
“Hello” only. Therefore, the output is Hello.
Example2 -concat
package stringPrograms;
public class StringConcatenationTest2
{
public static void main(String[] args)
{
String s1 = "Indian ";
String s2 = "Team";
String s3 = s1.concat(s2);
System.out.println(s3);
}
}
Example3 -concat
package stringPrograms;
public class StringConcatenationTest1
{
public static void main(String[] args)
{
String s1 = new String("Java");
s1.concat(" Core");
s1 = s1.concat(" Programming");
System.out.println(s1);
}
}
Example4 -concat
package stringPrograms;
public class StringConcatenationTest4
{
public static void main(String[] args)
{
String s1 = "Shubh" + " Deep";
System.out.println(s1);
}
}
replace() Method
• The replace() is used to replace a character or a sequence of
characters of an invoking string with a desired character or set
of characters .
• The replace has two forms:
1.String replace(char original, char replacement)
This form is used to replace a character with a desired
character in the invoking string. Here original specifies the
character to be replaced, replacement specifies the character
that replaces original.
2.The other form of replace is:
String replace(CharSequence original, CharSequence
replacement)
This form is used to replace a charactersequence with a
desired charactersequence in the invoking string. Here
also original specifies the character sequence to be
replaced, replacement specifies the character sequence that
replaces original.
Example
class ReplaceDemo
{
public static void main(String arg[])
{
String sentence = "Moon is bright";
System.out.println(sentence);
String sentence2 = sentence.replace('M', 'N');
System.out.println(sentence2);
String sentence3 = sentence.replace("Moon", "Sun");
System.out.println(sentence3);
}
}
OUTPUT
Moon is bright
Noon is bright
Sun is bright
Java program to illustrate the string
methods in Java
package com.dataflair.stringclass;
public class StringMethods {
public static void main(String[] args) {
String s = " I am learning Java at DataFlair! ";
System.out.println("The output of s.length() is " + s.length());
System.out.println("The output of s.charAt(10) is " + s.charAt(10));
System.out.println("The output of s.substring(4) is " + s.substring(4));
System.out.println("The output of s.substring(5,10) is " +
s.substring(10, 18));
String s1 = "Data“;
String s2 = "Flair";
System.out.println("The output of s1.concat(s2) is " + s1.concat(s2));
System.out.println("The output of s.indexOf('D') is " + s.indexOf("D"));
System.out.println("The output of s.length() is " + s.length());
System.out.println("The output of s1.equals(s2) is " + s1.equals(s2));
System.out.println("The output of s1.compareTo(s2) is " +
s1.compareTo(s2));
System.out.println("The output of s.toLowerCase() is " +
s.toLowerCase());
System.out.println("The output of s.toUpperCase() is " +
s.toUpperCase());
System.out.println("The output of s.trim() is " + s.trim());
}
}
Output

The output of s.length() is 41


The output of s.charAt(10) is e
The output of s.substring(4) is I am learning Java at DataFlair!
The output of s.substring(5,10) is earning
The output of s1.concat(s2) is DataFlair
The output of s.indexOf(‘D’) is 26
The output of s.length() is 41
The output of s1.equals(s2) is false
The output of s1.compareTo(s2) is -2
The output of s.toLowerCase() is i am learning java at dataflair!
The output of s.toUpperCase() is I AM LEARNING JAVA AT
DATAFLAIR!
The output of s.trim() is I am learning Java at DataFlair!
String Buffer
• StringBuffer in java is used to create modifiable String
objects. This means that we can use StringBuffer to
append, reverse, replace, concatenate and manipulate
Strings or sequence of characters. Corresponding
methods under StringBuffer class are respectively
created to adhere to these functions.
• In Java, Strings are known to be immutable or un-
editable, unless overwritten upon. This is where
StringBuffer class comes into picture, where it can
accommodate character sequences and still enable a
mutable feature.
Some important points about StringBuffer in java
are:
• StringBuffer is much alike the String class, but
with mutability features.
• Unlike Strings where the length and memory
allocation are final, StringBuffer has existing
methods to modify these properties.
• StringBuffer is thread safe, most of it’s methods
are synchronized. So StringBuffer object can’t be
accessed or used by multiple threads at the same
time.
Important Constructors of StringBuffer
class
Constructor Description

StringBuffer() creates an empty string buffer


with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the
specified string.
StringBuffer(int capacity) creates an empty string buffer
with the specified capacity as
length.
Important methods of StringBuffer
class
Modifier and Type Method Description

public synchronized append(String s) is used to append the


StringBuffer specified string with
this string. The
append() method is
overloaded like
append(char),
append(boolean),
append(int),
append(float),
append(double) etc.
Modifier and Type Method Description

public synchronized insert(int offset, is used to insert the


StringBuffer String s) specified string with
this string at the
specified position. The
insert() method is
overloaded like
insert(int, char),
insert(int, boolean),
insert(int, int),
insert(int, float),
insert(int, double)
etc.
public synchronized replace(int startIndex, is used to replace the
StringBuffer int endIndex, String string from specified
str) startIndex and
endIndex.
Modifier and Type Method Description

public synchronized delete(int startIndex, is used to delete the


StringBuffer int endIndex) string from specified
startIndex and
endIndex.
public synchronized reverse() is used to reverse the
StringBuffer string.
public int capacity() is used to return the
current capacity.
public void ensureCapacity(int is used to ensure the
minimumCapacity) capacity at least equal
to the given
minimum.
Modifier and Type Method Description

public char charAt(int index) is used to return the


character at the
specified position.

public int length() is used to return the


length of the string
i.e. total number of
characters.

public String substring(int is used to return the


beginIndex) substring from the
specified beginIndex.

public String substring(int is used to return the


beginIndex, int substring from the
endIndex) specified beginIndex
and endIndex.
Example Pgm. -1
class Main {
public static void main(String[] args) {
StringBuffer str = new
StringBuffer("ContentWriter");
int len = str.length();
System.out.println("Length : " + len);
}
}
Example Pgm. -2
public class StringBufferInsert {
public static void main(String[] args) {
StringBuffer stringName = new StringBuffer(" Welcome");
System.out.println(stringName);
stringName.insert(8, " to ");
System.out.println(stringName);
stringName.insert(12, "TechVidvan ");
System.out.println(stringName);
stringName.insert(22, " Tutorial ");
System.out.println(stringName);
stringName.insert(31, " of ");
System.out.println(stringName);
stringName.insert(35, "Java");
System.out.println(stringName);
}
}
Output
Welcome
Welcome to
Welcome to TechVidvan
Welcome to TechVidvan Tutorial
Welcome to TechVidvan Tutorial of
Welcome to TechVidvan Tutorial of Java
Example Pgm. -3
public class StringBufferReverse {
public static void main(String[] args) {
StringBuffer stringName = new
StringBuffer("Welcome to TechVidvan");
System.out.println("Original String: " +
stringName);
stringName.reverse();
System.out.println("Reversed String: " +
stringName);
}
}
String Builder
• StringBuilder objects are like String objects, except that they
can be modified.
• Hence Java StringBuilder class is also used to create mutable
(modifiable) string object.
• StringBuilder is same as StringBuffer except for one important
difference.
• StringBuilder is not synchronized, which means it is not
thread safe. At any point, the length and content of the
sequence can be changed through method invocations.
• StringBuilder class provides an API compatible with
StringBuffer, but with no guarantee of synchronization.
• This class is designed for use as a drop-in replacement for
• StringBuffer in places where the string buffer was being used
by a single thread.

• Where possible, it is recommended that this class be used in


preference to StringBuffer as it will be faster under most
implementations.
• Instances of StringBuilder are not safe for use by multiple
threads. If such synchronization is required then it is
recommended that StringBuffer be used.
Constructors of StringBuilder class

• StringBuilder ( ) : Constructs a string builder with no


characters in it and an initial capacity of 16 characters.
• StringBuilder ( int capacity ) : Constructs a string builder with
no characters in it and an initial capacity specified by the
capacity argument.
• 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 Program-1
import java.lang.StringBuilder;
public class Program
{
public static void main(String[] args)
{ // Initialize StringBuilder with this value.
StringBuilder builder = new
StringBuilder("abc"); // Insert this substring at
position 2. builder.insert(2, "xyz");
System.out.println(builder); }
}
Example Program-2

import java.lang.StringBuilder;
public class Program
{
public static void main(String[] args)
{
StringBuilder builder = new StringBuilder("abc");
// Try to find this substring.
int result = builder.indexOf("bc"); System.out.println(result);
// This substring does not exist.
int result2 = builder.indexOf("de"); System.out.println(result2); }
}
Example Program-3
import java.lang.StringBuilder;
public class Program
{ public static void main(String[] args)
{
StringBuilder builder = new StringBuilder("carrot");
// Delete characters from index 2 to index 5.
builder.delete(2, 5);
System.out.println(builder); }
}
Example Program-4
import java.lang.StringBuilder;
public class Program
{ public static void main(String[] args)
{ // Create new StringBuilder.
StringBuilder b = new StringBuilder("abc");
// Replace second character with "xyz".
b.replace(1, 2, "xyz");
System.out.println(b); } }
String, StringBuffer and StringBuilder
- Which one to use ?
• If your string is not going to change use a String class because
a String object is immutable.
• If your string can change (example: lots of logic and
operations in the construction of the string) and will only be
accessed from a single thread, using a StringBuilder is good
enough.
• If your string can change, and will be accessed from multiple
threads, use a StringBuffer because StringBuffer is
synchronous so you have thread-safety.
Exception Handling
• Exception handling in java is a powerful mechanism or
technique that allows us to handle runtime errors in a
program so that the normal flow of the program can be
maintained.
• All the exceptions occur only at runtime. A syntax error occurs
at compile time.
What is Exception in Java?
• In general, an exception means a problem or an abnormal
condition that stops a computer program from processing
information in a normal way.
• An exception in java is an object representing an error or an
abnormal condition that occurs at runtime execution and
interrupts (disrupts) the normal execution flow of the
program.
• In other words, unwanted and unexpected behavior/event
that interrupts the normal execution flow of the program is
called exception in java. It is thrown from a method. The caller
of the method can catch and handle the exception.
• An exception can be identified only at runtime, not at compile
time. Therefore, it is also called runtime errors that are
thrown as exceptions in Java. They occur while a program is
running.
• For example, if we access an array using an index that is out of
bounds, we will get a runtime error named
ArrayIndexOutOfBoundsException.
• If we enter a double value while the program expecting an integer
value, we will get a runtime error called InputMismatchException.
• When JVM faces these kinds of errors or dividing an integer by zero
in a program, it creates an exception object and throws it to inform
us that an error has occurred.
• If the exception object is not caught and handled properly, JVM will
display an error message and will terminate the rest of the program
abnormally.
• If we want to continue the execution of remaining code in the
program, we will have to handle exception object thrown by error
condition and then display a user-friendly message for taking
corrective actions. This task is known as exception handling in java.
Realtime Example of Exception in Java
1. Suppose you are watching a video on Youtube, suddenly,
internet connectivity is disconnected or not working. In this
case, you are not able to continue watching the video on
Youtube. This interruption is nothing but an exception.
2. Suppose a person is traveling by car from Mumbai to Pune.
After traveling mid-distance, the tire of his car is punctured.
This unexpected or unwanted event is nothing but an
exception.
The car owner always keeps an extra tire as an alternative on
a long-distance journey. He changes the punctured tire by a
new tire. After changing the tire, he continues the rest of the
journey. This alternative way is called exception handling.
• Similarly, when we create a java program and it is
compiled successfully, even exceptions might occur at
runtime due to errors in the program logic.
• This exception must be handled to maintain the normal
execution flow of the program.
• If this exception is not handled suitably, the rest of code
in the program will not be executed.
• To handle runtime exception, the exceptional handling
technique is used in java programming.
• By handling the occurrence of exception, we can provide
a meaningful message to the user about the error rather
than a system-generated error message which is not easy
to understand for a user.
Difference between error and
exception
• Errors indicate that something severe enough has gone wrong, the
application should crash rather than try to handle the error.
• Exceptions are events that occurs in the code. A programmer can
handle such conditions and take necessary corrective actions.
• Few examples:
NullPointerException – When you try to use a reference that points
to null.
ArithmeticException – When bad data is provided by user, for
example, when you try to divide a number by zero this exception
occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the
elements of an array out of its bounds, for example array size is 5
(which means it has five elements) and you are trying to access the
10th element.
Exception Hierarchy in Java
Types of exceptions
• There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
• The main difference between checked and unchecked
exception is that the checked exceptions are checked at
compile-time while unchecked exceptions are checked at
runtime.
1)Checked exceptions
All exceptions other than Runtime Exceptions are known as
Checked exceptions as the compiler checks them during
compilation to see whether the programmer has handled
them or not.
If these exceptions are not handled/declared in the program,
you will get compilation error. For example, SQLException,
IOException, ClassNotFoundException etc.
Unchecked Exceptions
• Runtime Exceptions are also known as Unchecked
Exceptions.
• These exceptions are not checked at compile-
time so compiler does not check whether the
programmer has handled them or not but it’s the
responsibility of the programmer to handle these
exceptions and provide a safe exit.
• For example, ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException etc.
Example-1
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter two integer numbers");

// Read two integer numbers.


int num1 = sc.nextInt();
int num2 = sc.nextInt();
System.out.println(num1 + "/" + num2 + " = " + (num1/num2));
}
}
Output 1:
Enter two integer numbers
4
2
4/2 = 2
Output 2:
Enter two integer numbers
2
0
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Why Exception occurs in Program?
• There can be many reasons that might generate an exception
in a Java program.
1. Opening a non-existing file in your program.
2. Reading a file from a disk but the file does exist there.
3. Writing data to a disk but the disk is full or unformatted.
4. When the program asks for user input and the user enters
invalid data.
5. When a user attempts to divide an integer value by zero, an
exception occurs.
6. When a data stream is in an invalid format, etc.
What is Exception Handler in Java?
• The code that catches the exception thrown by JVM is
called exception handler in Java. It is responsible for receiving
information about the exception/error.
• When an exception occurs, exception handling transfers the
control of execution of the program to an appropriate
exception handler.
• For example, suppose we call a method that opens a file but
the file does not open. In this case, the execution of that
method will stop and the code that we wrote to handle with
this situation, will be run.
• Therefore, we need an alternative way to tell JVM what code
has to be executed to maintain the normal flow of the
program when a certain exception occurs.
• Thus, exception handling is an alternative way to continue the
execution of the rest of the program normally.
How does Exception handling
mechanism work?
• The main purpose of using exception handling mechanism in a
java program is to handle unexpected errors and maintain the
normal flow of the program.
• When an exceptional case occurs in a program, the exception
handling mechanism performs the following tasks to manage
unexpected situations in java program at runtime.
1. When an exception occurs inside a method in java
program, the method in which exception has occurred,
creates an exception object (i.e, an object of exception
class) internally with the help of JVM and hands it over to
the java runtime system (JVM). This process is
called throwing an exception in java.
• The exception object contains information about the
exception such as the name of exception, and Stack
Trace/Location.
2. When a java method throws an exception, JVM searches for a
method in the method call stack that can handle that exception. A
method call stack is an ordered list of methods. This process
continues until the exception is caught by an exception handler.
The method which handles thrown exception is called exception
handler. It is used to catch the exception that is thrown by JVM. This
process is called catching an exception.
3. If an exception handler is found, the control of execution is
transferred to exception handler, and the statements specified inside
exception handler are executed.
4. If JVM does not find an appropriate exception handler, exception is
caught by the default exception handler provided by JVM.
Default exception handler is a part of the run-time system that
displays exception information on the console such as exception
name, message, and a full stack trace from where it was thrown.
• The full stack track describes the sequence of steps that is responsible for
throwing an error.
5. After printing exception information on the console, the default exception
handler terminates the execution of the whole program abnormally.
• Thus, exception handler mechanism works to manage unexpected
situations in a program at runtime. The exception may be user-defined
(custom exception) or predefined. Most of the exceptions are predefined
and must be handled in the program to avoid runtime errors.
• You can keep in mind the working of exception handling mechanism by the
below points.
• Get the exception (Detects problem)
• Throw exception (Inform that an error has occurred)
• Catch the exception (Recieve error information)
• Handle exception (Take appropriate and corrective actions)
• In Java program, we can handle such unexpected errors by using try and
catch block.
Example 2 –Pgm without Exception
package exceptionHandling;
public class ExceptionWithoutError
{
public static void main(String[] args)
{
System.out.println("One");
System.out.println("Two");
System.out.println("Three");
System.out.println("Four");
}
}
Example 3 –Pgm withException
package exceptionHandling;
public class ExceptionDivideByZero
{
public static void main(String[] args)
{
System.out.println("One");
System.out.println("Two");
int a = 1/0; // Exceptional case.
System.out.println("Three");
System.out.println("Four");
}
}
• When you will compile the above code, Java compiler will not
show any kind of error and it will be successfully compiled but at
runtime, an Arithmetic exception will be thrown by JVM. Let’s
understand how it happened?
• In the preceding code, exception has occurred in the main()
method, therefore, main method will create an exception object
of ArithmeticException class and hands it over to java run-time
system.
• Now, JVM will check inside the main method, error handling code
is there or not. Since the main method did not handle exception,
JVM will terminate main method abnormally and hands over to
the default exception handler.
• The default exception handler will catch the exception thrown by
JVM and display a system-generated error message on the
console.
• After displaying a system-generated error message, default
exception handler will terminate the whole program.
• Let’s compile the above code and look at the
output.
• Output:
One
Two
Exception in thread "main"
java.lang.ArithmeticException: / by zero at
exceptionHandling.ExceptionDivideByZero.main
(ExceptionDivideByZero.java:9)
Java Exception Handling Keywords
• A block of code that catches the exception thrown by JVM is
called exception handler. This whole mechanism is called exception
handling.
• In java, the basic concepts of exception handling are throwing an
exception and catching it.
• Java exception handling is managed via five keywords:
try,catch,throw, throws, and finally.
1)try-catch:
• try-catch block will be used for exception handling in our code. try
is the start of the block and catch is at the end of try block to
handle the exceptions.
• We can have multiple catch blocks with a try and try-catch block can
be nested also.
• catch block requires a parameter that should be of type Exception.
2) throw – if any exception occurs, an exception object is getting
created and then Java runtime starts processing to handle them.
• Sometime we might want to generate exception explicitly in our
code, for example in a user authentication program we should
throw exception to client if the password is null.
• throw keyword is used to throw exception to the runtime to handle
it.
3) throws – When we are throwing any exception in a method and not
handling it, then we need to use throws keyword in method
signature to let caller program know the exceptions that might be
thrown by the method.
• The caller method might handle these exceptions or propagate it to
it’s caller method using throws keyword. We can provide multiple
exceptions in the throws clause and it can be used
with main() method also.
4) finally – finally block is optional and can be used only with try-catch
block. Since exception halts the process of execution, we might
have some resources open that will not get closed, so we can use
finally block. finally block gets executed always, whether exception
occurred or not.
try-catch block
• Java try, catch and finally blocks helps in writing the
application code which may throw exceptions in runtime .
• It gives us a chance to either recover from exception by
executing alternate application logic or handle the exception
gracefully to report back to the user.
• It helps in preventing the application crashes.
try block:
• The try block contains the application code which is expected
to work in normal conditions.
• try block syntax
try {
//application code
}
• The three possible forms of try block are as
follows:
• try-catch: A try block is always followed by one or
more catch blocks.
• try-finally: A try block followed by a finally block.
• try-catch-finally: A try block followed by one or
more catch blocks followed by a finally block.
catch block:
• The optional catch block(s) follows the try block and
MUST handle the checked exceptions thrown by try
block as well as any possible unchecked exceptions
catch block syntax
try {
//code
}
catch(Exception e) {
//handle exception
}
Exception Handling Mechanism using
Try-Catch block
Rules of using Try and Catch block in
Java
• There are some rules for using try-catch block in
java program. They are as follows:
1. Java try-catch block must be within a method.
2. A try block can not be used without a catch or
finally block. It must be followed by at least one
catch block otherwise, the compilation error will
occur.
3. A catch block must be followed by try block.
There should not be any statement between the
end of try block and the beginning of catch block.
4. A finally block cannot come before catch block.
Control Flow of Try Catch Block in
Java
try
{
statement 1;
statement 2;
statement 3;
}
catch(exception_class var)
{
statement 4;
}
statement 5;
Example-4
package exceptionHandling;
public class ExceptionHandlingwithTryCatch
{
public static void main(String[] args)
{
System.out.println("One");
System.out.println("Two");
try // Error handling code starts here
{
System.out.println("Before divide");
int a = 1/0; // Exceptional case (Exception has occurred).
System.out.println("After divide");
}
catch(ArithmeticException e) // Exception handled. Here, catch
block is exception handler.
{
System.out.println("A number cannot be divided by zero.");
// User-friendly message
}
System.out.println("Three");
System.out.println("Four");
}
}
Output:
One
Two
Before divide
A number cannot be divided by zero.
Three
Four
• Now, notice that we handled exception in catch block thrown
by try block in the program and printed a user-friendly
message on the console. ArithmeticException is a class that is
used to handle all arithmetical exception. It extends
RuntimeException.
• Thus, we can handle exception occurring at runtime and can
maintain the normal flow of the program.
Java Default Exception Handling
Example -5
package exceptionHandling;
public class DefaultExceptionHandlingEx1
{
public static void main(String[] args)
{
m1(); // main() method calling m1().
}
public static void m1()
{
m2(); // m1() method calling m2().
}
public static void m2()
{
m3(); // m2() method calling m3().
}
public static void m3()
{
System.out.println(1/0); // Exceptional case. A number cannot
be divided by zero.
}
}
• In the above code, there is only the main thread. For every
thread, JVM creates one runtime stack. The main() method is
called by JVM. For every method call, JVM will add one entry
in the method call stack as shown in the following figure.
• Method call stack is the chain/order of methods that our
program will execute to get to the current method. We
represent method call stack as growing upward. The method
that is to be called first, will go at the bottom.
• The method that will be called at last, will go at the top of the
stack. If we move back down in the call stack, we are moving
the current method to previously called method. Now, look at
the above figure that will show how the call stack in java
works.
• Now, the main() method is calling m1(). So, JVM will add one
entry for m1() method in the call stack. The control of
execution is transferred to the m1() method.
• Similarly, the m1() method is calling the m2() method. Again,
JVM will add one entry for m2() method in the method call
stack. The control of execution will be transferred to m2()
method.
• The method m2() is calling m3() method. JVM will add one
entry for m3() method as shown in the above figure and the
control of execution will be transferred to method m3().
• Inside the m3() method, an exception has occurred, so the
m3() method will create an exception object internally and
hands over it to JVM. Now, JVM checks the exception handling
code is there or not.
• Since inside the m3() method, there is no error handling code,
so JVM immediately, terminates this method abnormally
without execution of its remaining code and removed the
corresponding entry from the method call stack.
• Now JVM will search that method which is calling m3(). Since
m3() method is called by m2(). So, the control of execution
will go back to m2() method and JVM will again check that
m2() is handled the exception or not.
• Since m2 is not handled the exception there, JVM terminates
m2() method abnormally and removed the corresponding
entry from the call stack.
• Similarly, JVM will again search that method that is calling
m2(). The method m2() is called by m1(). The control of
execution will go back to m1() method and JVM will check
that exception handling is there or not.
• Since m1() is not handled the exception, JVM terminates m1()
abnormally and removed the corresponding entry from the
call stack.
• Since m1() is called by main() method but the main() method
did not handle the exception. So, JVM will terminate the
main() method abnormally and will remove the corresponding
entry from the call stack.
• At last, JVM is responsible to handle this exception because
JVM called the main method to start the execution of
program. JVM will hand over exception to the default
exception handler.
• The default exception handler will just print exception
information on the console and terminates the whole
program abnormally.
Output:
1. Exception in thread "main"
java.lang.ArithmeticException: / by zero at
2. exceptionHandling.DefaultExceptionHandlingEx1.m3(
DefaultExceptionHandlingEx1.java:18) at
3. exceptionHandling.DefaultExceptionHandlingEx1.m2(
DefaultExceptionHandlingEx1.java:14) at
4. exceptionHandling.DefaultExceptionHandlingEx1.m1(
DefaultExceptionHandlingEx1.java:10) at
5. exceptionHandling.DefaultExceptionHandlingEx1.mai
n(DefaultExceptionHandlingEx1.java:6)
Example-6 Checked Exception
package exceptionHandling;
public class CheckedExceptionEx1
{
public static void main(String[] args)
{
System.out.println("Hello Java");
Thread.sleep(1000); // Here, main thread paused for
specified amount of time. // Compilation error.
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved
compilation problem: Unhandled exception type
InterruptedException
Explanation:
• In the above code, there is a compilation error: “Unhandled
exception type InterruptedException”. This is because
thread.sleep(); method throws an InterruptedException that
has been not handled by try-catch or throws clause.
• Since InterruptedException is a checked exception that is
checked by the compiler itself for the smooth execution of the
program at runtime, therefore, we got a compilation error at
compile-time and InterruptedException exception at runtime
Handle this checked exception either
using a try-catch block
public class CheckedExceptionEx1
{
public static void main(String[] args)
{
System.out.println("Hello Java");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}}
Example-7 UnChecked Exception
public class UncheckedExceptionEx1
{
public static void main(String[] args)
{
int x = 10;
int y = 0;
int z = x/y;
System.out.println(z);
}
}
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero at
exceptionHandling.UncheckedExceptionEx1.main
(UncheckedExceptionEx1.java:9)
• The above code has become compile successfully
but when you will go to execute it, so it would
throw ArithmeticException. This shows that
runtime exceptions do not occur during
compilation.
Example-8 UnChecked Exception
public class UncheckedExceptionEx2
{
public static void main(String[] args)
{
int x[ ] = {1, 2, 3, 4};
System.out.println(x[6]);
}
}
• Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 6
Exception handled by using try-catch block
public class UncheckedExceptionEx2
{
public static void main(String[] args)
{
try
{
int x[ ] = {1, 2, 3, 4};
System.out.println(x[6]);
System.out.println(“Exception Handled”);

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Specified index does not exist. " + "Please
correct the error.");
}
}
}
Output:
Specified index does not exist. Please, correct the
error.
Example-9
public class TryCatchEx9
{
public static void main(String[] args)
{
try
{
System.out.println("111");
System.out.println("222");
}
catch(ArithmeticException ae)
{
System.out.println("333");
}
System.out.println("444");
}
}
Multiple Catch Blocks
• An application can go wrong in N different ways. That’s why
we can associate multiple catch blocks with a single try block.
• In each catch block, we can handle one or more specific
exceptions in a unique way.
• When one catch block handles the exception, the next catch
blocks are not executed.
• Control shifts directly from the executed catch block to
execute the remaining part of the program, including finally
block.
Multiple catch block syntax
try {
//code
}
catch(NullPointerException e) {
//handle exception
}
catch(NumberFormatException e) {
//handle exception
}
catch(Exception e) {
//handle exception
}
Example-10
public class MultiCatchEx1
{
public static void main(String[] args)
{
try
{
int arr[] = new int[6];
arr[3] = 20/0; // Exception occurred.
System.out.println("I am in try block");
}
catch(ArithmeticException ae)
{
System.out.println("A number cannot be divided by zero, Illegal operation in
java");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Accessing array element outside of specified
limit");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("I am out of try-catch block");
}
}
Example-11
public class MultiCatchEx2
{
public static void main(String[] args)
{
String s = "Scientech Easy";
int a[] = {0, 1, 2, 3, 4, 5};
try
{
//s = null;
int sLength = s.length();
System.out.println("String length: " +sLength);
int b = 6;
System.out.println(a[b]);
}
catch(NullPointerException npe)
{
System.out.println("Exception is caught");
System.out.println(npe.toString());
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Exception is caught");
System.out.println(aie.toString());
}
}
}
Output:
Exception is caught java.lang.NullPointerException
• Note
If you comment out line marked statement s = null;
then you will get the following output.

Output:

String length: 14
Exception is caught
java.lang.ArrayIndexOutOfBoundsException: 6
Nested Try Catch Java

• When a try block is defined within another try,


it is called nested try block in java.
• The try block which encloses another try block
is called outer try block and the enclosed try
block is called inner try block.
Syntax of Java Nested Try Block
try // Outer try block
{
statements;
statements;
try // Inner try block
{
statements;
statements;
}
catch(Exception1 e1) // Inner catch block
{
statements;
statements;
}
}
catch(Exception2 e2) // Outer catch block
{
statements;
statements;
}
Case 1:
If an exception occurs within outer try block, the control of execution is
transferred from the outer try block to outer catch block that will handle the
exception thrown by outer try block.
After handling the exception by catch block, the execution continues with the
statement following the outer catch block. The inner try block and its
corresponding catch blocks are skipped in this case.
If an exception does not occur inside outer try block, the control of execution
enters into the inner try block. If an exception occurs inside inner try block, the
catch block associated with this inner try block is searched for a proper match.
If a match is found then the execution of outer catch block is skipped and the
execution continues with statements following outer catch block.
If no match is found, the control of execution is transferred to the next outer
try-catch block to handle the exception of inner try block. This process
continues until and unless an appropriate match is found. If no match is
found then Java runtime system will handle the exception at runtime and the
program terminates abnormally.
Case 3:
If both try blocks do not throw any exception,
both catch blocks are skipped naturally and
the execution continues with statements
following the outer catch block.
Example-12
package nestedTryExample;
public class NestedTryBlockEx1
{
public static void main(String[] args)
{
String str = "Scientech Easy";
int x[ ] = {0, 1, 2, 3, 4};
try // Outer try block
{
str = null; // Exception occurred.
int slength = str.length();
System.out.println("String length: " +slength);
try // Inner try block
{
int y = 6;
System.out.println(x[y]);
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Exception is thrown");
System.out.println(aie.toString());
}
}
catch(NullPointerException npe)
{
System.out.println("Exception is thrown ");
System.out.println(npe.toString());
}
}
}
Output:
Exception is thrown java.lang.NullPointerException
Example-13
package nestedTryExample;
public class NestedTryBlockEx4
{
public static void main(String[] args)
{
String str = "Scientech Easy";
int x[ ] = {0, 1, 2, 3, 4};
try
{
int slength = str.length();
System.out.println("String length: " +slength);
try
{
int y = 6;
System.out.println(x[y]); // Exception occurred.
}
catch(ArithmeticException ae) // No match is found.
{
System.out.println("Exception is thrown");
System.out.println(ae.toString());
}}
catch(NullPointerException npe) // No match is found.
{
System.out.println("Exception is thrown ");
System.out.println(npe.toString());
}
System.out.println("I am out of outer catch block");
}}
Output:
String length: 14
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 6
at
nestedTryExample.NestedTryBlockEx4.main(NestedTryBlockEx
4.java:17)
• In the above program, the exception thrown by inner catch
block does not match with the type of outer and inner catch
blocks. Therefore, Java runtime system will handle exception
at runtime and the program terminates abnormally.
Finally Block in Java
• A “finally” is a keyword used to create a block of code that follows a try or
catch block.
• A finally block contains all the crucial codes such as closing connections,
stream, etc that is always executed whether an exception occurs within a
try block or not.
• When finally block is attached with a try-catch block, it is always executed
whether the catch block has handled the exception thrown by try block or
not.
Syntax for try-finally block:

try
{
statement1;
statement2;
}
finally // finally block
{
statement3;
}
Syntax for try-catch-finally block:
try
{
statement1;
statement2;
}
catch(Exceptiontype e1)
{
statement3;
}
statement4;
finally
{
statement5;
}
• Some important rules of using finally block or
clause are:
1. A finally block is optional but at least one of
the catch or finally block must exist with a try.
2. It must be defined at the end of last catch
block. If finally block is defined before a catch
block, the program will not compile successfully.
3. Unlike catch, multiple finally blocks cannot be
declared with a single try block. That is there can
be only one finally clause with a single try block.
Control flow of try-catch-finally block
in Java
Use of finally block in Java

• 1. Generally, finally block or clause is used for


freeing up resources, cleaning up code, db closing
connection, io stream, etc.
• 2. A java finally block is used to prevent resource
leak. While closing a file or recovering resources,
the code is put inside the finally block to ensure
that the resource is always recovered.
• 3. Finally clause is used for terminating threads.
Example-14
public class finallyBlockExample1
{
public static void main(String[] args)
{
int a = 20, b = 30;
try
{
int sum = a + b;
System.out.println("Sum: " +sum);
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block must be executed");
}
System.out.println("Hello Java");
}
}

Output:
Sum: 50
finally block must be executed
Hello Java
• In the above code, no exception has occurred inside try block.
So, catch block will not be executed and the control will
directly go to execute the finally block.
Example-15
public class finallyBlockExample3
{
public static void main(String[] args)
{
int a = 20, b = 0;
try
{
System.out.println("Value of a: " +a);
System.out.println("Value of b: " +b);
int div = a/b;
System.out.println("Division: " +div);
}
catch(NullPointerException npe)
{
System.out.println(npe); // prints corresponding exception.
}
finally
{
System.out.println("Denominator cannot be zero");
}
System.out.println("Hello Java");
}
}
Output:
Value of a: 20
Value of b: 0
Exception in thread "main" Denominator cannot be zero
java.lang.ArithmeticException: / by zero at
finallyBlockExample.finallyBlockExample1.main(finallyBlockEx
ample1.java:11)
Example-16
public class finallyBlockExample4
{
public static void main(String[] args)
{
try
{
System.out.println("111");
System.out.println("222");
}
catch(Exception ae)
{
System.out.println(10/0);
}
finally
{
System.out.println("444");
}
System.out.println("555");
}
}
Example-17
public class finallyBlockExample5
{
public static void main(String[] args)
{
try
{
System.out.println("111");
System.out.println(20/0);
System.out.println("222");
}
catch(Exception ae)
{
System.out.println(10/0);
}
finally
{
System.out.println("444");
}
System.out.println("555");
}
}
Output:
111
Exception in thread "main" 444
java.lang.ArithmeticException: / by zero at
finallyBlockExample.finallyBlockExample5.main(finallyBlockEx
ample5.java:14)
Throw Keyword in Java

• Throw in Java is a keyword that is used to throw a


built-in exception or a custom exception explicitly or
manually. Using throw keyword, we can throw either
checked or unchecked exceptions in java programming.
• When an exception occurs in the try block, throw
keyword transfers the control of execution to the caller
by throwing an object of exception. Only one object of
exception type can be thrown by using throw keyword
at a time. Throw keyword can be used inside a method
or static block provided that exception handling is
present.
Syntax:
throw exception_name;
where exception_name is a reference to an object of Throwable
class or its subclass.
For example:
throw new ArithmeticException();
or
ArithmeticException ae = new ArithmeticException();
throw ae;

throw new NumberFormatException();


Key points:
1. The object of Throwable class or its
subclasses can be created using new keyword
or using a parameter inside catch clause.
2. Instances of classes other than Throwable
class or its subclasses cannot be used as
exception objects.
Example-18
public class ThrowTest1
{
public static void main(String[] args)
{
try
{
ArithmeticException a = new
ArithmeticException("Hello from throw");
throw a; // Exception thrown explicitly.
// Line 7 and 8 can be written also in one line like this:
// throw new ArithmeticException("Hello from throw");
}
catch(ArithmeticException ae){
System.out.println("ArithmeticException caught: \n" +ae);
System.out.println(ae.getMessage());
}
}
}
Output:
ArithmeticException caught:
java.lang.ArithmeticException: Hello from throw
Hello from throw
Explanation:
• In the main() method of class ThrowTest1, the try
block creates an object of ArithmeticException
class with reference variable a and passing an
argument of String type to its constructor. The
exception object is then thrown by the
statement: throw a;

• The thrown exception object is caught by


corresponding catch block and stored in ae. The
ae.getMessage() displays a string message
append along with the internally generated
message.
Example-19
public class ThrowTest2
{
public static void main(String[] args)
{
int x = 20;
int y = 0;
try
{
int z = x/y; // Exception occurred.
System.out.println("Result: " +z);
throw new ArithmeticException();
}
catch(ArithmeticException ae){
System.out.println("Exception caught: \n" +ae);
}}}
Output:
Exception caught:
java.lang.ArithmeticException: / by zero
Example-20
class Test1 extends Exception {

}
class Test2 extends Exception {

}
class Test3 extends Exception {

}
public class ThrowTest5
{
public static void main(String[] args)
{
int num = 1;
for(num = 1; num <= 10; num++)
{
try
{
if(num == 5)
throw new Test1();
else if(num < 2)
throw new Test2();
else if(num > 9)
throw new Test3();
}
catch(Exception e)
{
System.out.println("Caught an exception");
}
}
}}
Output:
• Caught an exception
• Caught an exception
• Caught an exception
Throws Keyword
• Java, sometimes a method may throw an
exception in a program but cannot handle it due
to not have an appropriate exception
handling mechanism.
• In such a case, the programmer has to throw that
exception to the caller of the method
using throws clause.
• Throws clause consists of throws keyword
followed by a comma-separated by the list of all
exceptions thrown by that method.
• Throws keyword in Java is used in the method declaration. It
provides information to the caller method about exceptions being
thrown and the caller method has to take the responsibility of
handling the exception.
• Throws keyword is used in case of checked exception only because
if we are not handling runtime exceptions (unchecked exceptions),
Java compiler does not give any error related to runtime exceptions.
If an error occurs, we are unable to do anything.
• When the code generates a checked exception inside a method but
the method does not handle it, Java compiler detects it and informs
us about it to handle that exception. In this case, compulsorily, we
must handle that checked exception otherwise we will get an error
flagged by Java compiler.
• To prevent this error flagged by the compiler, we need to handle
exceptions using throw clause. There are two ways to handle the
exception:
1. By using try-catch block
2. By using throws keyword
Syntax:
access_specifier return_type method_name(parameter list) throws
exception
{
// body of the method.
}
• Java throws keyword can be used to throw multiple exceptions thrown by
a method at a time. Multiple exceptions thrown by a method can be
declared by separating them in comma with the help of throws keyword.
• The general syntax is as follows:
access_specifier return_type method_name(parameter_list) throws
exception1, exception2, . . . . exceptionN
{
// body of the method.
}
When throws keyword is used with a method declaration, the method calling
a method with throws keyword must be enclosed within try-catch block.
Example-21
public class ThrowsTest1
{
public static void main(String[] args)
{
Thread.sleep(1000);
System.out.println("Hello Java");
}
}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Unhandled exception type InterruptedException
• When you will execute the above program, you
will get compile-time error because Java compiler
expects from you to handle InterruptedException
either using throws clause or try-catch block. But
you did not handle it. So, compile-time error is
displayed.
Handle InterruptedException generated by
sleep() method using throws clause.
public class ThrowsTest1
{
public static void main(String[] args) throws
InterruptedException
{
Thread.sleep(1000);
System.out.println("Hello Java");
}
}
Output:
Hello Java
Example-22
package throwsProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ThrowsTest2


{
private String firstName, lastName;
void accept() throws IOException
{
// Reading data from keyboard.
InputStreamReader sr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(sr);
System.out.println("Enter your first name");
firstName = br.readLine();
System.out.println("Enter your last name");
lastName = br.readLine();
}
void display(){
System.out.println("Full Name: " +firstName+ " " +lastName);
}
public static void main(String[] args) throws IOException
{
ThrowsTest2 obj = new ThrowsTest2();
obj.accept();
obj.display();
}
}
Output:
Enter your first name
Sachin
Enter your last name
Tendulkar
Full Name: Sachin Tendulkar
Explanation:
1. InputStreamReader and BufferedReader
classes are used to read data from the keyboard.
2. readLine() method is used to read a line of text.
This method may throw IOException if an I/O
error occurs.
Note:
Throws keyword in Java language provides
flexibility method for throwing an exception
instead of handling it. It takes a list of objects
of type Throwable class as an argument. It is
applicable to a method when a method raises
a certain type of exception.
Difference between throw and throws
Throw Throws
This keyword is used for explicitly throwing an This keyword is used for declaring any
exception. exception.
Programmers cannot disseminate checked Programmers can disseminate checked
exceptions using the throw keyword. exceptions using throws keyword.
An instance trails the throw keyword. A class trails the throws keyword.
You have to use the throw keyword inside any You have to use the throws keyword with any
method. sign of the method.
Many exceptions cannot be thrown. Many exceptions can be declared using the
throws.
Class Example public void testExc() throws SQLException ,
{ IOException
public static void main(String argu[])
{
throw new ArithmeticException("Divided by
zero");}}
User defined Exception /Custom Exception
• We have seen predefined exceptions provided by the Java platform.
These predefined exceptions are used to handle errors occurring in
the program.
• But sometimes the programmer wants to create his own
customized exception as per requirements of the application which
is called user-defined exception or custom exception.
• Custom exceptions in Java are those exceptions which are created
by a programmer to meet their specific requirements of the
application.
For example:
1. A banking application, a customer whose age is lower than 18
years, the program throws a custom exception indicating “needs to
open joint account”.
2. Voting age in India: If a person’s age entered is less than 18 years,
the program throws “invalid age” as a custom exception.
How to create your own User-defined
Exception in Java?
• There are following steps that are followed in creating user-
defined exception or custom exception in Java. They are as
follows:
Step 1: User-defined exceptions can be created simply by
extending Exception class. This is done as:
class OwnException extends Exception
Step 2: If you do not want to store any exception details, define a
default constructor in your own exception class. This can be
done as follows:
OwnException()
{

}
Step 3: If you want to store exception details, define a
parameterized constructor with string as a parameter, call
super class (Exception) constructor from this, and store
variable “str”. This can be done as follows:
OwnException(String str)
{
super(str); // Call super class exception constructor and store variable "str" in it.
}
Step 4: In the last step, we need to create an object of user-
defined exception class and throw it using throw clause.
OwnException obj = new OwnException("Exception details");
throw obj;
or,
throw new OwnException("Exception details");
Example-23
package customExceptionProgram;
public class OwnException extends Exception
{
// Declare default constructor.
OwnException()
{

}
}
public class MyClass {
public static void main(String[] args)
{
try
{
// Create an object of user defined exception and throw it
using throw clause.
OwnException obj = new OwnException();
throw obj;
}
catch (OwnException ex)
{
System.out.println("Caught a user defined exception");
}
}
}
Example-24
import java.util.Scanner;
public class InvalidAgeException extends Exception
{
// Declare a parameterized exception with string str
as a parameter.
InvalidAgeException(String str)
{
super(str);
}
}
public class TestClass
{
private static int age;
static void validate() throws InvalidAgeException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age");
age = sc.nextInt();

if(age < 18)


throw new InvalidAgeException("Invalid Age, You are not
eligible to vote");
else
System.out.println("Welcome to vote");
}
public static void main(String[] args)
{
try
{
validate();
}
catch(Exception e)
{
System.out.println("Caught an Exception: \n "+e);
}
}
}
Output:
First Execution:
Enter your age
7
Caught an Exception:
customExceptionProgram.InvalidAgeException: Invalid
Age, You are not eligible to vote
Second Execution:
Enter your age
40
Welcome to vote

You might also like