Unit 2 Final Notes
Unit 2 Final Notes
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. It is a name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its value can be
changed.
e.g. int a = 15;
a
15
Here, in the above diagram, ‘a’ is the name given to the starting address of the memory where 15
is stored.
Types of Variables
There are three types of variables in Java:
• local variable
• instance variable
• static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable.
It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Example 0-1 types of variables in java
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Types of Data
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. There are 8 types of primitive data types:
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.
Example: Boolean one = false;
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example:
byte a = 10, b = -20 ;
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
Example:
short s = 10000, r = -5000;
int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
int a = 100000, b = -200000;
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
long a = 100000L, b = -200000L;
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0F.
Example:
float f1 = 234.5f;
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example:
double d1 = 12.3 ;
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A' ;
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of
Unicode system.
Unicode System
Unicode is a universal international standard character encoding that is capable of representing
most of the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.
Problem
This caused two problems:
A particular code value corresponds to different letters in the various language standards.
The encodings for languages with large character sets have variable length. Some common
characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System. In unicode,
character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
The default values and size of primitive data-types are listed in the Table 2.1
Table 0.1Default values and size of primitive data-types
Java Constants
Constants have a name like variables and store a certain type of information but unlike variables
they CANNOT change.
Format:
final <constant type> <CONSTANT NAME> = <value>;
Example:
final int SIZE = 100;
Why use constants ?
They make your program easier to read and understand
populationChange = (0.1758 – 0.1257) * currentPopulation;
Vs.
final float BIRTH_RATE = 17.58;
final float MORTALITY_RATE = 0.1257;
int currentPopulation = 1000000;
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;
It can make your program easier to maintain (update with changes).
If the constant is referred to several times throughout the program, changing the value of the
constant once will change it throughout the program.
Example Java Constants
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Table 0.2 Types of Operators
Example 0: Expression
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
Example : Left Shift Operator
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words which acts as
a key to a code. These are predefined words by Java so it cannot be used as a variable or object
name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
• abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide
the implementation of interface. It can have abstract and non-abstract methods.
• boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
• break: Java break keyword is used to break loop or switch statement. It breaks the current
flow of the program at specified condition.
• byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
• case: Java case keyword is used to with the switch statements to mark blocks of text.
• catch: Java catch keyword is used to catch the exceptions generated by try statements. It
must be used after the try block only.
• char: Java char keyword is used to declare a variable that can hold unsigned 16-bit
Unicode characters
• class: Java class keyword is used to declare a class.
• continue: Java continue keyword is used to continue the loop. It continues the current flow
of the program and skips the remaining code at the specified condition.
• default: Java default keyword is used to specify the default block of code in a switch
statement.
• do: Java do keyword is used in control statement to declare a loop. It can iterate a part of
the program several times.
• double: Java double keyword is used to declare a variable that can hold a 64-bit floating-
point numbers.
• else: Java else keyword is used to indicate the alternative branches in an if statement.
• enum: Java enum keyword is used to define a fixed set of constants. Enum constructors
are always private or default.
• extends: Java extends keyword is used to indicate that a class is derived from another class
or interface.
• final: Java final keyword is used to indicate that a variable holds a constant value. It is
applied with a variable. It is used to restrict the user.
• finally: Java finally keyword indicates a block of code in a try-catch structure. This block
is always executed whether exception is handled or not.
• float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
• for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some conditions become true. If the number of
iteration is fixed, it is recommended to use for loop.
• if: Java if keyword tests the condition. It executes the if block if condition is true.
• implements: Java implements keyword is used to implement an interface.
• import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
• instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
• int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
• interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
• long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
• native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
• new: Java new keyword is used to create new objects.
• null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
• package: Java package keyword is used to declare a Java package that includes the classes.
• private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
• protected: Java protected keyword is an access modifier. It can be accessible within
package and outside the package but through inheritance only. It can't be applied on the
class.
• public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
• return: Java return keyword is used to return from a method when its execution is
complete.
• short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
• static: Java static keyword is used to indicate that a variable or method is a class method.
The static keyword in Java is used for memory management mainly.
• strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
• super: Java super keyword is a reference variable that is used to refer parent class object.
It can be used to invoke immediate parent class method.
• switch: The Java switch keyword contains a switch statement that executes code based on
test value. The switch statement tests the equality of a variable against multiple values.
• synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.
• this: Java this keyword can be used to refer the current object in a method or constructor.
• throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exception. It is followed by an instance.
• throws: The Java throws keyword is used to declare an exception. Checked exception can
be propagated with throws.
• transient: Java transient keyword is used in serialization. If you define any data member
as transient, it will not be serialized.
• try: Java try keyword is used to start a block of code that will be tested for exceptions. The
try block must be followed by either catch or finally block.
• void: Java void keyword is used to specify that a method does not have a return value.
• volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.
• while: Java while keyword is used to start a while loop. This loop iterates a part of the
program several times. If the number of iteration is not fixed, it is recommended to use
while loop.
Control Statements
Java conditional statements allow you to make a decision, based upon the result of a condition.
These statements are called Decision Making Statements or Conditional Statements.
Figure : Control Statements
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false. There
are various types of if statement in Java.
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
• Java if Statement
“If statement” in C is used to control the program flow based on some condition, it's used to execute
some statement code block if the expression is evaluated to true. Otherwise, it will get skipped.
This is the simplest way to modify the control flow of the program.
Example : if statement
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Example : Nested If
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in Java.
• for loop
• while loop
• do-while loop
Figure : Loops in Java
Table 0.3 Comparison between Types of Loops
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Example: Infinite For Loop
As you can see in the above output, 5 is not printed on the console. It is because the loop is
continued when it reaches to 5.
Java Continue Statement with Inner Loop
It continues inner loop only if you use the continue statement inside the inner loop.
Example : Java Continue Statement with Inner Loop
Java Continue Statement with Labeled For Loop
We can use continute statement with a label. This feature is introduced since JDK 1.5. So, we can
continue any loop in Java now whether it is outer loop or inner.
Example: Java Continue Statement with Labeled For Loop
Java Comments
The Java comments are the statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code.
Types of Java Comments
There are three types of comments in Java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment
Figure: Types of Comments
(1) Java Single Line Comment
The single line comment is used to comment only one line.
Initializing an Object
Here's the code for the Point class:
public class Point {
publicint x = 0;
publicint y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The constructor in the Point class takes
two integer arguments, as declared by the code (int a, int b). The following statement provides 23
and 94 as values for those arguments:
Point originOne = new Point(23, 94);
Access Levels
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The first data column indicates whether the class itself has access to the member defined by the
access level. As you can see, a class always has access to its own members. The second column
indicates whether classes in the same package as the class (regardless of their parentage) have
access to the member. The third column indicates whether subclasses of the class declared outside
this package have access to the member. The fourth column indicates whether all classes have
access to the member.
Access levels affect you in two ways. First, when you use classes that come from another source,
such as the classes in the Java platform, access levels determine which members of those classes
your own classes can use. Second, when you write a class, you need to decide what access level
every member variable and every method in your class should have.
Let's look at a collection of classes and see how access levels affect visibility. The following
figure shows the four classes in this example and how they are related.
Visibility
Public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
Private Y N N N
class Demo
{
final void add(int x, int y)
{
int sum =x+y;
}
}
class child extends Demo
{
Void add(int a, int b)// error because the method was final in the base class
{
}
}
Class as Final
If the user add final keyword with the class definition then that class can never be inherited. It is
opposite of abstract class. The abstract class has to be extended so instantiate where as a final class
can never be extended.
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
What is Exception in Java
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the
rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.
Hierarchy of Java Exception classes:
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by
two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Keyword Description
Try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
Catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception.
It specifies that there may occur an exception in the method. It is always used with
method signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling where we using a try-catch statement to handle
the exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
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.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur NumberFormatException. Suppose I have
a string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of
the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
Example 2
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Now, 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.
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
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.
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
catch(Exception e)
{
System.out.println("Can't divided by zero");
}
}
}
Output:
Can't divided by zero
Example 6
Let's see an example to resolve the exception in a catch block.
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
public class TryCatchExample7 {
public static void main(String[] args) {
try
{
int data1=50/0; //may throw exception
}
catch(Exception e)
{
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
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).
public class TryCatchExample8 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 9
Let's see an example to handle another unchecked exception.
public class TryCatchExample9 {
public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class TryCatchExample10 {
public static void main(String[] args) {
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
}
Output:
File saved successfully
Internal working of java try-catch block
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
Example 3
In this example, try block contains two exceptions. But at a time only one exception occurs and its
corresponding catch block is invoked.
public class MultipleCatchBlock3 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
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:
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.
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
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:
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).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Rule: If you are calling a method that declares an exception, you must either caught or declare the
exception.
There are two cases:
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs during
the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
Case2: You declare the exception
A)In case you declare the exception, if exception does not occur, the code will be executed fine.
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
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:device operation performed
normal flow...
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
import java.io.*;
class Parent{
void msg()throws ArithmeticException{System.out.println("parent");}
}
class TestExceptionChild2 extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild2();
try{
p.msg();
}catch(Exception e){}
}
}
Output:Compile Time Error