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

Java Unit 3

Uploaded by

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

Java Unit 3

Uploaded by

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

Java Arrays

An array is a collection of similar type of elements which has contiguous


memory location.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
In java, we can get the length of the array using the length member.
In C/C++, we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class.
Java array inherits the Object class, and implements the Serializable as well as
Cloneable interfaces.
We can store primitive values or objects in an array in Java.
Like C/C++, we can also create single dimentional or multidimentional arrays
in Java.
Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array.
It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java
dataType[] arr;
(or)
dataType []arr;
(or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];

Example of Java Array


simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50

Declaration, Instantiation and Initialization of


Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5

For-each Loop for Java Array


print the Java array using for-each loop.
The Java for-each loop prints the array elements one by one.
It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}

class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix
form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar;
(or)
dataType [][]arrayRefVar;
(or)
dataType arrayRefVar[][];
(or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array


simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
1 2 3
2 4 5
4 4 5

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged
array. In other words, it is an array of arrays with different number of columns.
//Java Program to illustrate the jagged array
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
0 1 2
3 4 5 6
7 8

Array of Objects in Java


how to create and initialize an array of objects in Java.
Array of Objects in Java
Java is an object-oriented programming language.
an array is a collection of the same data type that dynamically creates objects and can
have elements of primitive types.
Java allows us to store objects in an array.
In Java, the class is also a user-defined data type.
An array that conations class type elements are known as an array of objects.
It stores the reference variable of the object.

Creating an Array of Objects


Before creating an array of objects, we must create an instance of the class by using
the new keyword.
We can use any of the following statements to create an array of objects.
Syntax:
ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of object
s
Or
ClassName[] objArray;
Or
ClassName objeArray[];
Suppose, we have created a class named Employee. We want to keep records of 20
employees of a company having three departments. In this case, we will not create 20
separate variables. Instead of this, we will create an array of objects, as follows.
1. Employee department1[20];
2. Employee department2[20];
3. Employee department3[20];
The above statements create an array of objects with 20 elements.
Let's create an array of objects in a Java program.
In the following program, we have created a class named Product and initialized an
array of objects using the constructor. We have created a constructor of the class
Product that contains product id and product name. In the main function, we have
created individual objects of the class Product. After that, we have passed initial
values to each of the objects using the constructor.
ArrayOfObjects.java
public class ArrayOfObjects
{
public static void main(String args[])
{
//create an array of product object
Product[] obj = new Product[5] ;
//create & initialize actual product objects using constructor
obj[0] = new Product(23907,"Dell Laptop");
obj[1] = new Product(91240,"HP 630");
obj[2] = new Product(29823,"LG OLED TV");
obj[3] = new Product(11908,"MI Note Pro Max 9");
obj[4] = new Product(43590,"Kingston USB");
//display the product object data
System.out.println("Product Object 1:");
obj[0].display();
System.out.println("Product Object 2:");
obj[1].display();
System.out.println("Product Object 3:");
obj[2].display();
System.out.println("Product Object 4:");
obj[3].display();
System.out.println("Product Object 5:");
obj[4].display();
}
}
//Product class with product Id and product name as attributes
class Product
{
int pro_Id;
String pro_name;
//Product class constructor
Product(int pid, String n)
{
pro_Id = pid;
pro_name = n;
}
public void display()
{
System.out.print("Product Id = "+pro_Id + " " + " Product Name = "+pro_name);
System.out.println();
}
}
Output:
Product Object 1:
Product Id = 23907 Product Name = Dell Laptop
Product Object 2:
Product Id = 91240 Product Name = HP 630
Product Object 3:
Product Id = 29823 Product Name = LG OLED TV
Product Object 4:
Product Id = 11908 Product Name = MI Note Pro Max 9
Product Object 5:
Product Id = 43590 Product Name = Kingston USB

PACKAGE
1. Package in Java is a collection or pack or group of classes, sub-packages, and
interfaces.
2. It helps organize your classes and interfaces into a folder structure
3. and make it easy to locate and use them.
4. it helps improve code reusability.
5. Each package in Java has its unique name and organizes its classes and interfaces
into a separate namespace, or name group.
6. Although interfaces and classes with the same name cannot appear in the same
package, they can appear in different packages.
7. This is possible by assigning a separate namespace to each Java package.
Advantages of using a package in Java

 Reusability: While developing a project in java, there are few things that are writing
again and again in our code. Using packages, create such things in form of classes inside
a package and whenever need to perform that same task, just import that package and
use the class.
 Better Organization: Again, in large java projects where we have several hundreds of
classes, it is always required to group the similar types of classes in a meaningful package
name so that you can organize your project better and when you need something you can
quickly locate it and use it, which improves the efficiency.
 Name Conflicts: We can define two classes with the same name in different packages
so to avoid name collision
 Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 Java package provides access protection.

Types of packages in Java


1)User defined package: The package we create is called user-defined package.
2)Built-in package: The already defined package like java.io.*, java.lang.* , awt, javax, swing,
net, util, sql etc.etc are known as built-in packages.
Example when we need user input, we import a package like this:
import java.util.Scanner
• java is a top level package
• util is a sub package
• and Scanner is a class which is present in the sub package util.
Step 1) Write the package Java program in Notepad
Step 2) save this file calculator.java
Step 3) compile the file using javac –d . classname.java
Step 4) Run the file using java packagename.classname
How to Create a package?

1. Choose the name of the package


2. Include the package command as the first line of code in your Java Source File.
3. if you want, to include the Source file contains the classes, interfaces, etc in the package,
4. Compile to create the Java packages

Syntax:-
package nameOfPackage;
Example 1: Java packages
package letmecalculate; //New package created (or) the package declaration
public class Calculator //class defined
{
public int add(int a, int b) //method defined
{
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator(); // object created
System.out.println(obj.add(10, 20)); // calling method
}
}

Explanation:
 I have created a class Calculator inside a package name letmecalculate.
 To create a class inside a package, declare the package name in the first
statement in your program.
 A class can have only one package declaration.
 Calculator.java file created inside a package letmecalculate

How to Import Package


To create an object of a class (bundled in a package), in our code, we have to use its fully
qualified name.
Instead of using fully qualified name we can use import statement for doing the same.

Syntax
import packageName;

Examples of java in-built classes imported:


import java.awt.event.*; // * signifies all classes in this package are
imported
import javax.swing.JFrame // here only the JFrame class is imported

Example 2: How to use this package in another program.


import letmecalculate.Calculator; //already created package is imported in this program
public class Demo
{
public static void main(String args[])
{
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));// calling method
}
}

To use the class Calculator, the package letmecalculate have imported.


If you have several classes inside package letmecalculate then you can import the package like
this, to use all the classes of this package.
import letmecalculate.*;
Example 3: Creating a class inside package while importing another package
 Both package declaration and package import should be the first statement in our java
program.
 order when we are creating a class inside a package while importing another package.

→ package declaration
→ package import

//correct syntax
package p3;
import package p1.*;
//Declaring a package
package anotherpackage;
//importing a package
import letmecalculate.Calculator;
public class Example{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
Sub packages in Java
A package inside another package is known as sub package.
It should be created to categorize the package further.
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages.
Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.

For example If create a package inside letmecalculate package then that will be called sub
package.
Another package is created inside letmecalculate and the sub package name is multiply.
So if create a class in this subpackage it should have this package declaration in the beginning:
package letmecalculate.multiply;

Example:
//Multiplication.java
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;
}}
If we need to use this Multiplication class to some other program, to use this package in both
the ways:

import letmecalculate.multiply;
or
// fully qualified name
letmecalculate.multiply.Multiplication obj = new letmecalculate.multiply.Multiplication();

Extra Sample Programs Explanation


How to access package from another package?
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully quali ied name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:

char[] ch={'j','a','v','a'};
String s=new String(ch);

is same as:
String s="java";
Java String class provides a lot of methods to perform operations on strings such as

1. compare(),
2. concat(),
3. equals(),
4. split(),
5. length(),
6. replace(),
7. compareTo(),
8. intern(),
9. substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it.
It means, we can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed.


Whenever we change any string, a new instance is created.
For mutable strings, you can use StringBuffer and StringBuilder classes.
What is String in Java?
Generally, String is a sequence of characters.
But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java"; //creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
example

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of
char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... It returns a formatted string.


args)

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.
6 String substring(int beginIndex, int endIndex) It returns substring for given
begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, It replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It


doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value


index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring


index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string.


It is an overloaded method.

Immutable String in Java


A String is an unavoidable type of variable while writing any application program.
String references are used to store various attributes like username, password, etc.
In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new String object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar"); //concat() method appends the string at the end
System.out.println(s); //will print Sachin because strings are immutable objects
}
}
Output:
Sachin
two objects are created but s reference variable still refers to "Sachin" not to "Sachin
Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.
For example:
Testimmutablestring1.java
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar

Why String objects are immutable in Java?


As Java uses the concept of String literal.
Suppose there are 5 reference variables, all refer to one object "Sachin".
If one reference variable changes the value of the object, it will be affected by all the reference
variables.
That is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument.
Consider, if the String object is modifiable, the value might be changed and the class that
is supposed to be loaded might be different.
To avoid this kind of misinterpretation, String is immutable.

2. Thread Safe:

As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.

3. Security:

As we have seen in class loading, immutable String objects avoid further errors by loading
the correct class. This leads to making the application program more secure.
Consider an example of banking software. The username and password cannot be modified
by any intruder because String objects are immutable.
This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory.
When we try to declare a new String object, the JVM checks whether the value already exists
in the String pool or not.

If it exists, the same value is assigned to the new object. This feature allows Java to use the
heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override the methods
of the String class.
So that it can provide the same features to the new String objects as well as to the old ones.
Java String compare
We can compare String in Java on the basis of content and reference.
It is used in

1. Authentication (by equals() method),


2. sorting (by compareTo() method),
3. reference matching (by == operator) etc.

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

1) By Using equals() Method


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

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

Teststringcomparison1.java

1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }

Output:
true
true
false
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
Teststringcomparison2.java

1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5. System.out.println(s1.equals(s2));//false
6. System.out.println(s1.equalsIgnoreCase(s2));//true
7. }
8. }

Output:
false
true
In the above program, the methods of String class are used.
The equals() method returns true if String objects are matching and both strings are of same
case.
equalsIgnoreCase() returns true regardless of cases of strings.

2) By Using == operator
The == operator compares references not values.
Teststringcomparison3.java

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

Output:
true
false

3) By Using compareTo() method


The String class 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 objects. If:

 s1 == s2 : The method returns 0.


 s1 > s2 : The method returns a positive value.
 s1 < s2 : The method returns a negative value.

Teststringcomparison4.java

1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }

Output:
0
1
-1

String Concatenation in Java


In Java, String concatenation forms a new String that is the combination of multiple strings.
There are two ways to concatenate strings in Java:

1. By + (String concatenation) operator


2. By concat() method

1) String Concatenation by + (String concatenation) operator


Java String concatenation operator (+) is used to add strings. For Example:
TestStringConcatenation1.java

1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }

Sachin Tendulkar
The Java compiler transforms above code to this:

1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

In Java, String concatenation is implemented through the StringBuilder (or StringBuffer)


class and it's append method.
String concatenation operator produces a new String by appending the second operand onto
the end of the first operand.
The String concatenation operator can concatenate not only String but primitive values also.
For Example:
TestStringConcatenation2.java

1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
Output:
80Sachin4040

2) String Concatenation by concat() method


The String concat() method concatenates the specified string to the end of current string.
Syntax:

1. public String concat(String another)

Let's see the example of String concat() method.


TestStringConcatenation3.java

1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }

Output:
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.
There are some other possible ways to concatenate Strings in Java,
1. String concatenation using StringBuilder class
StringBuilder is class provides append() method to perform concatenation operation.
The append() method accepts arguments of different types like Objects, StringBuilder, int,
char, CharSequence, boolean, float, double.
StringBuilder is the most popular and fastet way to concatenate strings in Java.
It is mutable class which means values stored in StringBuilder objects can be updated or
changed.
StrBuilder.java

1. public class StrBuilder


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. StringBuilder s1 = new StringBuilder("Hello"); //String 1
7. StringBuilder s2 = new StringBuilder(" World"); //String 2
8. StringBuilder s = s1.append(s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:
Hello World
In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores
the result of concatenation of s1 and s2 using append() method.
2. String concatenation using format() method
String.format() method allows to concatenate multiple strings using format specifier like %s
followed by the string values or objects.
StrFormat.java

1. public class StrFormat


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.format("%s%s",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
} }
Output:
Hello World
Here, the String objects s is assigned the concatenated result of
Strings s1 and s2 using String.format() method.
format() accepts parameters as format specifier followed by String objects or values.

2. String concatenation using String.join() method


(Java Version 8+)

The String.join() method is available in Java version 8 and all the above versions.
String.join() method accepts arguments first a separator and an array of String objects.
StrJoin.java:

1. public class StrJoin


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.join("",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:
Hello World
In the above code snippet, the String object s stores the result of String.join("",s1,s2) method.
A separator is specified inside quotation marks followed by the String objects or array of String
objects.
4. String concatenation using StringJoiner class (Java Version 8+)
StringJoiner class has all the functionalities of String.join() method.
In advance its constructor can also accept optional arguments, prefix and suffix.
StrJoiner.java

1. public class StrJoiner


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. StringJoiner s = new StringJoiner(", "); //StringJoiner object
7. s.add("Hello"); //String 1
8. s.add("World"); //String 2
9. System.out.println(s.toString()); //Displays result
10. }
11. }

Output:
Hello, World
In the above code snippet, the StringJoiner object s is declared and the constructor
StringJoiner() accepts a separator value.
A separator is specified inside quotation marks.
The add() method appends Strings passed as arguments.
5. String concatenation using Collectors.joining() method (Java (Java Version 8+)
The Collectors class in Java 8 offers joining() method that concatenates the input elements in
a similar order as they occur.
ColJoining.java

1. import java.util.*;
2. import java.util.stream.Collectors;
3. public class ColJoining
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. List<String> liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array
9. String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operation
10. System.out.println(str.toString()); //Displays result
11. }
12. }

Output:
abc, pqr, xyz
Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.
Substring in Java
A part of String is called substring.
In other words, substring is a subset of another String.
Java String class provides the built-in substring() method that extract a substring from the given
string by using the index values passed as an argument.
In case of substring() method startIndex is inclusive and endIndex is exclusive.
Suppose the string is "computer", then the substring will be com, compu, ter, etc.
You can get substring from the given String object by one of the two methods:
public String substring(int startIndex):
This method returns new String object containing the substring of the given string from
specified startIndex (inclusive). The method throws an IndexOutOfBoundException when the
startIndex is larger than the length of String or less than zero.
public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from
specified startIndex to endIndex.
The method throws an IndexOutOfBoundException when the startIndex is less than zero or
startIndex is greater than endIndex or endIndex is greater than length of String.
In case of String:
 startIndex: inclusive
 endIndex: exclusive

The startIndex and endIndex by the code given below.

1. String s="hello";
2. System.out.println(s.substring(0,2)); //returns he as a substring

In the above substring, 0 points the first letter and 2 points the second letter
i.e., e (because end index is exclusive).
Example of Java substring() method
TestSubstring.java

1. public class TestSubstring{


2. public static void main(String args[]){
3. String s="SachinTendulkar";
4. System.out.println("Original String: " + s);
5. System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar
6. System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin
7. }
8. }

Output:
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin
The above Java programs, demonstrates variants of the substring() method of String class.
The startindex is inclusive and endindex is exclusive.
Using String.split() method:
The split() method of String class can be used to extract a substring from a sentence.
It accepts arguments in the form of a regular expression.
TestSubstring2.java

1. import java.util.*;
2.
3. public class TestSubstring2
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. String text= new String("Hello, My name is Sachin");
9. /* Splits the sentence by the delimeter passed as an argument */
10. String[] sentences = text.split("\\.");
11. System.out.println(Arrays.toString(sentences));
12. }
13. }

Output:
[Hello, My name is Sachin]
In the above program, we have used the split() method. It accepts an argument \\. that checks a
in the sentence and splits the string into another string. It is stored in an array of String objects
sentences
Java String Class Methods
The java.lang.String class provides a lot of built-in methods that are used to manipulate string
in Java.
By the help of these methods, we can perform operations on String objects such as trimming,
concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a String if you submit any
form in window based, web based or mobile application.
Java String toUpperCase() and toLowerCase() method
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Stringoperation1.java

1. public class Stringoperation1


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.toUpperCase()); //SACHIN
7. System.out.println(s.toLowerCase()); //sachin
8. System.out.println(s); //Sachin(no change in original)
9. }
10. }

Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java

1. public class Stringoperation2


2. {
3. public static void main(String ar[])
4. {
5. String s=" Sachin ";
6. System.out.println(s);// Sachin
7. System.out.println(s.trim());//Sachin
8. }
9. }

Output:
Sachin
Sachin
Java String startsWith() and endsWith() method
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
Stringoperation3.java

1. public class Stringoperation3


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.startsWith("Sa"));//true
7. System.out.println(s.endsWith("n"));//true
8. }
9. }

Output:
true
true
Java String charAt() Method
The String class charAt() method returns a character at specified index.
Stringoperation4.java

1. public class Stringoperation4


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.charAt(0)); //S
7. System.out.println(s.charAt(3)); //h
8. }
9. }

Output:
S
h
Java String length() Method
The String class length() method returns length of the specified String.
Stringoperation5.java
1. public class Stringoperation5
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }

Output:
6
Java String intern() Method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a String equal to this String
object as determined by the equals(Object) method, then the String from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.
Stringoperation6.java

1. public class Stringoperation6


2. {
3. public static void main(String ar[])
4. {
5. String s=new String("Sachin");
6. String s2=s.intern();
7. System.out.println(s2); //Sachin
8. }
9. }

Output:
Sachin
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into String.
Stringoperation7.java

1. public class Stringoperation7


2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }

Output:
1010
Java String replace() Method
The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.
Stringoperation8.java

1. public class Stringoperation8


2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is an Island.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"

7. System.out.println(replaceString);
8. }
9. }

Output:
Kava is a programming language. Kava is a platform. Kava is an Island.

Java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects.
The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.
Important Constructors of StringBuffer Class
Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string.

StringBuffer(int It creates an empty String buffer with the specified capacity as


capacity) length.

Important methods of StringBuffer class

What is a mutable String?


A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.
StringBufferExample.java

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4.
5. System.out.println(sb);
6. }
7. }

Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java

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

Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java

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

Output:
HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex
to endIndex.
StringBufferExample4.java

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

Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java

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

Output:
olleH
6) StringBuffer capacity() Method
The capacity() method of the 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.
StringBufferExample6.java

1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

Output:
16
16
34
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the 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.
StringBufferExample7.java

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

Output:
16
16
34
34
70

Java StringBuilder Class


Java StringBuilder class is used to create mutable (modifiable) String.
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
It is available since JDK 1.5.
Important Constructors of StringBuilder class
Constructor Description

StringBuilder() It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String It creates a String Builder with the specified string.


str)

StringBuilder(int It creates an empty String Builder with the specified capacity as


length) length.

Important methods of StringBuilder class


Method Description

public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.

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

public StringBuilder It is used to delete the string from specified startIndex and
delete(int startIndex, int endIndex.
endIndex)

public StringBuilder reverse() It is used to reverse the string.

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

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

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total number
of characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

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

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this String.
StringBuilderExample.java

1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

Output:
Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.
StringBuilderExample2.java

1. class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

Output:
HJavaello
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex
and endIndex.
StringBuilderExample3.java

1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

Output:
HJavalo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
StringBuilderExample4.java

1. class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

Output:
Hlo
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
StringBuilderExample5.java

1. class StringBuilderExample5{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

Output:
olleH
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder 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.
StringBuilderExample6.java

1. class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("Java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

Output:
16
16
34
7) StringBuilder ensureCapacity() method
The ensureCapacity() method of StringBuilder 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.
StringBuilderExample7.java

1. class StringBuilderExample7{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("Java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

Output:
16
16
34
34
70

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

2) String is slow and consumes more memory StringBuffer is fast and consumes
when we concatenate too many strings because less memory when we
every time it creates new instance. concatenate t strings.

3) String class overrides the equals() method of StringBuffer class doesn't


Object class. So you can compare the contents override the equals() method of
of two strings by equals() method. Object class.

4) String class is slower while performing StringBuffer class is faster while


concatenation operation. performing concatenation
operation.

5) String class uses String constant pool. StringBuffer uses Heap memory
Difference between StringBuffer and StringBuilder
Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e.


safe. It means two threads can't call the not thread safe. It means two threads can
methods of StringBuffer simultaneously. call the methods of StringBuilder
simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

1. /Java Program to demonstrate the use of StringBuffer class.


2. public class BufferTest{
3. public static void main(String[] args){
4. StringBuffer buffer=new StringBuffer("hello");
5. buffer.append("java");
6. System.out.println(buffer);
7. }
8. }

Output:
hellojava
StringBuilder Example
BuilderTest.java

1. //Java Program to demonstrate the use of StringBuilder class.


2. public class BuilderTest{
3. public static void main(String[] args){
4. StringBuilder builder=new StringBuilder("hello");
5. builder.append("java");
6. System.out.println(builder);
7. }
8. }

Output:
hellojava

Java toString() Method


If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depending on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.

Final, Finally, and Finalize


The final, finally, and finalize are keywords in Java that are used in exception handling.
Each of these keywords has a different functionality.
The basic difference between final, finally and finalize is that the final is an access
modifier finally is the block in Exception Handling and finalize is the method of object
class.
A list of differences between final, finally and finalize are given below:

Sr. Key final finally finalize


no.

1. Definition final is the keyword finally is the block in finalize is the method
and access modifier Java Exception in Java which is used
which is used to Handling to execute to perform clean up
apply restrictions on the important code processing just
a class, method or whether the before object is
variable. exception occurs or garbage collected.
not.

2. Applicable Final keyword is Finally block is finalize() method is


to used with the always related to the used with the objects.
classes, methods try and catch block in
and variables. exception handling.

3. Functionality (1) Once declared, (1) finally block runs finalize method
final variable the important code performs the
becomes constant even if exception cleaning activities
and cannot be occurs or not. with respect to the
modified. (2) finally block object before its
(2) final method cleans up all the destruction.
cannot be resources used in try
overridden by sub block
class.
(3) final class
cannot be inherited.
4. Execution Final method is Finally block is finalize method is
executed only when executed as soon as executed just before
we call it. the try-catch block is the object is
executed. destroyed.
It's execution is not
dependant on the
exception.

Java final Example


public class FinalExampleTest {
//declaring final variable
final int age = 18;
void display() {

// reassigning value to age variable


// gives compile time error
age = 55;
}

public static void main(String[] args) {

FinalExampleTest obj = new FinalExampleTest();


// gives compile time error
obj.display();
}
}

Output:

In the above example, we have declared a variable final. Similarly, we can declare the
methods and classes final using the final keyword.
Java finally Example
In this example where the Java code throws an exception and the catch block handles
that exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.

public class FinallyExample {


public static void main(String args[]){
try {
System.out.println("Inside try block");
// below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
// handles the Arithmetic Exception / Divide by zero exception
catch (ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
// executes regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Output:

Java finalize Example


public class FinalizeExample {
public static void main(String[] args)
{
FinalizeExample obj = new FinalizeExample();
// printing the hashcode
System.out.println("Hashcode is: " + obj.hashCode());
obj = null;
// calling the garbage collector using gc()
System.gc();
System.out.println("End of the garbage collection");
}
// defining the finalize method
protected void finalize()
{
System.out.println("Called the finalize() method");
}
}

Output:
Exception Handling in Java
 It is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
 Exception Handling is a mechanism to handle runtime errors
 such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
 An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.

Exception in Java
 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.

Advantage of Exception Handling


 The core advantage of exception handling is to maintain the normal
flow of the application.

Types of Java Exceptions


There are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
 An error is considered as the unchecked exception.
Difference between Checked and Unchecked Exceptions
1. Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time,
but they are checked at runtime.
3) Error
Error is irrecoverable.
Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.

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 below:
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur.
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) 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
3) 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
4) 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];
a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Keywords


Java provides five keywords that are used to handle the exception.

Keyword Description

try The "try" keyword is used to specify a block where we


should place an exception code.
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.

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;

Explanation:
 Suppose there are 10 statements in a Java program and an exception occurs
at statement 5;
 the rest 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.

Java try-catch block


1) Java try block is used to enclose the code that might throw an exception.
2. It must be used within the method.
3. If an exception occurs at the particular statement in the try block, the rest
of the block code will not execute.
4. So, it is recommended not to keep the code in try block that will not throw
an exception.
5. Java try block must be followed by either catch or finally block.
Java catch block
1. Java catch block is used to handle the Exception by declaring the type
of exception within the parameter.
2. The declared exception must be the parent class exception (i.e.,
Exception) or the generated exception type.
3. The good approach is to declare the generated type of exception.
4. The catch block must be used after the try block only.
5. You can use multiple catch block with a single try 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
{}

Internal Working of Java try-catch block

Explanation:
 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:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception
occurred).
 Causes the program to terminate.
 But if the application programmer handles the exception, the normal
flow of the application is maintained, i.e., rest of the code is executed.

Problem without exception handling

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

Explanation:
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.

 Solution to the above problem by exception handling


 Java Exception Handling Example
 In which we are using a try-catch statement to handle the exception.

public class JavaExceptionExample{


public static void main(String args[]){
try{
int data=100/0; //code that may raise exception
}
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...
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
 At a time only one exception occurs and at a time only one catch block is
executed.
 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 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

Example 2
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
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:
ArrayIndexOutOfBounds Exception occurs
rest of the code

This example, try block contains two exceptions.


But at a time only one exception occurs and its corresponding catch block is
executed.

Java Nested try block

 In Java, using a try block inside another try block is permitted.


 It is called as nested try block.
 Every statement that we enter a statement in try block, context of that
exception is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can
handle the ArithemeticException (division by zero).
Why use nested try block
where a part of a block may cause one error and the entire block itself may
cause another error.
Exception handlers have to be nested.
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....

Example:1
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}

//catch block of outer try block


catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
 When any try block does not have a catch block for a particular
exception, then the catch block of the outer (parent) try block are
checked for that exception, and if it matches, the catch block of outer
try block is executed.
 If none of the catch block specified in the code is unable to handle
the exception, then the Java runtime system will handle the
exception.
 It displays the system generated message for that exception.

public class NestedTryBlock2 {


public static void main(String args[])
{
// outer (main) try block
try {

//inner try block 1


try {

// inner try block 2


try {
int arr[] = { 1, 2, 3, 4 };

//printing the array element out of its bounds


System.out.println(arr[10]);
}

// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}

// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}

// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}

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 occurs or not.
 The finally block follows the try-catch block.

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

Why use Java finally block?


 finally block in Java can be used to put "cleanup" code such as closing a
file, closing connection, etc.
 The important statements to be printed can be placed in the finally block.
 Usage of Java finally

Example:
Case 1: When an exception occurs and is handled by the catch block

 In the example where the Java code throws an exception and the catch
block handles the exception.
 Later the finally block is executed after the try-catch block.
 Further, the rest of the code is also executed normally.
public class TestFinallyBlock2{
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}

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


}
}

Output:

Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if the program exits
(either by calling System.exit()
(or) by causing a fatal error that causes the process to abort).

Extra Programs with different situatons


The different cases where Java finally block can be used.
Case 2: When an exception does not occur

 In example where the Java program does not throw any exception, and the
finally block is executed after the try block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//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 phe code...");


}
}

Output:

Case 3: When an exception occur but not handled by the catch block

 In example the code throws an exception however the catch block cannot
handle it.
 Despite this, the finally block is executed after the try block and then the
program terminates abnormally.

public class TestFinallyBlock1{


public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:

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.
 specify the exception object which is to be thrown.
 The Exception has some message with it 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.
 define our own set of conditions and throw an exception explicitly using
throw keyword.
 For example, we can throw ArithmeticException if we divide a number by
another number.
 Here, we just need to set the condition and throw exception using throw
keyword.
 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.

syntax of the Java throw keyword is given below.

throw Instance
i.e.,
throw new exceptionclass("error message");

Example of throw IOException.

throw new IOException("sorry device error");

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

 The above code throw an unchecked exception.


 Similarly, we can also throw unchecked and user defined exceptions.
 Note: If we throw unchecked exception from a method, it is must to handle
the exception or declare in throws clause.
 If we throw a checked exception using throw keyword, it is must to handle
the exception using catch block or the method must declare it using
throws declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception
in Java.
A checked exception is everything else under the Throwable class.

import java.io.*;
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");


BufferedReader fileInput = new BufferedReader(file);

throw new FileNotFoundException();


}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:

Example 3: Throwing User-defined Exception


Exception is everything else under the Throwable class.
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:

Extra Programs with different exception handling

Example 1
Example, kept the code in a try block that will not throw an exception.

public class TryCatchExample {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
Explanation:
java.lang.ArithmeticException: / by zero
 if an exception occurs in the try block, the rest of the block code will
not execute.

Example 2 to handle another unchecked exception.


public class TryCatchExample{
public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code

Example3 to handle checked exception.

import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class TryCatchExample10 {
public static void main(String[] args) {
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
}
Output:
File saved successfully
Throw and Throws keywords
The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.
A list of differences between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is Java throws keyword is


used throw an used in the method
exception explicitly in signature to declare an
the code, inside the exception which might
function or the block be thrown by the
of code. function while the
execution of the code.

2. Type of exception Using Using throws


throw keyword, we can keyword, we can
only propagate declare both checked
unchecked exception and unchecked
i.e., the checked exceptions. However,
exception cannot be the throws keyword
propagated using throw can be used to
only. propagate checked
exceptions only.

3. Syntax The throw keyword is The throws keyword is


followed by an followed by class names
instance of Exception of Exceptions to be
to be thrown. thrown.

4. Declaration throw is used within throws is used with the


the method. method signature.

5. Internal implementation We are allowed to We can declare multiple


throw only one exceptions using throws
exception at a time keyword that can be
i.e. we cannot throw thrown by the method.
multiple exceptions. For example, main()
throws IOException,
SQLException.

Java throw Example


public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square"
);
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}

Output:

Java throws Example


public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

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


}
}

Output:
Java throw and throws Example
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}

Output:

You might also like