Java Unit 3
Java Unit 3
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array.
It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5
PACKAGE
1. Package in Java is a collection or pack or group of classes, sub-packages, and
interfaces.
2. It helps organize your classes and interfaces into a folder structure
3. and make it easy to locate and use them.
4. it helps improve code reusability.
5. Each package in Java has its unique name and organizes its classes and interfaces
into a separate namespace, or name group.
6. Although interfaces and classes with the same name cannot appear in the same
package, they can appear in different packages.
7. This is possible by assigning a separate namespace to each Java package.
Advantages of using a package in Java
Reusability: While developing a project in java, there are few things that are writing
again and again in our code. Using packages, create such things in form of classes inside
a package and whenever need to perform that same task, just import that package and
use the class.
Better Organization: Again, in large java projects where we have several hundreds of
classes, it is always required to group the similar types of classes in a meaningful package
name so that you can organize your project better and when you need something you can
quickly locate it and use it, which improves the efficiency.
Name Conflicts: We can define two classes with the same name in different packages
so to avoid name collision
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Syntax:-
package nameOfPackage;
Example 1: Java packages
package letmecalculate; //New package created (or) the package declaration
public class Calculator //class defined
{
public int add(int a, int b) //method defined
{
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator(); // object created
System.out.println(obj.add(10, 20)); // calling method
}
}
Explanation:
I have created a class Calculator inside a package name letmecalculate.
To create a class inside a package, declare the package name in the first
statement in your program.
A class can have only one package declaration.
Calculator.java file created inside a package letmecalculate
Syntax
import packageName;
→ package declaration
→ package import
//correct syntax
package p3;
import package p1.*;
//Declaring a package
package anotherpackage;
//importing a package
import letmecalculate.Calculator;
public class Example{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
Sub packages in Java
A package inside another package is known as sub package.
It should be created to categorize the package further.
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages.
Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
For example If create a package inside letmecalculate package then that will be called sub
package.
Another package is created inside letmecalculate and the sub package name is multiply.
So if create a class in this subpackage it should have this package declaration in the beginning:
package letmecalculate.multiply;
Example:
//Multiplication.java
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;
}}
If we need to use this Multiplication class to some other program, to use this package in both
the ways:
import letmecalculate.multiply;
or
// fully qualified name
letmecalculate.multiply.Multiplication obj = new letmecalculate.multiply.Multiplication();
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully quali ied name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:
char[] ch={'j','a','v','a'};
String s=new String(ch);
is same as:
String s="java";
Java String class provides a lot of methods to perform operations on strings such as
1. compare(),
2. concat(),
3. equals(),
4. split(),
5. length(),
6. replace(),
7. compareTo(),
8. intern(),
9. substring() etc.
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.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java"; //creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
example
2. Thread Safe:
As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by loading
the correct class. This leads to making the application program more secure.
Consider an example of banking software. The username and password cannot be modified
by any intruder because String objects are immutable.
This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory.
When we try to declare a new String object, the JVM checks whether the value already exists
in the String pool or not.
If it exists, the same value is assigned to the new object. This feature allows Java to use the
heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override the methods
of the String class.
So that it can provide the same features to the new String objects as well as to the old ones.
Java String compare
We can compare String in Java on the basis of content and reference.
It is used in
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this string to another
string, ignoring case.
Teststringcomparison1.java
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
Output:
true
true
false
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
Teststringcomparison2.java
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5. System.out.println(s1.equals(s2));//false
6. System.out.println(s1.equalsIgnoreCase(s2));//true
7. }
8. }
Output:
false
true
In the above program, the methods of String class are used.
The equals() method returns true if String objects are matching and both strings are of same
case.
equalsIgnoreCase() returns true regardless of cases of strings.
2) By Using == operator
The == operator compares references not values.
Teststringcomparison3.java
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Output:
true
false
Teststringcomparison4.java
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
Output:
0
1
-1
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
Sachin Tendulkar
The Java compiler transforms above code to this:
1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
Output:
80Sachin4040
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }
Output:
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.
There are some other possible ways to concatenate Strings in Java,
1. String concatenation using StringBuilder class
StringBuilder is class provides append() method to perform concatenation operation.
The append() method accepts arguments of different types like Objects, StringBuilder, int,
char, CharSequence, boolean, float, double.
StringBuilder is the most popular and fastet way to concatenate strings in Java.
It is mutable class which means values stored in StringBuilder objects can be updated or
changed.
StrBuilder.java
Output:
Hello World
In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores
the result of concatenation of s1 and s2 using append() method.
2. String concatenation using format() method
String.format() method allows to concatenate multiple strings using format specifier like %s
followed by the string values or objects.
StrFormat.java
The String.join() method is available in Java version 8 and all the above versions.
String.join() method accepts arguments first a separator and an array of String objects.
StrJoin.java:
Output:
Hello World
In the above code snippet, the String object s stores the result of String.join("",s1,s2) method.
A separator is specified inside quotation marks followed by the String objects or array of String
objects.
4. String concatenation using StringJoiner class (Java Version 8+)
StringJoiner class has all the functionalities of String.join() method.
In advance its constructor can also accept optional arguments, prefix and suffix.
StrJoiner.java
Output:
Hello, World
In the above code snippet, the StringJoiner object s is declared and the constructor
StringJoiner() accepts a separator value.
A separator is specified inside quotation marks.
The add() method appends Strings passed as arguments.
5. String concatenation using Collectors.joining() method (Java (Java Version 8+)
The Collectors class in Java 8 offers joining() method that concatenates the input elements in
a similar order as they occur.
ColJoining.java
1. import java.util.*;
2. import java.util.stream.Collectors;
3. public class ColJoining
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. List<String> liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array
9. String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operation
10. System.out.println(str.toString()); //Displays result
11. }
12. }
Output:
abc, pqr, xyz
Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.
Substring in Java
A part of String is called substring.
In other words, substring is a subset of another String.
Java String class provides the built-in substring() method that extract a substring from the given
string by using the index values passed as an argument.
In case of substring() method startIndex is inclusive and endIndex is exclusive.
Suppose the string is "computer", then the substring will be com, compu, ter, etc.
You can get substring from the given String object by one of the two methods:
public String substring(int startIndex):
This method returns new String object containing the substring of the given string from
specified startIndex (inclusive). The method throws an IndexOutOfBoundException when the
startIndex is larger than the length of String or less than zero.
public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from
specified startIndex to endIndex.
The method throws an IndexOutOfBoundException when the startIndex is less than zero or
startIndex is greater than endIndex or endIndex is greater than length of String.
In case of String:
startIndex: inclusive
endIndex: exclusive
1. String s="hello";
2. System.out.println(s.substring(0,2)); //returns he as a substring
In the above substring, 0 points the first letter and 2 points the second letter
i.e., e (because end index is exclusive).
Example of Java substring() method
TestSubstring.java
Output:
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin
The above Java programs, demonstrates variants of the substring() method of String class.
The startindex is inclusive and endindex is exclusive.
Using String.split() method:
The split() method of String class can be used to extract a substring from a sentence.
It accepts arguments in the form of a regular expression.
TestSubstring2.java
1. import java.util.*;
2.
3. public class TestSubstring2
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. String text= new String("Hello, My name is Sachin");
9. /* Splits the sentence by the delimeter passed as an argument */
10. String[] sentences = text.split("\\.");
11. System.out.println(Arrays.toString(sentences));
12. }
13. }
Output:
[Hello, My name is Sachin]
In the above program, we have used the split() method. It accepts an argument \\. that checks a
in the sentence and splits the string into another string. It is stored in an array of String objects
sentences
Java String Class Methods
The java.lang.String class provides a lot of built-in methods that are used to manipulate string
in Java.
By the help of these methods, we can perform operations on String objects such as trimming,
concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a String if you submit any
form in window based, web based or mobile application.
Java String toUpperCase() and toLowerCase() method
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Stringoperation1.java
Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
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
Output:
true
true
Java String charAt() Method
The String class charAt() method returns a character at specified index.
Stringoperation4.java
Output:
S
h
Java String length() Method
The String class length() method returns length of the specified String.
Stringoperation5.java
1. public class Stringoperation5
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }
Output:
6
Java String intern() Method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a String equal to this String
object as determined by the equals(Object) method, then the String from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.
Stringoperation6.java
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
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
7. System.out.println(replaceString);
8. }
9. }
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4.
5. System.out.println(sb);
6. }
7. }
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java"); //now original string is changed
5. System.out.println(sb); //prints HJavaello
6. }
7. }
Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
Output:
HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex
to endIndex.
StringBufferExample4.java
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
Output:
olleH
6) StringBuffer capacity() Method
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
StringBufferExample6.java
1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
Output:
16
16
34
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
StringBufferExample7.java
1. class StringBufferExample7{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
Output:
16
16
34
34
70
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public StringBuilder It is used to replace the string from specified startIndex and
replace(int startIndex, int endIndex.
endIndex, String str)
public StringBuilder It is used to delete the string from specified startIndex and
delete(int startIndex, int endIndex.
endIndex)
public void It is used to ensure the capacity at least equal to the given
ensureCapacity(int minimum.
minimumCapacity)
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number
of characters.
public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int It is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.
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
2) String is slow and consumes more memory StringBuffer is fast and consumes
when we concatenate too many strings because less memory when we
every time it creates new instance. concatenate t strings.
5) String class uses String constant pool. StringBuffer uses Heap memory
Difference between StringBuffer and StringBuilder
Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
Output:
hellojava
StringBuilder Example
BuilderTest.java
Output:
hellojava
1. Definition final is the keyword finally is the block in finalize is the method
and access modifier Java Exception in Java which is used
which is used to Handling to execute to perform clean up
apply restrictions on the important code processing just
a class, method or whether the before object is
variable. exception occurs or garbage collected.
not.
3. Functionality (1) Once declared, (1) finally block runs finalize method
final variable the important code performs the
becomes constant even if exception cleaning activities
and cannot be occurs or not. with respect to the
modified. (2) finally block object before its
(2) final method cleans up all the destruction.
cannot be resources used in try
overridden by sub block
class.
(3) final class
cannot be inherited.
4. Execution Final method is Finally block is finalize method is
executed only when executed as soon as executed just before
we call it. the try-catch block is the object is
executed. destroyed.
It's execution is not
dependant on the
exception.
Output:
In the above example, we have declared a variable final. Similarly, we can declare the
methods and classes final using the final keyword.
Java finally Example
In this example where the Java code throws an exception and the catch block handles
that exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.
Output:
Output:
Exception Handling in Java
It is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors
such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.
Exception in Java
Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program.
It is an object which is thrown at runtime.
Keyword Description
Explanation:
Suppose there are 10 statements in a Java program and an exception occurs
at statement 5;
the rest of the code will not be executed,
i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements
will be executed.
Explanation:
The JVM firstly checks whether the exception is handled or not.
If exception is not handled, JVM provides a default exception handler
that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception
occurred).
Causes the program to terminate.
But if the application programmer handles the exception, the normal
flow of the application is maintained, i.e., rest of the code is executed.
Explanation:
As displayed in the above example, the rest of the code is not executed
(in such case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception.
If the exception is not handled, all the code below the exception won't be
executed.
Points to remember
At a time only one exception occurs and at a time only one catch block is
executed.
All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for Exception.
Output:
Arithmetic Exception occurs
rest of the code
Example 2
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example:1
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).
Example:
Case 1: When an exception occurs and is handled by the catch block
In the example where the Java code throws an exception and the catch
block handles the exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.
public class TestFinallyBlock2{
public static void main(String args[]){
try {
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).
In example where the Java program does not throw any exception, and the
finally block is executed after the try block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
Output:
Case 3: When an exception occur but not handled by the catch block
In example the code throws an exception however the catch block cannot
handle it.
Despite this, the finally block is executed after the try block and then the
program terminates abnormally.
throw Instance
i.e.,
throw new exceptionclass("error message");
import java.io.*;
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {
Example 1
Example, kept the code in a try block that will not throw an exception.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class TryCatchExample10 {
public static void main(String[] args) {
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
}
Output:
File saved successfully
Throw and Throws keywords
The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.
A list of differences between throw and throws are given below:
Output:
Output:
Java throw and throws Example
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Output: