Object Oriented Concepts Using Java Unit 4
Object Oriented Concepts Using Java Unit 4
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
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
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 provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
JavaExceptionExample.java
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to
java.lang package.
Recoverable/
Exception can be recovered by using the try-
Irrecoverabl
catch block. An error cannot be recovered.
e
It can be classified into two categories i.e. All errors in Java are
Type
checked and unchecked. unchecked.
It belongs to java.lang.Error
Package It belongs to java.lang.Exception package.
package.
Known or Only checked exceptions are known to the Errors will not be known to
unknown compiler. the compiler.
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.
1. try{
3. }catch(Exception_class_Name ref){}
1. try{
3. }finally{}
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.
Advertisement
The catch block must be used after the try block only. You can use multiple catch block with a single
try block.
Example:
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
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.
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
1. class TestFinallyBlock {
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){
8. System.out.println(e);
9. }
10. finally {
12. }
14. }
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
checking the code before it being used.
3. }
o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advertisement
Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
5. }
7. m();
8. }
9. void p(){
10. try{
11. n();
13. }
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
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.
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
Java throws
Java throw keyword is
keyword is used in the
used throw method
an signature to
exception declare an
1. Definition explicitly in exception
the code, which might
inside the be thrown by
function or the function
the block of while the
code. execution of
the code.
throw is throws is
used within used with the
4. Declaration
the method
method. signature.
We can
declare
We are
multiple
allowed to
exceptions
throw only
using throws
one
keyword that
Internal exception at
5. can be
implementation a time i.e.
thrown by the
we cannot
method. For
throw
example,
multiple
main() throws
exceptions.
IOException,
SQLException.
Array and String: Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects
in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in
Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Disadvantages
o 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.
• Multidimensional Array
3. dataType arr[];
1. arrayRefVar=new datatype[size];
3. class Testarray{
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
13. System.out.println(a[i]);
14. }}
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
2. //to method.
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
11. }}
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'};
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(), intern(), substring() etc.
No. Method Description
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.
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
Mutable Immutable
It supports get() and set() methods to It only supports get() method to pass
dela with the object. the value of the object.
String in Java is a very special class, as it is used almost in every Java program. That's why it is
Immutable to enhance performance and security. Let's understand it in detail:
In Java, strings use the concept of literals. Suppose we have an object having many reference
variables. In such a scenario, if we will change the value of a reference variable, it will affect the
entire object and all of its values.
Apart from the above reasons, the following reasons are also responsible for making the String
immutable:
String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
The append() method concatenates the given argument with this String.
StringBufferExample.java
1. class StringBufferExample{
6. }
7. }
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
1. class StringBufferExample2{
5. System.out.println(sb);//prints HJavaello
6. }
7. }