Module III 22ise43
Module III 22ise43
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?
}
}
String Constructor in Java
• The most commonly used constructors of String class are as
follows:
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()
}
}
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
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");
}
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
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
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
}
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;
}
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();