0% found this document useful (0 votes)
8 views31 pages

403-Java-Unit-3

This document covers basic concepts of strings and exceptions in Java, detailing the immutability of String objects and the use of StringBuffer and StringBuilder for mutable strings. It explains various constructors for creating String objects, string methods for operations like length, concatenation, conversion, character extraction, and comparison. Additionally, it highlights the differences between equals() and == operator, as well as the compareTo() method for string comparison.

Uploaded by

8t46ct85bb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

403-Java-Unit-3

This document covers basic concepts of strings and exceptions in Java, detailing the immutability of String objects and the use of StringBuffer and StringBuilder for mutable strings. It explains various constructors for creating String objects, string methods for operations like length, concatenation, conversion, character extraction, and comparison. Additionally, it highlights the differences between equals() and == operator, as well as the compareTo() method for string comparison.

Uploaded by

8t46ct85bb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

403-JAVA PROGRAMMING LANGUAGE

Unit 3. Basic Concepts of Strings and Excep�ons

Strings :Basic String opera�ons, String Comparison & String methods


Somewhat unexpectedly, when you create a String object, you are creating a string that
cannot be changed.
For those cases in which a modifiable string is desired using StringBuffer and StringBuilder.
Both hold strings that can be modified after they are created.
The String, StringBuffer, and StringBuilder classes are defined in java.lang. Thus, they are
available to all programs automatically. All are declared final, which means that none of
these classes may be subclassed.

The String Constructors

The String class supports several constructors. To create an empty String, you call the
default constructor. For example,
String s = new String();
will create an instance of String with no characters in it. Frequently, you will want to create
strings that have initial values. The String class provides a variety of constructors to handle
this.
• To create a String initialized by an array of characters, use the constructor shown
here:
String(char chars[ ])
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
• You can specify a subrange of a character array as an initializer using the following
constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars
specifies the number of characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
• You can construct a String object that contains the same character sequence as
another String object using this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
output
Java
Java

• The String class provides constructors that initialize a string when given a byte array.
Their forms are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to specify
a subrange. In each of these constructors, the byte-to-character conversion is done
by using the default character encoding of the platform. The following program
illustrates these constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}}
output
ABCDEF
CDE
Methods
String Length
The length of a string is the number of characters that it contains. To obtain this value, call
the
int length( )
The following fragment prints “3”, since there are three characters in the string s:

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
System.out.println(s.length());
It calls the length( ) method on the string “abc”. As expected, it prints “3”.
System.out.println("abc".length());

String Concatenation
the + operator, which concatenates two strings, producing a String object as the result.
This allows you to chain together a series of + operations. For example, the following
fragment concatenates three strings or String Concatenation with Other Data Types:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
String s2 = "four: " + (2 + 2);
System.out.println(s2);

This displays the string


“He is 9 years old.”
"This could have been a very long line that would have wrapped around. But string
concatenation prevents this."
“Four:4”

String Conversion
1.String.valueOf()
The String.valueOf() method converts int to String. The valueOf() is the static method of
String class. The signature of valueOf() method is given below:
public static String valueOf(int i)
example:
public class IntToStringExample1{
public static void main(String args[]){
int i=200;
String s=String.valueOf(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is string concatenation operator
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

}}
Output:
300
200100
2.Integer.toString()
The Integer.toString() method converts int to String. The toString() is the static method of
Integer class. The signature of toString() method is given below:
public static String toString(int i)
Example:
public class IntToStringExample2{
public static void main(String args[]){
int i=200;
String s=Integer.toString(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is string concatenation operator
}}
Output:
300
200100
3.String.format()
The String.format() method is used to format given arguments into String. It is introduced
since Jdk 1.5.
public static String format(String format, Object... args)
example:
public class IntToStringExample3{
public static void main(String args[]){
int i=200;
String s=String.format("%d",i);
System.out.println(s);
}}
Output
200

Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Each is examined here. Although the characters that comprise a string within
a String object cannot be indexed as if they were a character array, many of the String

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

methods employ an index (or offset) into the string for their operation. Like arrays, the
string indexes begin at zero.
charAt( )
To extract a single character from a String, you can refer directly to an individual character
via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must
be nonnegative and specify a location within the string. charAt( ) returns the character at
the specified location. For example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch.
getChars( )
If you need to extract more than one character at a time, you can use the getChars( )
method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd
specifies an index that is one past the end of the desired substring. Thus, the substring
contains the characters from sourceStart through sourceEnd–1. The array that will receive
the characters is specified by target. The index within target at which the substring will be
copied is passed in targetStart. Care must be taken to assure that the target array is large
enough to hold the number of characters in the specified substring.
The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}}
output
demo

getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This
method is called getBytes( ), and it uses the default character-to-byte conversions
provided by the platform. Here is its simplest form:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are
exporting a String value into an environment that does not support 16-bit Unicode
characters. For example, most Internet protocols and text file formats use 8-bit ASCII for
all text interchange.

toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest
way is to call toCharArray( ). It returns an array of characters for the entire string. It has
this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve
the same result.
String s = "GeeksForGeeks";
char[] gfg = s.toCharArray();
System.out.println(gfg);

String Comparison
The String class includes several methods that compare strings or substrings within strings.
Each is examined here.
equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It returns true
if the strings contain the same characters in the same order, and false otherwise.
The comparison is case-sensitive. To perform a comparison that ignores case
differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be
the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too, returns
true if the strings contain the same characters in the same order, and false otherwise.
Example:
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));


System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +s1.equalsIgnoreCase(s4));
}}

output
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
regionMatches( )
The regionMatches() method of the String class has two variants that can be used to test
if two string regions are matching or equal.
Syntax:
1. Case sensitive test method:
public boolean regionMatches(int toffset, String other, int offset, int len)
2. It has the option to consider or ignore the case method:
public boolean regionMatches(boole+an ignoreCase, int toffset, String other,
int offset, int len)
Parameters:
• ignoreCase: if true, ignore the case when comparing characters.
• toffset: the starting offset of the subregion in this string.
• other: the string argument being compared.
• offset: the starting offset of the subregion in the string argument.
• len: the number of characters to compare.
Example:
// Java Program to find if substrings
// or regions of two strings are equal

import java.io.*;

class CheckIfRegionsEqual {
public static void main(String args[])
{

// create three string objects


String str1
= new String("Welcome to Geeksforgeeks.com");
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

String str2 = new String("Geeksforgeeks");


String str3 = new String("GEEKSFORGEEKS");

// Comparing str1 and str2


System.out.print(
"Result of Comparing of String 1 and String 2: ");
System.out.println(
str1.regionMatches(11, str2, 0, 13));

// Comparing str1 and str3


System.out.print(
"Result of Comparing of String 1 and String 3: ");
System.out.println(
str1.regionMatches(11, str3, 0, 13));

// Comparing str2 and str3


System.out.print(
"Result of Comparing of String 2 and String 3: ");
System.out.println(
str2.regionMatches(0, str3, 0, 13));
}
}
Output
Result of Comparing of String 1 and String 2: true
Result of Comparing of String 1 and String 3: false
Result of Comparing of String 2 and String 3: false

startsWith( ) and endsWith( )


The startsWith( ) method determines whether a given String begins with a specified string.
endsWith( ) determines whether the String in question ends with a specified string. They
have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise, false
is returned. For example,

System.out.print("Foobar".endsWith("bar"))
System.out.print("Foobar".startsWith("Foo"))
Output
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

true
true.

Asecond form of startsWith( ), shown here, lets you specify a starting point:
boolean startsWith(String str, int startIndex)
Here, startIndex specifies the index into the invoking string at which point the search will
begin. For example,
System.out.print("Foobar".startsWith("bar", 3))
Output
true.

equals( ) Versus ==
The equals( ) method and the == operator perform two different operations.
The equals( ) method compares the characters inside a String object.
The == operator compares two object references to see whether they refer to the same
instance.
The following program shows how two different String objects can contain the same
characters, but references to these objects will not compare as equal:

EXAMPLE:
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}}

The variable s1 refers to the String instance created by “Hello”. The object referred to by
s2 is created with s1 as an initializer. Thus, the contents of the two String objects are
identical, but they are distinct objects. This means that s1 and s2 do not refer to the same
objects and are, therefore, not ==, as is shown here by the output of the preceding
example:
Hello equals Hello -> true
Hello == Hello -> false

compareTo( )

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Often, it is not enough to simply know whether two strings are identical. For sorting
applications, you need to know which is less than, equal to, or greater than the next.
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted, as shown here:
0 if the string is equal to the other string.
< 0 if the string is lexicographically less than the other string
> 0 if the string is lexicographically greater than the other string (more characters)

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

String myStr1 = "Hello";


String myStr2 = "Hello";
System.out.println(myStr1.compareTo(myStr2));
If you want to ignore case differences when comparing two strings, use
compareToIgnoreCase( ), as shown here:
int compareToIgnoreCase(String str)
This method returns the same results as compareTo( ), except that case differences are
ignored.
Searching Strings
The String class provides two methods that allow you to search a string for a specified
character or substring:
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.

These two methods are overloaded in several different ways. In all cases, the methods
return the index at which the character or substring was found, or –1 on failure. To search
for the first occurrence of a character, use
int indexOf(int ch)
To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)

Here, str specifies the substring.


You can specify a starting point for the search using these forms:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

int indexOf(int ch, int startIndex)


int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

Here, startIndex specifies the index at which point the search begins. For indexOf( ), the
search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs
from startIndex to zero. The following example shows how to use the various index
methods to search inside of Strings:

// Demonstrate indexOf() and lastIndexOf().


class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}}

Here is the output of this program:


Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or StringBuilder, or use one of the following String
methods, which will construct a new copy of the string with your modifications complete.
substring( )
The substring() method has two variants and returns a new string that is a substring of
this string. The substring begins with the character at the specified index and extends to
the end of this string. Endindex of the substring starts from 1 and not from 0.
public String substring(int begIndex, int endIndex);
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.optional
example:
String Str = new String("Welcome to geeksforgeeks");
// using substring() to extract substring
System.out.println(Str.substring(10));
System.out.println(Str.substring(10, 16));
Output:
Geeksforgeeks
geeks

concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents of str
appended to the end. concat( ) performs the same function as +. For example, String s1 =
"one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character
in the invoking string with another character. It has the following general form:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by


replacement.
Example,
String s = "Hello".replace('l', 'w');
Print(s)
puts the string “Hewwo” into s.
The second form of replace( ) replaces one character sequence with another. It has this
general form:
String replace(CharSequence original, CharSequence replacement)

trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed. It has this general form:
String trim( )
Example:
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());
It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently
been entered by the user.

Data Conversion Using valueOf( )

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

public static String valueOf(boolean b)


public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

example:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
Output
3010

Changing the Case of Characters Within a String

The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase
to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the
general
forms of these methods:
String toLowerCase( )
String toUpperCase( )
Both methods return a String object that contains the uppercase or lowercase equivalent
of the invoking String.
Example
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
Output:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
StringBuffer class and its constructors & StringBuffer methods :
(append(),insert(),update(), delete(), reverse(),capacity())
StringBuffer Class in Java:
String in general is a sequence of characters that is immutable(unchangeable) in
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

nature. But java provides a class called StringBuffer that facilitates the programmer to
create a string that is mutable in nature.
Every class in java has two main attributes:

1. Constructors
2. Methods
A string that facilitates modification or change is known as a mutable string. The
StringBuffer and StringBuilder classes allow us to create mutable strings.
StringBuffer Constructors in Java:

Constructor(Syntax) Description

It is the default constructor of the StringBuffer class. This


StringBuffer() constructor creates an empty StringBuffer with an initial
capacity of 16.

StringBuffer(String str) It is a parameterized constructor with String as Parameter. This


constructor creates a StringBuffer with the specified string.

It is a parameterized constructor with an integer as a


StringBuffer(int capacity) parameter. This constructor creates an empty StringBuffer
with the specified capacity as length.

Let us discuss some of the important methods present in Java StringBuffer class:
1. Java append():
This method is used to concatenate two strings.
Example
public class Append
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Data");
str.append("Flair");
System.out.println(str);
}
}
The output of the above code:
DataFlair

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

2. Java insert():
The insert method inserts the given string into the StringBuffer object at the given
position.
Example
public class Insert
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Data");
str.insert(4,"Flair");
System.out.println(str);
}
}
The output of the above code:
DataFlair
3. Java replace():
This method replaces the StringBuffer object with the specified string at the
specified position.
Example
public class Replace
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Data");
sb.replace(2,3,"Flair"); //from 2 to 3-1
System.out.println(sb);
}
}
The output of the above code:
DaFlaira
4. Java delete():
This method deletes the StringBuffer object from the specified position.
Example
public class Delete
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("DataFlair");
sb.delete(2,4);//delete ta

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

System.out.println(sb);
}
}
The output of the above code:
DaFlair
5. Java reverse():
This method is used to reverse the String present in the StringBuffer object.
Example
public class Reverse
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("DataFlair");
str.reverse();
System.out.println(str);
}
}
The output of the above code:
rialFataD
6. Java capacity():
The capacity() method returns the current capacity of the StringBuffer object. The default
capacity of the StringBuffer object is 16.
If the number of characters increases from its current capacity, it increases the capacity
by:(old capacity*2)+2.
For example, if your current capacity is 16, then the capacity will be calculated as:
(16*2)+2= 34.
Example
public class Capacity
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());// 16
sb.append("DataFlair");
System.out.println(sb.capacity());//16
sb.append("DataFlair is company that teaches programming!!!");
System.out.println(sb.capacity());//50
}
}

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

The output of the above code:


16
16
57

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException,IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application.An exception normally disrupts the normal flow of the application; that is why
we need to handle exceptions. Let's consider a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement
5; therest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is whywe use exception handling in Java

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered
as the unchecked exception.
1. Checked Exception
2. Unchecked Exception
• Runtime exception & Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
Checked exceptions, also known as compile-time exceptions, are exceptions
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

that must be either caught or declared in the method signature using the
throws keyword.
For example, IOException, SQLException, etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description

Try The "try" keyword is used to specify a block where we should place an
exception code(statement that causes an exception). It means we can't use
try block alone. The try block must be followed by either catch or finally.

Catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by
finally block later.

Finally The "finally" block is used to execute the necessary code of the program. It
is executed whether an exception is handled or not.

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

Throws The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

public class JavaExceptionExample


{
public static void main(String args[]){
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
• A scenario where ArithmeticException occurs If we divide any number by zero, there
occurs an ArithmeticException.
int a=50/0;//ArithmeticException
• A scenario where NullPointerException occurs If we have a null value in any variable,
performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
• A scenario where NumberFormatException occurs If the formatting of any
variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
• A scenario where ArrayIndexOutOfBoundsException occurs When an array exceeds
to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
int a[]=new int[5];
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block


Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method. If an exception occurs at the particular statement in the try block, the
rest of the block code willnot execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}
catch(Exception_class_Name ref_variable)
{
}

Syntax of try-finally block


try{
//code that may throw an exception
}
finally{
}

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block
with a single try block.

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not handled,JVM provides a
default exception handler that performs the following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the
application ismaintained, i.e., rest of the code is executed.

Problem without exception handling


Example 1 TryCatchExample1.java
public class TryCatchExample1 {
public static void main(String[] args)
{ int data=50/0; //may throw exception
System.out.println("rest of the code");
}}
As displayed in the above example, the rest of the code is not executed (in such case,the
rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled,all
the code below the exception won't be executed.

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Solution by exception handling


Example 2 TryCatchExample2.java

public class TryCatchExample2 {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}}

Java Catch Multiple Exceptions Java Multi-catch block


A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the occurrence
of different exceptions, use java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch
forArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
Output
Arithmetic Exception occurs
rest of the code

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Java finally block


Java finally block is a block used to execute important code such as closing the connection,
etc. Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed regardless of
the exception occursor not.The finally block follows the try-catch block
Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executesfinally
block (if any).

Why use Java finally block?

o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.

TestFinallyBlock.java

class TestFinallyBlock {
public static void main(String args[]){

try{
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE

//below code do not throw any exception


int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e)
{ System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are checked at
the compile time instead of runtime and we can create custom exceptions making the code
recovery and debugging easier.

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message
with in that provides the error description. These exceptions may be related to user
inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in this
section.
We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw Arithmetic Exception if we divide a number
by another number. Here, we just need to set the condition and throw exception using
throwkeyword.

The syntax of the Java throw keyword is given below.throw Instance i.e.,
throw new exception_class("error message");
Let's see the example of throw IOException.
throw new NullPointerException ("sorry device error");

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
printa message welcome to vote.

TestThrow1.java
In this example, we have created the validate method that takes integer value as a
parameter. Ifthe age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Example:
import java.util.*;
class TestThrow1 {
public static void main(String arg[])
{ try
{
System.out.print("enter m1");
Scanner s=new Scanner(System.in);

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

int m1=s.nextInt();
if (m1<0)
throw new ArithmeticException("invalid");
else
System.out.print("valid");
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
}
Java throws Keyword
Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class Main
{ static void checkAge(int age) throws ArithmeticException
{if (age < 18)
{throw new ArithmeticException("Access denied - You must be at least 18 years
old.");
}
Else
{System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Definition and Usage
The throws keyword indicates what exception type may be thrown by a method.There
are many exception types available in
Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException,
S ecurityException, etc.
Differences between throw and throws:
Throw Throws
Used to throw an exception for a Used to indicate what exception type may be
method thrown by a method

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

Cannot throw multiple exceptions Can declare multiple exceptions


Syntax: Syntax:
• throw is followed by an • throws is followed by a class
object (new type) • and used with the method signature
• used inside the method

User-defined Custom Exception in Java


Java provides us the facility to create our own exceptions which are basically derived
classes of Exception. Creating our own Exception is known as a custom exception or user-
defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.
For example, MyException in the below code extends the Exception class.
Why use custom exceptions?
Java exceptions cover almost all the general types of exceptions that may occur in
the programming. However, we sometimes need to create custom exceptions.
Following are a few of the reasons to use custom exceptions:
• To catch and provide specific treatment to a subset of existing Java exceptions.
• Business logic exceptions: These are the exceptions related to business logic
and workflow. It is useful for the application users or the developers to
understand the exact problem.
In order to create a custom exception, we need to extend the Exception class that
belongsto java.lang package.
Example:
// A Class that represents use-defined exception
class MyException extends Exception
{
MyException(String message)
{
// Call constructor of parent Exception
super(message);
}
}
// A Class that uses above MyException
public class TestMyException
{
// Driver Program
public static void main(String args[])
{

C.B.PATEL COMPUTER COLLEGE (B.C.A.)


403-JAVA PROGRAMMING LANGUAGE

int age=15;
try
{
if(age<18)
// Throw an object of user defined exception
throw new MyException("Person is not eligible to vote");
}
catch (MyException ex)
{
System.out.println("Caught My Exception");
// Print the message from
MyException object
System.out.println(ex.getMessage()
);
}
finally
{
System.out.println(“I am always here”);
}
}
Output
Caught My Exception Person is not eligible to vote I am always here

Example
class invstd extends Exception
{invstd(String s)
{super(s);
}
}
class A{
public static void main(String arg[]) throws invstd
{ int std=Integer.parseInt(arg[0]);
if (std !=12)
{throw new invstd("invalid std");
}
else
System.out.print("welcome");
}
}
Runjava A 12 or java A 11

C.B.PATEL COMPUTER COLLEGE (B.C.A.)

You might also like