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

MODULE_3-Java Notes

This document covers string manipulation in Java, including the String class, constructors, length operations, character extraction, and searching methods. It explains how to create and manipulate strings, extract characters, and search for substrings, along with examples of each method. Additionally, it discusses exception handling fundamentals related to string operations.

Uploaded by

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

MODULE_3-Java Notes

This document covers string manipulation in Java, including the String class, constructors, length operations, character extraction, and searching methods. It explains how to create and manipulate strings, extract characters, and search for substrings, along with examples of each method. Additionally, it discusses exception handling fundamentals related to string operations.

Uploaded by

Akash Kengua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

MODULE-3

String Manipulation: Constructors, Length Operations, Character Extraction, Comparison, Searching,


Modifying, StringBuffer, Exception handling: Fundamentals, Types, Using try, catch, throw, throws,
finally, User Defined Exceptions.

String Class in Java:


The String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support
mutable strings. 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);

Here are some more examples of how strings can be used:


System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

The class String includes methods for examining individual characters of the sequence, for comparing
strings, for searching strings, for extracting substrings, and for creating a copy of a string with all
characters translated to uppercase or to lowercase.

The Java language provides special support for the string concatentation operator ( + ), and for
conversion of other objects to strings. String concatenation is implemented through
the StringBuffer class and its append method. String conversions are implemented through the
method toString, defined by Object and inherited by all classes in Java. For additional information on
string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

The String Constructors:


String s = new String();

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


To create a String initialized by an array

of characters, use the constructor shown here:

String(char chars[ ])

Here is an 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.

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);

The output from this program is as follows:

Java

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

Length method in strings:


This method returns the length of this string. The length is equal to the number of 16-bit Unicode
characters in the string.

Syntax

public int length()

Parameters

Return Value

 This method returns the the length of the sequence of characters represented by this object.

Example
import java.io.*;
public class Test {

public static void main(String args[]) {


String Str1 = new String("Welcome to Tutorialspoint.com");
String Str2 = new String("Tutorials" );

System.out.print("String Length :" );


System.out.println(Str1.length());

System.out.print("String Length :" );


System.out.println(Str2.length());
}
}
Output

String Length :29


String Length :9

String Character Extraction:


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

String Character Extraction Methods

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

charAt(int index)

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

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

String str = "Welcome to string handling guide";


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

Character at 0 index is: W


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

Example 2: Throws IndexOutOfBoundsException - if the index argument is negative or not less than the
length of this string.
String str = "Java Guides";
char ch1 = str.charAt(str.length() + 1);
System.out.println("character :: " + ch1);
Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12


at java.lang.String.charAt(String.java:658)
at com.javaguides.strings.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26)
at com.javaguides.strings.methods.ChatAtExample.main(ChatAtExample.java:6)

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

String str = "Java Guides";


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

Character at 0 index is: J


Character at last index is: s

getChars()

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

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);}}

Here is the output of this program:

demo

getBytes()

There are four versions of getBytes() methods. There is an alternative to getChars( ) that stores the
characters in an array of bytes.

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

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

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

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

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

public class GetBytesExamples {


public static void main(String[] args) throws UnsupportedEncodingException {
String str = "javaguides";

// Encodes this String into a sequence of bytes using the platform's


// default charset, storing the result into a new byte array.
byte[] bs = str.getBytes();
for (byte b: bs) {
System.out.println(b);
}

// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs1 = str.getBytes(Charset.forName("UTF-8"));
for (byte b: bs1) {
System.out.println(b);
}
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs2 = str.getBytes("UTF-8");
for (byte b: bs2) {
System.out.println(b);
}

byte[] dest = new byte[str.length()];


str.getBytes(0, str.length(), dest, 0);
for (byte b: dest) {
System.out.println(b);
}

}
}

toCharArray()

Converts this string to a new character array.

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

public class ToCharArrayExample {


public static void main(String[] args) {
String str = "javaguides";
char[] characters = str.toCharArray();
for (char c : characters) {
System.out.println(c);
}

}
}
Ouput:

j
a
v
a
g
u
i
d
e
s
Searching characters and substring in a String in Java
Searching a character in the String
indexOf(char c) : It searches the index of specified character within a given string. It starts searching
from beginning to the end of the string (from left to right) and returns the corresponding index if found
otherwise returns -1.
Note: If given string contains multiple occurrence of specified character then it returns index of only first
occurrence of specified character.
Syntax:
int indexOf(char c)
// Accepts character as argument, Returns index of the first occurrence of specified character

lastIndexOf(char c): It starts searching backward from end of the string and returns the index of
specified character whenever it is encountered.

Syntax:
public int lastIndexOf(char c)
// Accepts character as argument, Returns an index of the last occurrence specified character

IndexOf(char c, int indexFrom): It starts searching forward from the specified index in the string and
returns the corresponding index when the specified character is encountered otherwise returns -
1. Note: The returned index must be greater than or equal to the specified index.

Syntax:
public int IndexOf(char c, int indexFrom)
char: character to be searched.
indexfrom : an integer from where searching
// Returns an index of specified character that appeared at or after the specified index in forward
direction

lastIndexOf(char c, int fromIndex): It starts searching backward from the specified index in the string.
And returns the corresponding index when the specified character is encountered otherwise returns -1.
Note: The returned index must be less than or equal to the specified index.

Syntax:
public int lastIndexOf(char c, int fromIndex)
charAt(int indexNumber): Returns the character existing at the specified index, indexNumber in the
given string. If the specified index number does not exist in the string, the method throws an unchecked
exception, StringIndexOutOfBoundsException.

Syntax:
char charAt(int indexNumber)
// Java program to illustrate to find a character in the string.

import java.io.*;

class GFG
{
public static void main (String[] args)
{
// This is a string in which a character
// to be searched.
String str = "GeeksforGeeks is a computer science portal";

// Returns index of first occurrence of character.


int firstIndex = str.indexOf('s');
System.out.println("First occurrence of char 's'" +
" is found at : " + firstIndex);

// Returns index of last occurrence specified character.


int lastIndex = str.lastIndexOf('s');
System.out.println("Last occurrence of char 's' is" +
" found at : " + lastIndex);

// Index of the first occurrence of specified char


// after the specified index if found.
int first_in = str.indexOf('s', 10);
System.out.println("First occurrence of char 's'" +
" after index 10 : " + first_in);

int last_in = str.lastIndexOf('s', 20);


System.out.println("Last occurrence of char 's'" +
" after index 20 is : " + last_in);

// gives ASCII value of character at location 20


int char_at = str.charAt(20);
System.out.println("Character at location 20: " +
char_at);

// throws StringIndexOutOfBoundsException
// char_at = str.charAt(50);
}
}
Output:
First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

Searching Substring in the String

 The methods used for searching a character in the string which are mentioned above can also be used
for searching the substring in the string.

// Java program to illustrate to find a substring in the string.

import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a substring
// is to be searched.
String str = "GeeksforGeeks is a computer science portal";

// Returns index of first occurrence of substring


int firstIndex = str.indexOf("Geeks");
System.out.println("First occurrence of char Geeks"+
" is found at : " + firstIndex);

// Returns index of last occurrence


int lastIndex = str.lastIndexOf("Geeks");
System.out.println("Last occurrence of char Geeks is"+
" found at : " + lastIndex);

// Index of the first occurrence


// after the specified index if found.
int first_in = str.indexOf("Geeks", 10);
System.out.println("First occurrence of char Geeks"+
" after index 10 : " + first_in);

int last_in = str.lastIndexOf("Geeks", 20);


System.out.println("Last occurrence of char Geeks " +
"after index 20 is : " + last_in);
}
}
Output:
First occurrence of char Geeks is found at : 0
Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8
 contains(CharSequence seq): It returns true if the String contains the specified sequence of char
values otherwise returns false. Its parameters specify sequence of character to be searched and
throws NullPointer exception if seq is null.
 public boolean contains(CharSequence seq)
Note: CharSequence is an interface that is implemented by String class, Therefore we use string as
an argument in contains() method.

// Java program to illustrate how to find a substring in the string using contains

import java.io.*;
import java.lang.*;

class GFG
{
public static void main (String[] args)
{
// This is a string in which substring
// to be searched.
String test = "software";

CharSequence seq = "soft";


boolean bool = test.contains(seq);
System.out.println("Found soft?: " + bool);

// it returns true substring if found.


boolean seqFound = test.contains("war");
System.out.println("Found war? " + seqFound);

// it returns true substring if found otherwise


// return false.
boolean sqFound = test.contains("wr");
System.out.println("Found wr?: " + sqFound);
}
}
Output:
Found soft?: true
Found war? true
Found wr?: false

Matching String Start and End

 boolean startsWith(String str): Returns true if the string str exist at the starting of the given string,
else false.
 boolean startsWith(String str, int indexNum): Returns true if the string str exist at the starting of
the index indexNum in the given string, else false.
 boolean endsWith(String str): Returns true if the string str exist at the ending of the given string,
else false.

// Java program to illustrate to match of start and end of a substring


import java.io.*;

class GFG
{
public static void main (String[] args)
{
// This is a string in which substring
// is to be searched.
String str = "GeeksforGeeks is a computer science portal";

System.out.println(str.startsWith("Geek"));
System.out.println(str.startsWith("is", 14));
System.out.println(str.endsWith("port"));
}
}
Output:
true
true

Java String compare:

We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.

There are three ways to compare string in java:


1. By equals() method
2. By = = operator
3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for
equality. String class provides two methods:

o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring
case.

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}

Output:
true
true
false

class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}

Output:

false
true

2) String compare by == operator

The = = operator compares references not values.


class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}

Output:
true
false

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:

o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:

0
1
-1

Java StringBuffer class: StringBuffer is a peer class of String that provides much of the
functionality of strings.As you know, String represents fixed-length, immutable character sequences.
In contrast,StringBuffer represents growable and writeable character sequences. StringBuffer may
have
characters and substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more characters preallocated
than are actually needed, to allow room for growth. Java uses both classes heavily, but many
programmers deal only with String and let Java manipulate StringBuffers behind the scenes
by using the overloaded + operator.

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is
safe and will result in an order.

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 specified string with this
StringBuffer string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.

public synchronized insert(int offset, String s) is used to insert the specified string with this string
StringBuffer 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, int is used to replace the string from specified
StringBuffer endIndex, String str) startIndex and endIndex.

public synchronized delete(int startIndex, int is used to delete the string from specified startIndex
StringBuffer endIndex) and endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.

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 beginIndex) is used to return the substring from the specified
beginIndex.

public String substring(int beginIndex, int is used to return the substring from the specified
endIndex) beginIndex and endIndex.

What is mutable string?

A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder
classes are used for creating mutable string.

1) StringBuffer append() method

The append() method concatenates the given argument with this string.

class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

2) StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.

class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

4) StringBuffer delete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

6) StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.

class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

Exception Handling in Java


1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur

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

In this page, we will learn about Java exceptions, its type and the difference between checked and
unchecked exceptions.
What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception handling.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

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

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 important 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 doesn't throw an exception. It specifies that
there may occur an exception in the method. It is always used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.

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...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

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 of try block, the rest of the block code will not execute.
So, it is recommended not to keeping 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)
{
}

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.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.


Example 1
public class TryCatchExample1
{
public static void main(String[] args)
{

int data=50/0; //may throw exception

System.out.println("rest of the code");

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling

Let's see the solution of the above problem by a java try-catch block.

Example 2
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");
}

Output:
java.lang.ArithmeticException: / by zero
rest of the code

ava catch multiple exceptions

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use
java multi-catch block.

Points to remember

o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example 1

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

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

Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

Java nested try example

class Excep6
{
public static void main(String args[])
{
try
{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
1. }catch(Exception e){System.out.println("handeled");}
2.
3. System.out.println("normal flow..");
4. }
5. }

Java finally block

Java finally block is a block that is used to execute important code such as closing connection, stream
etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).
Why use java finally

o Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.

Case 1

Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

Let's see the example of throw IOException.

throw new IOException("sorry device error);

java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If the age is
less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that
there may occur an exception so it is better for the programmer to provide the exception handling code so
that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up before
the code being used.

Syntax of java throws


return_type method_name() throws exception_class_name{
//method code
}

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws example

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Output:

exception handled
normal flow...

Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and
throws are given below:

No. throw throws

1) Java throw keyword is used to explicitly throw an exception. Java throws


keyword is used
to declare an
exception.

2) Checked exception cannot be propagated using throw only. Checked


exception can be
propagated with
throws.

3) Throw is followed by an instance. Throws is


followed by
class.

4) Throw is used within the method. Throws is used


with the method
signature.

5) You cannot throw multiple exceptions. You can declare


multiple
exceptions e.g.
public void
method()throws
IOException,SQ
LException.

Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between final, finally
and finalize are given below:

No. final finally finalize

1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to
method and variable. Final class can't be important code, it will perform clean up
inherited, final method can't be overridden and be executed whether processing just before
final variable value can't be changed. exception is handled or object is garbage
not. collected.

2) Final is a keyword. Finally is a block. Finalize is a method.

Java final example

class FinalExample
{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}
}

Java finally example

class FinallyExample
{
public static void main(String[] args)
{
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}

Java finalize example

class FinalizeExample
{
public void finalize(){System.out.println("finalize called");
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}

You might also like