String And StringBuffer StringBuilder
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:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform
operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(),
substring() etc.
The java.lang.String class
implements Serializable, Comparable and CharSequence i
nterfaces.
2.2M
Java Try Catch
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.
Immutable -cannot be changed
Mutable – which can change
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.
We will discuss immutable string later. Let's first
understand what String in Java is and how to create the
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:
int a=10;
float b=60.70f
1. String s="welcome";
Each time you create a string literal, the JVM checks the
"string constant pool" first. If the string already exists in
the pool, a reference to the pooled instance is returned.
If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created.
Firstly, JVM will not find any string object with the value
"Welcome" in string constant pool, that is why it will
create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area
known as the "string constant pool".
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
1. String s=new String("Welcome");//creates two objects a
nd one reference variable
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) returns char value for the
particular index
2 int length() returns string length
3 static String format(String returns a formatted string.
format, Object... args)
4 static String format(Locale l, returns formatted string
String format, Object... args) with given locale.
5 String substring(int returns substring for given
beginIndex) begin index.
6 String substring(int returns substring for given
beginIndex, int endIndex) begin index and end index.
7 boolean returns true or false after
contains(CharSequence s) matching the sequence of
char value.
8 static String returns a joined string.
join(CharSequence delimiter,
CharSequence... elements)
9 static String returns a joined string.
join(CharSequence delimiter,
Iterable<? extends
CharSequence> elements)
10 boolean equals(Object checks the equality of
another) string with the given
object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified
string.
13 String replace(char old, char replaces all occurrences of
new) the specified char value.
14 String replace(CharSequence replaces all occurrences of
old, CharSequence new) the specified
CharSequence.
15 static String compares another string. It
equalsIgnoreCase(String doesn't check case.
another)
16 String[] split(String regex) returns a split string
matching regex.
17 String[] split(String regex, int returns a split string
limit) matching regex and limit.
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char
value index.
20 int indexOf(int ch, int returns the specified char
fromIndex) value index starting with
given index.
21 int indexOf(String substring) returns the specified
substring index.
22 int indexOf(String substring, returns the specified
int fromIndex) substring index starting
with given index.
23 String toLowerCase() returns a string in
lowercase.
24 String toLowerCase(Locale l) returns a string in
lowercase using specified
locale.
25 String toUpperCase() returns a string in
uppercase.
26 String toUpperCase(Locale l) returns a string in
uppercase using specified
locale.
27 String trim() removes beginning and
ending spaces of this
string.
28 static String valueOf(int converts given type into
value) string. It is an overloaded
method.
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
StringExample.java
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
The above code, converts a char array into
a String object. And displays the String objects s1, s2,
and s3 on console using println() method.
Immutable String in Java
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.
Let's try to understand the immutability concept by the
example given below:
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. String s1=s.concat(" Tendulkar");
5. System.out.prinltn(s.concat(" Tendulkar"));//concat() m
ethod appends the string at the end
6. System.out.println(s);//will print Sachin because strings
are immutable objects
7. }
8. }
Test it Now
Output:Sachin
Now it can be understood by the diagram given below.
Here Sachin is not changed but a new object is created
with sachintendulkar. That is why string is known as
immutable.
6.2M
10
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 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:
67
OOPs Concepts in Java
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.
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.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9. }
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 t
o same instance)
7. System.out.println(s1==s3);//false(because s3 refers to
instance created in nonpool)
8. }
9. }
Output:
true
false
3) String compare by compareTo() method
The above code, demonstrates the use of == operator
used for comparing two String objects.
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:
o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o 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>s
3)
8. System.out.println(s3.compareTo(s1));//-
1(because s3 < s1 )
9. }
10. }
Test it Now
Output:
0
1
-1
8
Hello Java Program for Beginners
As you can see in the above figure that two objects are
created but s reference variable still refers to "Sachin"
not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it
will refer to "Sachin Tendulkar" object.For example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please
notice that still sachin object is not modified.
String Concatenation in Java
In java, string concatenation forms a new string that
is the combination of multiple strings. There are two
ways to concat string 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:
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
Test it Now
Output: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 its 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 concat not only string but primitive values also. For
Example
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. }
Test it Now
80Sachin4040
Note: After a string literal, all the + will be treated as
string concatenation operator.
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.
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. }
Test it Now
Sachin Tendulkar
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.
Note: Index starts from 0.
You can get substring from the given String object by
one of the two methods:
1. 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.
2. 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:
o startIndex: inclusive
o endIndex: exclusive
Let's understand 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 sub
string
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.
Let's use some important methods of String class.
Java String toUpperCase() and toLowerCase() method
The Java String toUpperCase() method converts this
String into uppercase letter and String toLowerCase()
method into lowercase letter.
6.1M
149
Exception Handling in Java - Javatpoint
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. }
Test it Now
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. }
Test it Now
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. }
Test it Now
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. }
Test it Now
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. }
Test it Now
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. }
Test it Now
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 pla
tform. 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.
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() It creates an empty String buffer with th
initial capacity of 16.
StringBuffer(String It creates a String buffer with the specifie
str) string..
StringBuffer(int It creates an empty String buffer with th
capacity) specified capacity as length.
Important methods of StringBuffer class
Modifier and Method Description
Type
public append(String s) It is used to append the
synchronized specified string with this
StringBuffer string. The append()
method is overloaded like
append(char),
append(boolean),
append(int),
append(float),
append(double) etc.
public insert(int offset, It is used to insert the
synchronized String s) specified string with this
StringBuffer string at the specified
position. The insert()
method is overloaded like
insert(int, char), insert(int,
boolean), insert(int, int),
insert(int, float), insert(int,
double) etc.
public replace(int It is used to replace the
synchronized startIndex, int string from specified
endIndex, String
StringBuffer str) startIndex and endIndex.
public delete(int It is used to delete the
synchronized startIndex, int string from specified
StringBuffer endIndex) startIndex and endIndex.
public reverse() is used to reverse the
synchronized string.
StringBuffer
public int capacity() It is used to return the
current capacity.
public void ensureCapacity(int It is used to ensure the
minimumCapacity) capacity at least equal to
the given minimum.
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
beginIndex) substring from the
specified beginIndex.
public String substring(int It is used to return the
beginIndex, int substring from the
endIndex) specified beginIndex and
endIndex.
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
00:15/05:19
10 Sec
6.1M
149
Exception Handling in Java - Javatpoint
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
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
str) specified string.
StringBuilder(int It creates an empty String Builder with
length) the specified capacity as length.
Important methods of StringBuilder class
Method Description
public StringBuilder It is used to append the specified
append(String s) string with this string. The append()
method is overloaded like
append(char), append(boolean),
append(int), append(float),
append(double) etc.
public StringBuilder It is used to insert the specified string
insert(int offset, with this string at the specified
String s) 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
replace(int specified startIndex and endIndex.
startIndex, int
endIndex, String str)
public StringBuilder It is used to delete the string from
delete(int specified startIndex and endIndex.
startIndex, int
endIndex)
public StringBuilder It is used to reverse the string.
reverse()
public int capacity() It is used to return the current
capacity.
public void It is used to ensure the capacity at
ensureCapacity(int least equal to the given minimum.
minimumCapacity)
public char It is used to return the character at
charAt(int index) the specified position.
public int length() It is used to return the length of the
string i.e. total number of characters.
public String It is used to return the substring from
substring(int the specified beginIndex.
beginIndex)
public String It is used to return the substring from
substring(int the specified beginIndex and
beginIndex, int endIndex.
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
77.6K
8. Modules and PHP Abstract class | Build a CMS using OOP
PHP CMS tutorial MVC [2020]
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:
public class ConcatTest{
public static String concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "Tpoint";
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
return sb.toString();
}
public static void main(String[] args){
long startTime = System.currentTimeMillis();
concatWithString();
System.out.println("Time taken by Concating with Stri
ng: "+(System.currentTimeMillis()-startTime)+"ms");
startTime = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Time taken by Concating with Stri
ngBuffer: "+(System.currentTimeMillis()-startTime)+"ms");
}
}
Time taken by Concating with String:
578ms
Time taken by Concating with
StringBuffer: 0ms
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.
A list of differences between StringBuffer and
StringBuilder are given below:
StringBuffer Example
//Java Program to demonstrate the use of StringBuffer clas
s.
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
hellojava
StringBuilder Example
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. }
hellojava
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of
StringBuffer and StringBuilder classes.
//Java Program to demonstrate the performance of StringB
uffer and StringBuilder classes.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " + (Sy
stem.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("Tpoint");
}
System.out.println("Time taken by StringBuilder: " + (S
ystem.currentTimeMillis() - startTime) + "ms");
}
}
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
Interface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while
it is not supported in case of class.
5. Marker Interface
6. Nested Interface
An interface in Java is a blueprint of a class. It has static
constants and abstract methods.
The interface in Java is a mechanism to
achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method
body.
Java Interface also represents the IS-A relationship.
6.1M
151
Features of Java - Javatpoint
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static
methods in an interface.
Since Java 9, we can have private methods in an
interface.
Why use Java interface?
There are mainly three reasons to use interface. They are
given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of
multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword.
It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the
fields are public, static and final by default. A class that
implements an interface must implement all the
methods declared in the interface.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Java 8 Interface Improvement
Since Java 8, interface can have default and static
methods which is discussed later.
Internal addition by the compiler
The Java compiler adds public and abstract keywords
before the interface method. Moreover, it adds public,
static and final keywords before data members.
In other words, Interface fields are public, static and final
by default, and the methods are public and abstract.
The relationship between classes and interfaces
As shown in the figure given below, a class extends
another class, an interface extends another interface, but
a class implements an interface.
Java Interface Example
In this example, the Printable interface has only one
method, and its implementation is provided in the A6
class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Test it Now
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one
method. Its implementation is provided by Rectangle
and Circle classes. In a real scenario, an interface is
defined by someone else, but its implementation is
provided by different implementation providers.
Moreover, it is used by someone else. The
implementation part is hidden by the user who uses the
interface.
File: TestInterface1.java
1. //Interface declaration: by first user
2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangl
e");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circl
e");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is
provided by method e.g. getDrawable()
16. d.draw();
17. }}
Test it Now
Output:
drawing circle
Java Interface Example: Bank
Let's see another example of java interface which
provides the implementation of Bank interface.
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Test it Now
Output:
ROI: 9.15
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface
extends multiple interfaces, it is known as multiple
inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Test it Now
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in
java, but it is possible by an interface, why?
As we have explained in the inheritance chapter,
multiple inheritance is not supported in the case
of class because of ambiguity. However, it is supported
in case of an interface because there is no ambiguity. It
is because its implementation is provided by the
implementation class. For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }
Test it Now
Output:
Hello
As you can see in the above example, Printable and
Showable interface have same methods but its
implementation is provided by class TestTnterface1, so
there is no ambiguity.
Interface inheritance
A class implements an interface, but one interface
extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Test it Now
Output:
Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But
we need to make it default method. Let's see an
example:
File: TestInterfaceDefault.java
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method")
;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangl
e");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}
Test it Now
Output:
drawing rectangle
default method
Java 8 Static Method in Interface
Since Java 8, we can have static method in interface.
Let's see an example:
File: TestInterfaceStatic.java
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangl
e");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}
Test it Now
Output:
drawing rectangle
27
Q) What is marker or tagged interface?
An interface which has no member is known as a marker
or tagged interface, for example, Serializable, Cloneable,
Remote, etc. They are used to provide some essential
information to the JVM so that JVM may perform some
useful operation.
1. //How Serializable interface is written?
2. public interface Serializable{
3. }
Nested Interface in Java
Note: An interface can have another interface which is
known as a nested interface. We will learn it in detail in
the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
More about Nested Interface
Difference between abstract class and interface
Abstract class and interface both are used to achieve
abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.
But there are many differences between abstract class
and interface that are given below.
Abstract class Interface
1) Abstract class can have Interface can have only
abstract and non- abstract methods. Since
abstract methods. Java 8, it can have default
and static methods also.
2) Abstract class doesn't Interface supports multiple
support multiple inheritance. inheritance.
3) Abstract class can have Interface has only static and
final, non-final, static and final variables.
non-static variables.
4) Abstract class can provide Interface can't provide the
the implementation of implementation of
interface. abstract class.
5) The abstract keyword is The interface keyword is
used to declare abstract class. used to declare interface.
6) An abstract class can extend An interface can extend
another Java class and another Java interface only.
implement multiple Java
interfaces.
7) An abstract class can be An interface can be
extended using keyword implemented using keyword
"extends". "implements".
8) A Java abstract class can Members of a Java interface
have class members like are public by default.
private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to
100%) whereas interface achieves fully abstraction
(100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface
and abstract class both.
2.2M
Java Try Catch
1. //Creating interface that has 4 methods
2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementati
on of one method of A interface
10. abstract class B implements A{
11. public void c(){System.out.println("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need t
o provide the implementation of rest of the methods
15. class M extends B{
16. public void a(){System.out.println("I am a");}
17. public void b(){System.out.println("I am b");}
18. public void d(){System.out.println("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A in
terface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}
Test it Now
Output:
I am a
I am b
I am c
I am d
Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class
A java package is a group of similar types of classes,
interfaces and sub-packages.
Package in java can be categorized in two form, built-in
package and user-defined package.
There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and
using user-defined packages.
6M
113
Difference between JDK, JRE, and JVM
Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in
java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow
the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the
generated class file. You can use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same
directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple
etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file
it represents destination. The . represents the current folder.
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.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared
class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
3) Using fully qualified 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
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be
imported.
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.
Subpackage in java
Package inside the package is called the subpackage. It
should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a
package named java that contains many classes like
System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer
classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on.
So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
The standard of defining package is
domain.company.package e.g. com.javatpoint.bean or
org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java
source file in classes folder of c: drive. For example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to
classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of
java:
The -classpath switch can be used with javac and java
tool.
To run this program from e:\source directory, you can
use -classpath switch of java that tells where to look for
class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package
Ways to load the class files or jar files
There are two ways to load the class files temporary and permanen
o Temporary
o By setting the classpath in the command
prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment
variables
o By creating the jar file, that contains all the
class files, and copying the jar file in the
jre/lib/ext folder.
Rule: There can be only one public class in a java
source file and it must be saved by the public class
name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
How to put two public classes in a package?
If you want to put two public classes in a package, have two ja
source files containing one public class, but keep the package na
same. For example:
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
Java Static Import
The static import feature of Java 5 facilitate the java
programmer to access any static member of a class
directly. There is no need to qualify it by the class name.
Advantage of static import:
o Less coding is required if you have access any static
member of a class oftenly.
Disadvantage of static import:
o If you overuse the static import feature, it makes the
program unreadable and unmaintainable.
Simple Example of static import
1. import static java.lang.System.*;
2. class StaticImportExample{
3. public static void main(String args[]){
4.
5. out.println("Hello");//Now no need of System.out
6. out.println("Java");
7.
8. }
9. }
Output:Hello
Java
What is the difference between import and static import?
The import allows the java programmer to access classes
of a package without package qualification whereas the
static import feature allows to access the static members
of a class without the class qualification. The import
provides accessibility to classes and interface whereas
static import provides accessibility to static members of
the class
Package class
The package class provides methods to get information
about the specification and implementation of a
package. It provides methods such as getName(),
getImplementationTitle(), getImplementationVendor(),
getImplementationVersion() etc.
Example of Package class
In this example, we are printing the details of java.lang
package by invoking the methods of package class.
1. class PackageInfo{
2. public static void main(String args[]){
3.
4. Package p=Package.getPackage("java.lang");
5.
6. System.out.println("package name: "+p.getName());
7.
8. System.out.println("Specification Title: "+p.getSpecificati
onTitle());
9. System.out.println("Specification Vendor: "+p.getSpecific
ationVendor());
10. System.out.println("Specification Version: "+p.getSp
ecificationVersion());
11.
12. System.out.println("Implementaion Title: "+p.getImp
lementationTitle());
13. System.out.println("Implementation Vendor: "+p.get
ImplementationVendor());
14. System.out.println("Implementation Version: "+p.ge
tImplementationVersion());
15. System.out.println("Is sealed: "+p.isSealed());
16.
17.
18. }
19. }
Output:package name: java.lang
Specification Title: Java
Plateform API Specification
Specification Vendor: Sun
Microsystems, Inc.
Specification Version: 1.6
Implemenation Title: Java Runtime
Environment
Implemenation Vendor: Sun
Microsystems, Inc.
Implemenation Version: 1.6.0_30
IS sealed: false
Access Modifiers in Java
There are two types of modifiers in Java: access
modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is
only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is
only within the package. It cannot be accessed from
outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier
is within the package and outside the package
through child class. If you do not make the child
class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is
everywhere. It can be accessed from within the
class, outside the class, within the package and
outside the package.
There are many non-access modifiers, such as static,
abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.
4.5M
68
SQL CREATE TABLE
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple
table.
Access within within outside package outside
Modifier class package by subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Object class in Java
The Object class is the parent class of all the classes in
java by default. In other words, it is the topmost class of
java.
The Object class is beneficial if you want to refer any
object whose type you don't know. Notice that parent
class reference variable can refer the child class object,
know as upcasting.
Let's take an example, there is getObject() method that
returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference
to refer that object. For example:
1. Object obj=getObject();//we don't know what object will
be returned from this method
The Object class provides some common behaviors to all
the objects such as object can be compared, object can
be cloned, object can be notified etc.
2.2M
Java Try Catch
Methods of Object class
The Object class provides many methods. They are as follows:
Method Description
public final Class getClass() returns the
Class class
object of this
object. The
Class class can
further be used
to get the
metadata of
this class.
public int hashCode() returns the
hashcode
number for this
object.
public boolean equals(Object obj) compares the
given object to
this object.
protected Object clone() throws creates and
CloneNotSupportedException returns the
exact copy
(clone) of this
object.
public String toString() returns the
string
representation
of this object.
public final void notify() wakes up single
thread, waiting
on this object's
monitor.
public final void notifyAll() wakes up all the
threads, waiting
on this object's
monitor.
public final void wait(long timeout)throws causes the
InterruptedException current thread
to wait for the
specified
milliseconds,
until another
thread notifies
(invokes notify()
or notifyAll()
method).
public final void wait(long timeout,int causes the
nanos)throws InterruptedException current thread
to wait for the
specified
milliseconds
and
nanoseconds,
until another
thread notifies
(invokes notify()
or notifyAll()
method).
public final void wait()throws causes the
InterruptedException current thread
to wait, until
another thread
notifies
(invokes notify()
or notifyAll()
method).
protected void finalize()throws Throwable is invoked by
the garbage
collector before
object is being
garbage
collected.
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
the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's
types, 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.
2.2M
Java Try Catch
What is Exception Handling?
Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to
maintain the normal flow of the application. An
exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions.
Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
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.
That is why we use exception handling in Java.
Do You Know?
o What is the difference between checked and unchecked
exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws
keyword?
o What are the 4 rules for using exception handling with
method overriding?
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:
Types of Java Exceptions
There are mainly two types of exceptions: checked and
unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three
types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
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.
Java Exception Keywords
Java provides five keywords that are used to handle the
exception. The following table describes each.
Keyword Description
try The "try" keyword is used to specify a block where w
should place an exception code. It means we can't use t
block alone. The try block must be followed by eith
catch or finally.
catch The "catch" block is used to handle the exception. It mu
be preceded by try block which means we can't use catc
block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary cod
of the program. It is executed whether an exception
handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions.
specifies that there may occur an exception in th
method. It doesn't throw an exception. It is always use
with method signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling in
which we are using a try-catch statement to handle the
exception.
JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now
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.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked
exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an
ArithmeticException.
1. 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.
1. String s=null;
2. 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.
1. String s="abc";
2. 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.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Java Exceptions Index
1. Java Try-Catch Block
2. Java Multiple Catch Block
3. Java Nested Try
4. Java Finally Block
5. Java Throw Keyword
6. Java Exception Propagation
7. Java Throws Keyword
8. Java Throw vs Throws
9. Java Final vs Finally vs Finalize
10. Java Exception Handling with Method
Overriding
11. Java Custom Exceptions
Java try-catch block
Java try block
Java try block is used to enclose the code that might
throw an exception. It must be used within the method.
If an exception occurs at the particular statement in the
try block, the rest of the block code will not execute. So,
it is recommended not to keep the code in try block that
will not throw an exception.
Java try block must be followed by either catch or finally
block.
Syntax of Java try-catch
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }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.
2.5M
67
OOPs Concepts in Java
The catch block must be used after the try block only.
You can use multiple catch block with a single try block.
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled
or not. If exception is not handled, JVM provides a
default exception handler that performs the following
tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where
the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the
exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Problem without exception handling
Let's try to understand the problem if we don't use a try-
catch block.
Example 1
TryCatchExample1.java
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }
Test it Now
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 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 by exception handling
Let's see the solution of the above problem by a java
try-catch block.
Example 2
TryCatchExample2.java
1. public class TryCatchExample2 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now
Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the
code is executed, i.e., the rest of the code statement is
printed.
Example 3
In this example, we also kept the code in a try block that
will not throw an exception.
TryCatchExample3.java
1. public class TryCatchExample3 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining stat
ement will not exceute
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }
Test it Now
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try
block, the rest of the block code will not execute.
Example 4
Here, we handle the exception using the parent class
exception.
TryCatchExample4.java
1. public class TryCatchExample4 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception clas
s
9. catch(Exception e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Test it Now
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on
exception.
TryCatchExample5.java
1. public class TryCatchExample5 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }
Test it Now
Output:
Can't divided by zero
Example 6
Let's see an example to resolve the exception in a catch
block.
TryCatchExample6.java
1. public class TryCatchExample6 {
2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Test it Now
Output:
25
Example 7
In this example, along with try block, we also enclose
exception code in a catch block.
TryCatchExample7.java
1. public class TryCatchExample7 {
2.
3. public static void main(String[] args) {
4.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. System.out.println("rest of the code");
18. }
19. }
Test it Now
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the
exception code. So, enclose exception code within a try
block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception
(Arithmetic Exception) with a different type of exception
class (ArrayIndexOutOfBoundsException).
TryCatchExample8.java
1. public class TryCatchExample8 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using Arr
ayIndexOutOfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
Example 9
Let's see an example to handle another unchecked
exception.
TryCatchExample9.java
1. public class TryCatchExample9 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. System.out.println(arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Test it Now
Output:
java.lang.ArrayIndexOutOfBoundsException:
10
rest of the code
Example 10
Let's see an example to handle checked exception.
TryCatchExample10.java
1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw
exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Test it Now
Output:
File saved successfully
Java Catch Multiple Exceptions
Java Multi-catch block
A try block can be followed by one or more catch blocks.
Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch
block.
Points to remember
o At a time only one exception occurs and at a time
only one catch block is executed.
o All catch blocks must be ordered from most specific
to most general, i.e. catch for ArithmeticException
must come before catch for Exception.
Flowchart of Multi-catch Block
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
1. public class MultipleCatchBlock1 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception
occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBou
nds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occ
urs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:
3.7M
60
Prime Ministers of India | List of Prime Minister of India
(1947-2020)
Arithmetic Exception occurs
rest of the code
Example 2
MultipleCatchBlock2.java
1. public class MultipleCatchBlock2 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception
occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBou
nds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occ
urs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
In this example, try block contains two exceptions. But at
a time only one exception occurs and its corresponding
catch block is executed.
MultipleCatchBlock3.java
1. public class MultipleCatchBlock3 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception
occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBou
nds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occ
urs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now
Output:
Arithmetic Exception occurs
rest of the code
Example 4
In this example, we generate NullPointerException, but
didn't provide the corresponding exception type. In such
case, the catch block containing the parent exception
class Exception will invoked.
MultipleCatchBlock4.java
1. public class MultipleCatchBlock4 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. System.out.println(s.length());
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception
occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBou
nds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occ
urs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:
Parent Exception occurs
rest of the code
Example 5
Let's see an example, to handle the exception without
maintaining the order of exceptions (i.e. from most
specific to most general).
MultipleCatchBlock5.java
1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task c
ompleted");}
8. catch(ArithmeticException e){System.out.println("task1
is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out
.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
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
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:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
Java Nested try Example
Example 1
Let's see an example where we place a try block within
another try block for two different exceptions.
5.5M
121
HTML Tutorial
NestedTryBlock.java
1. public class NestedTryBlock{
2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer
catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }
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. Then it displays the system
generated message for that exception.
Example 2
Let's consider the following example. Here the try block
within nested try block (inner try block 2) do not handle
the exception. The control is then transferred to its
parent try block (inner try block 1). If it does not handle
the exception, then the control is transferred to the main
try block (outer try block) where the appropriate catch
block handles the exception. It is termed as nesting.
NestedTryBlock.java
1. public class NestedTryBlock2 {
2.
3. public static void main(String args[])
4. {
5. // outer (main) try block
6. try {
7.
8. //inner try block 1
9. try {
10.
11. // inner try block 2
12. try {
13. int arr[] = { 1, 2, 3, 4 };
14.
15. //printing the array element out of its b
ounds
16. System.out.println(arr[10]);
17. }
18.
19. // to handles ArithmeticException
20. catch (ArithmeticException e) {
21. System.out.println("Arithmetic exceptio
n");
22. System.out.println(" inner try block 2");
23. }
24. }
25.
26. // to handle ArithmeticException
27. catch (ArithmeticException e) {
28. System.out.println("Arithmetic exception")
;
29. System.out.println("inner try block 1");
30. }
31. }
32.
33. // to handle ArrayIndexOutOfBoundsException
34. catch (ArrayIndexOutOfBoundsException e4) {
35. System.out.print(e4);
36. System.out.println(" outer (main) try block");
37. }
38. catch (Exception e5) {
39. System.out.print("Exception");
40. System.out.println(" handled in main try-
block");
41. }
42. }
43. }
Output:
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.
Flowchart of finally block
Note: If you don't handle the exception, before
terminating the program, JVM executes finally block (if
any).
Why use Java finally block?
o finally block in Java can be used to put "cleanup"
code such as closing a file, closing connection, etc.
o The important statements to be printed can be
placed in the finally block.
Usage of Java finally
Let's see the different cases where Java finally block can
be used.
2.3M
56
History of Java
Case 1: When an exception does not occur
Let's see the below example where the Java program
does not throw any exception, and the finally block is
executed after the try block.
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed")
;
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:
Case 2: When an exception occurr but not handled by
the catch block
Let's see the the fillowing example. Here, 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.
TestFinallyBlock1.java
1. public class TestFinallyBlock1{
2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or n
ot
19. finally {
20. System.out.println("finally block is always execu
ted");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }
Output:
Case 3: When an exception occurs and is handled by
the catch block
Example:
Let's see the following 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.
TestFinallyBlock2.java
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by z
ero exception
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or n
ot
20. finally {
21. System.out.println("finally block is always execu
ted");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }
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).
Java throw exception
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.
1. throw exception;
Let's see the example of throw IOException.
5M
94
Triggers in SQL (Hindi)
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.
1. public class TestThrow1{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Exception in thread main
java.lang.ArithmeticException:not valid
Java Exception Propagation
An exception is first thrown from the top of the stack
and if it is not caught, it drops down the call stack to the
previous method. If not caught there, the exception
again drops down to the previous method, and so on
until they are caught or until they reach the very bottom
of the call stack. This is called exception propagation.
Note: By default Unchecked Exceptions are forwarded in
calling chain (propagated).
Exception Propagation Example
TestExceptionPropagation1.java
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception
handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptio
nPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Test it Now
Output:
exception handled
normal flow...
In the above example exception occurs in the m()
method where it is not handled, so it is propagated to
the previous n() method where it is not handled, again it
is propagated to the p() method where exception is
handled.
6.2M
108
Hello Java Program for Beginners
Exception can be handled in any method in call stack
either in the main() method, p() method, n() method or
m() method.
Note: By default, Checked Exceptions are not forwarded
in calling chain (propagated).
Exception Propagation Example
TestExceptionPropagation1.java
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//check
ed exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception
handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptio
nPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Test it Now
Output:
Compile Time Error
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
1. return_type method_name() throws exception_class_na
me{
2. //method code
3. }
Which exception should be declared
Ans) checked exception only, because:
o unchecked Exception: under your control so
correct your code.
o error: beyond your control e.g. you are unable to
do anything if there occurs VirtualMachineError or
StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded
in call stack).
5.5M
121
HTML Tutorial
It provides information to the caller of the method about
the exception.
Java throws example
Let's see the example of java throws clause which
describes that checked exceptions can be propagated by
throws keyword.
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exc
eption
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception
handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Test it Now
Output:
exception handled
normal flow...
Rule: If you are calling a method that declares an
exception, you must either caught or declare the
exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception us
try/catch.
2. Case2:You declare the exception i.e. specifying throws with
method.
Case1: You handle the exception
o In case you handle the exception, the code will be
executed fine whether exception occurs during the
program or not.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception
handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Test it Now
Output:exception handled
normal flow...
Case2: You declare the exception
o A)In case you declare the exception, if exception
does not occur, the code will be executed fine.
o B)In case you declare the exception if exception
occures, an exception will be thrown at runtime
because throws does not handle the exception.
A)Program if exception does not occur
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOExcepti
on{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now
Output:device operation performed
normal flow...
B)Program if exception occurs
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOExcepti
on{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now
Output:Runtime Exception
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 Java throws keyword is used
used to explicitly throw declare an exception.
an exception.
2) Checked exception Checked exception can b
cannot be propagated propagated with throws.
using throw only.
3) Throw is followed by an Throws is followed by class.
instance.
4) Throw is used within the Throws is used with the metho
method. signature.
5) You cannot throw You can declare multip
multiple exceptions. exceptions e.
public void method()throw
IOException,SQLException.
Java throw example
1. void m(){
2. throw new ArithmeticException("sorry");
3. }
Java throws example
1. void m()throws ArithmeticException{
2. //method code
3. }
Java throw and throws example
1. void m()throws ArithmeticException{
2. throw new ArithmeticException("sorry");
3. }
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 Finally is used to Finalize is use
restrictions on class, place important to perform clea
method and variable. code, it will be up processin
Final class can't be executed just befo
inherited, final method whether object is garbag
can't be overridden and exception is collected.
final variable value can't handled or not.
be changed.
2) Final is a keyword. Finally is a block. Finalize is
method.
Java final example
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
Java final example
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
Java finally example
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");}
7. }}
Java finalize example
1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");
}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc();
9. }}
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 Java throws keyword is used
used to explicitly throw declare an exception.
an exception.
2) Checked exception Checked exception can b
cannot be propagated propagated with throws.
using throw only.
3) Throw is followed by an Throws is followed by class.
instance.
4) Throw is used within the Throws is used with the metho
method. signature.
5) You cannot throw You can declare multip
multiple exceptions. exceptions e.
public void method()throw
IOException,SQLException.
Java throw example
1. void m(){
2. throw new ArithmeticException("sorry");
3. }
Java throws example
1. void m()throws ArithmeticException{
2. //method code
3. }
Java throw and throws example
1. void m()throws ArithmeticException{
2. throw new ArithmeticException("sorry");
3. }
ExceptionHandling with MethodOverriding in Java
There are many rules if we talk about methodoverriding w
exception handling. The Rules are as follows:
o If the superclass method does not declare an exception
o If the superclass method does not declare an excepti
subclass overridden method cannot declare the check
exception but it can declare unchecked exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subcl
overridden method can declare same, subclass exception
no exception but cannot declare parent exception.
If the superclass method does not declare an exception
1) Rule: If the superclass method does not declare an
exception, subclass overridden method cannot declare
the checked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild extends Parent{
7. void msg()throws IOException{
8. System.out.println("TestExceptionChild");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild();
12. p.msg();
13. }
14. }
Test it Now
Output:Compile Time Error
2) Rule: If the superclass method does not declare an
exception, subclass overridden method cannot declare
the checked exception but can declare unchecked
exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild1 extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild1();
12. p.msg();
13. }
14. }
Test it Now
Output:child
If the superclass method declares an exception
1) Rule: If the superclass method declares an exception,
subclass overridden method can declare same,
subclass exception or no exception but cannot declare
parent exception.
Example in case subclass overridden method declares
parent exception
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.prin
tln("parent");}
4. }
5.
6. class TestExceptionChild2 extends Parent{
7. void msg()throws Exception{System.out.println("child")
;}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild2();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:Compile Time Error
Example in case subclass overridden method declares
same exception
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent
");}
4. }
5.
6. class TestExceptionChild3 extends Parent{
7. void msg()throws Exception{System.out.println("child")
;}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild3();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:child
Example in case subclass overridden method declares
subclass exception
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent
");}
4. }
5.
6. class TestExceptionChild4 extends Parent{
7. void msg()throws ArithmeticException{System.out.prin
tln("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild4();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:child
Example in case subclass overridden method declares
no exception
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent
");}
4. }
5.
6. class TestExceptionChild5 extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild5();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:child
ava Custom Exception
If you are creating your own Exception that is known as
custom exception or user-defined exception. Java
custom exceptions are used to customize the exception
according to user need.
By the help of custom exception, you can have your own
exception and message.
Let's see a simple example of java custom exception.
1. class InvalidAgeException extends Exception{
2. InvalidAgeException(String s){
3. super(s);
4. }
5. }
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeExceptio
n{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Excepti
on occured: "+m);}
14.
15. System.out.println("rest of the code...");
16. }
17. }
Test it Now
Output:Exception occured:
InvalidAgeException:not valid
rest of the code...