UNIT - 4-JAVA-2-2
UNIT - 4-JAVA-2-2
com 1
www.Jntufastupdates.com 2
f
www.Jntufastupdates.com 3
www.Jntufastupdates.com 4
www.Jntufastupdates.com 5
www.Jntufastupdates.com 6
www.Jntufastupdates.com 7
www.Jntufastupdates.com 8
www.Jntufastupdates.com 9
www.Jntufastupdates.com 10
www.Jntufastupdates.com 11
www.Jntufastupdates.com 12
www.Jntufastupdates.com 13
www.Jntufastupdates.com 14
www.Jntufastupdates.com 15
www.Jntufastupdates.com 16
www.Jntufastupdates.com 17
www.Jntufastupdates.com 18
www.Jntufastupdates.com 19
www.Jntufastupdates.com 20
www.Jntufastupdates.com 21
www.Jntufastupdates.com 22
www.Jntufastupdates.com 23
www.Jntufastupdates.com 24
www.Jntufastupdates.com 25
UNIT-4
WWW.JNTUKNOTES.COM
I. Packages and Java Library:
1. Introduction
A Java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form,
i. built-in package and
ii. user-defined package.
There are many built-in packages such as java.lang, java.awt, java.javax, java.swing,
java.util, etc.
Here, we will have the detailed learning of creating and using user-defined packages.
2. Defining Package
A package comprises a group of similar type of classes, interfaces, and sub-packages. It
is defined with the keyword package followed by the name of the package and a
semicolon, as illustrated in the following figure.
WWW.JNTUKNOTES.COM
java.mypackage.xpack.ypack.MyClass;
Here different levels in package are seperated by a period (.)
import java.packageP1.packageP2.package3.ClassName
Here
java – Name of the package
packageP1 – Sub Package of Java
packageP2 – Sub Package of packageP1
packageP3 – Sub Package of packageP2
ClassName - Name of the Class in PackageP3.
WWW.JNTUKNOTES.COM
User-defined Packages and Classes
One of the important features of the Java programming language is that it allows a
programmer to build his/her own packages and classes and make use of them whenever
the need arises for the use of standard Java library packages and classes.
A programmer can save his/her own packages and classes in a directory, and from there,
it can be imported to the ones required into his/her application program by using import
keyword.
For this, the following points should be taken care of while constructing a folder for a
user's own package.
1. The folder name should be same as the name of the package desired to be created,
2. Create the desired class required to imported. Save it in the folder.
3. Compile the folder and class. However, do not run it because the class will not have the
main. The application class to which it is imported will have the main method.
4 The application class should be saved outside this folder in any directory of your choice.
Example: The following class is constructed and saved in "userpackage" folder, which is
saved in MyProject folder in Local Disk (C)
package userpackage;
WWW.JNTUKNOTES.COM
Program2: ArayMain.java in MyProject folder in Local Disk (C)
import userpackage.*;
Execution Process:
WWW.JNTUKNOTES.COM
4. Path and Class Path
The PATH is an environmental variable used by the operating system to find the
executive binary files
Javac, which compiles the source code into bytecode, and
java, which interprets the bytecode through for execution of the program
such commands Path tells the system where to locate the JDK files that contain these
commands.
If the programmer is using classes or packages other than the Java standard their location
is specified through classpath.
The directory tree after the Java Development Kit (JDK) has been installed in Windows
OS would look as illustrated in the following Diagram. The path is indicated by arrows
The system has to reach the location of jdk1.x.0_ yy\bin, which contains javac and java
commands The path may be set in two ways
The path can be set for individual programs. Therefore, the path to JDK files installed in our
computer is specified as
C:\Program Files\Javaljdk1.8.0_65\bin
WWW.JNTUKNOTES.COM
set path=%path%;C:\Program Files\Javaljdk1.8.0_65\bin
The important thing about setting path is that there will be no blank in assignment.
5. Access Control
In Java, There are three access specifiers are permitted:
• public
• protected
• private
The coding with access specifiers for variables is illustrated as
WWW.JNTUKNOTES.COM
6. Packages in Java SE
Java has been evolving since its inception as Java 1. The latest version of Java is Java SE 8
(The Java Standard Edition 8). Originally all were supposed to be part of Java SE 7; however, it was
taking more time, and Java SE 7 was released with some changes/ modifications and the remaining
enhancements of Java were released in Java 8. It is worthwhile to at the additions and modifications
in Java 7 and Java 8.
i. Object class is the super class of all other classes in Java. It is the root of the class
hierarchy
ii. Classes encapsulate the primitive data types in Java.
iii. Classes access system resources and other low-level entities.
iv. The class Math provides standard mathematical functions, for example, sine,
cosine, square root, etc
v. The class Throwable is the super class of all error and exception classes in Java. It
deals with the object that can be thrown by the throw statement. Subclasses of
Throwable represent errors and exceptions
vi. The class Thread controls each thread in a multithreaded program.
vii. Classes String and StringBuffer provide commonly used operations on character
strings.
WWW.JNTUKNOTES.COM
It is all very necessary for a programmer to know the different classes available
Table 10.4 gives a brief description of the classes available in this package.
Class name Brief description
Boolean Wrapper class for Boolean values 'true' and 'false'
Byte Wrapper class to provide reference to type byte
Character Wrapper class to provide reference to type char and it supports two byte
Unicode characters
Class Subclass of Object, used for referring classes as objects
Double Wrapper class to provide reference to type double
Enum Defines methods that support enumeration
Float Wrapper class to provide reference to type float
Integer Wrapper class to provide reference to type int
Long Wrapper class to provide reference to type long
Math Contains several mathematical methods
Abstract super class for the Wrapper classes such as Byte, Short, Integer,
Number
Float, and Double
Object Super class to all other classes in Java
Package For managing packages
String Subclass of Object; it defines methods for handling strings.
WWW.JNTUKNOTES.COM
8. Class Object
The class Object is one of the important classes of Java because it is the super class to all
other classes. The class has one constructor and defines 11 methods that are available to all
the objects. The methods of class are described in following Table.
WWW.JNTUKNOTES.COM
9. Enumeration
An enum is a special "class" that represents a group of constants (unchangeable
variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate the
constants with a comma. Note that they should be in uppercase letters:
Example:
class Enum
{
enum Level { LOW, MEDIUM, HIGH}
public static void main(String args[])
{
System.out.println("First Value = " + Level.LOW);
}
}
Output:
C:\ >javac Enum.java
WWW.JNTUKNOTES.COM
10. class Math
The Math class is an important class of java.lang package. It defines methods for
evaluating several mathematical functions such as trigonometry functions (sine, cosines,
etc.), exponential functions, rounding off functions, and other miscellaneous
mathematical functions. The class is defined as a final class.
Example: MathDemo.java
class MathDemo
{
public static void main(String args[])
{
System.out.println("Value of E = "+ Math.E);
System.out.println("Value of PI = "+ Math.PI);
System.out.println("Squar Root of 25 = "+ Math.sqrt(25));
System.out.println("2 to the power of 4 = "+ Math.pow(2,4));
}
}
Output:
C:\ >javac MathDemo.java
Value of E = 2.718281828459045
Value of PI = 3.141592653589793
WWW.JNTUKNOTES.COM
11. Wrapper Classes
Wrapper class wraps (i.e., encloses) a primitive data type and provides its object
representation.
In Java, a simple data type can also be converted into an object using Wrapper classes.
Many data structures in Java are designed to operate on objects.
Wrapper classes that encapsulate a primitive data type within an object.
The eight primitive data types, namely
i. boolean,
ii. byte,
iii. short,
iv. int,
v. long,
vi. float,
vii. double, and
viii. char,
These 8 primitive data types are not objects of classes; hence, they cannot be passed on
by references and they are passed on by value only.
Therefore, in order to provide object representation, eight Wrapper classes are
defined in java.lang package which is imported by default in all the Java programs.
The eight Wrapper classes are
i. Boolean
ii. Byte,
iii. Short,
iv. Integer,
v. Long,
vi. Float,
vii. Double
viii. Char
Methods of Wrapper Classes :
i. equals()
ii. isInfinite()
iii. isNaN()
iv. byteValue()
v. compareTo(type Object)
vi. doubleValue()
vii. floatValue()
viii. hashCode()
ix. intValue()
x. longValue()
xi. ShortValue()
xii. toHexString(type number)
xiii. valueOf(type number)
xiv. valueOf(String str)
xv. toString(type number)
WWW.JNTUKNOTES.COM
Example: WrapperClasses.java
class WrapperClasses
{
public static void main(String args[])
{
// for int values
int i = 10;
Integer in = i;
System.out.println("Value of in = "+ in);
}
}
Output:
C:\>javac WrapperClasses.java
WWW.JNTUKNOTES.COM
12. Auto-boxing and Auto- unboxing
Auto-boxing
Auto-boxing involves automatic conversion of the primitive data types into its
corresponding wrapper types so that the value may be represented by reference as the
objects of other classes.
This includes the conversion of
o int to Integer,
o double to Double,
o float to Float,
o boolean to Boolean, etc.,
Auto-unboxing
Auto - unboxing is the reverse process in which the wrapping class objects are
converted into the corresponding primitive data types.
This includes conversion of
o Integer to int,
o Long to long,
o Double to double, etc.
Example: AutoBoxing.java
class AutoBoxing
{
public static void main(String args[])
{
// Auto Boxing
int i = 10;
Integer in = new Integer(i); //Auto Boxing: Primitive to Wrapper
System.out.println("Value of Wrapper variable in = "+ in);
//Auto Unboxing
Integer x = 20;
int y = x.intValue(); //Auto Unboxing : Wrapper to Primitive
System.out.println("Value of primitive variable y = "+ y);
}
}
WWW.JNTUKNOTES.COM
Output:
C:\>javac AutoBoxing.java
C:\>java AutoBoxing
Value of Wrapper variable in = 10
Value of primitive variable y = 20
WWW.JNTUKNOTES.COM
Scanner Class
Java Scanner class is a text scanner that breaks the input into tokens using delimiter, which is
whitespace by default. Delimiter is a character that identifies the beginning or end of
character string and it is not a part of the character string.
The received string can then be converted into values of different types using the various
next() methods. The application of this class is not thread safe. Java Scanner class extends
Object class and implements Iterator and Closeable interfaces. For instance, the following
code allows the user to input into the program an integer number through the keyboard.
Sample Code:
Example : UserInput.java
import java.util.Scanner;
public class UserInput
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System. in);
int n;
int m;
System.out. print( "Enter the value of n : ");
n=scaninput.nextInt();
System.out. print( "Enter the value of m : ");
m=scaninput.nextInt();
}
}
Output
C:\>javac UserInput.java
C:\>java Arithmetic
Enter the value of n : 10
Enter the value of m : 3
Sum of two numbers is =13
WWW.JNTUKNOTES.COM
Radix in java.util package
Radix is another name of base of the number system being referred to.
Radix values specifies the base value of the numbers ie 2 for Binary Numbers, 8 for Octal
Numbers, 10 for Decimal Numbers (The default radix number is 10) and 16 for
HexaDecimal Numbers
radix() method prints the current radix value
useRadix() method used to change the radix value
Example : TestRadix.java
import java.util.Scanner;
public class TestRadix
{
public static void main(String[] args)
{
int n;
}
}
WWW.JNTUKNOTES.COM
Output:
E:\>javac TestRadix.java
E:\ >java TestRadix
For Decimal numbers- radix = 10
Enter an integer number: 56
The number n = 56
WWW.JNTUKNOTES.COM
Example : FormatterDemo.java
WWW.JNTUKNOTES.COM
Output:
C:\>javac FormatterDemo.java
C:\>java FormatterDemo
x = 165, f= 432.141602, d= 5654.875430, ch= a and str= Hello World
Upper case of ch = A and str = HELLO WORLD
Example: Random.java
import java.util.Random;
public class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
Output:
C:\ >javac RandomNumbers.java
WWW.JNTUKNOTES.COM
16. Time Package
This package provides support for date and time-related features for program developers.
It comprises classes that represent date/time concepts including instants, duration, date,
time, time zones, and periods.
The date and time framework in Java prior to Java SE 8 consisted of classes such as
o java.util.Date,
o java.util.Calendar, and
o java.util.SimpleDateFormatter
which posed problems to programmers because of the following reasons:
These classes are
i. not thread safe
ii. present a poor show.
iii. poor design.
iv. it was difficult to work with different calendar systems followed in different
parts of the world.
The result is the development of an entirely new package java.time that has classes
that are thread safe; these classes have robust design and they can be adapted to work
with different calendar systems.
Example: TimePrg.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Period;
// creating an object
LocalDate date = LocalDate.now();
System.out.println("The date today is : "+date);
WWW.JNTUKNOTES.COM
//1 year, 3 months and 10 days
Period p = Period.of(1,3,10);
Output:
Java Instant class is used to represent the specific moment on the time line. It inherits
the Object class and implements the Comparable interface.
WWW.JNTUKNOTES.COM
Example: TimeInstantDemo.java
import java.time.Instant;
public class TimeInstantDemo
{
public static void main(String[] args)
{
Instant now = Instant.now();
System.out.println("Now Time = "+ now);
}
}
Output:
Example2: UntilDemo.java
import java.time.*;
import java.time.temporal.*;
WWW.JNTUKNOTES.COM
//Calculating time difference (in minutes)thorugh until()
method
td = time1.until(time, ChronoUnit.MINUTES);
System.out.println("Time difference = "+ td + "
Minutes");
Output:
C:\>javac UntilDemo.java
C:\>java UntilDemo
Time difference = 2 Hours
Time difference = 169 Minutes
Time difference = 10188 Seconds
The class provides the following three ways to achieve the desired results.
1. By using the predefined constants in the language that represent a particular format of
formatting date/ time objects.
2. By using patterns defined by the programmer.
3. By using localized format.
Example: DateTimeFormatter.java
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.DateTimeException;
import java.time.LocalDateTime;
WWW.JNTUKNOTES.COM
//defining an instance
LocalDateTime datetime = LocalDateTime.now();
System.out.println("Default format of LocalDateTime: "+ datetime);
System.out.println("\nIn 150_LOCAL_DATE_TIME Format: " +
datetime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
Output:
C:\>javac DateTimeFormatDemo.java
C:\>java DateTimeFormatDemo
Default format of LocalDateTime: 2021-06-12T19:24:32.807557700
The java time temporal defines an interface by name TemporalAdjuster that defines methods
that take a temporal value and return an adjusted temporal value according to a user's
specifications.
The package also defines a class TemporalAdjusters, which contains predefined used by a
programmer. Some examples of adjusters are as follows.
i. firstDayOfMonth()
ii. lastDayOfMonth()
iii. firstDayOfyear()
iv. lastDayOfYear
v. firstDayOfWeek ()
WWW.JNTUKNOTES.COM
vi. lastbayOfWeek()
vii. firstInMonth (DayOfWeek. Monday)
viii. lastInMonth (DayOfWeek. FRIDAY)
All these methods are static methods and may be used with static import.
Static import is used to access any static member of a class directly without referring its class
name. There are two general forms of declaration of static import statements.
The first form of static import statement involves importing only a single member of a class
as shown:
As for instance,
The second form of static import statement involves importing all the static members
of a class as
It is different from import statement that allows the programmer to access classes of a
package without providing package name or qualification. It is to be noted that import
statement makes the classes and interfaces accessible, whereas the static import provides
accessibility to static members of the class only.
Example: TemporalAdjusterDemo.java
import java.time.*;
import java.time.temporal.TemporalAdjusters;
WWW.JNTUKNOTES.COM
System.out.println("The last day of November = "+
date1.with(TemporalAdjusters.lastDayOfMonth()));
}
}
Output
C:\>javac TemporalAdjusterDemo.java
C:\>java TemporalAdjusterDemo
The day of week on 20th Nov 2015 =FRIDAY
The first day of November = 2015-11-01
The last day of November = 2015-11-30
WWW.JNTUKNOTES.COM
II. Exception Handling:
1. Introduction
In Java, an exception is an object of a relevant exception class. When an error
occurs in a method, it throws out an exception object that contains the information
about where the error occurred and the type of error. The error (exception) object is
passed on to the runtime system, which searches for the appropriate code that can
handle the exception.
The event handling code is called exception handler.
Exception handling is a mechanism that is used to handle runtime errors such as
classNotFound and IO. This ensures that the normal flow of application is not
disrupted and program execution proceeds smoothly.
The exception handling code handles only the type of exception that is specified for
it to handle. The appropriate code is the one whose specified type matches the type
of exception thrown by the method.
If the runtime system finds such a handler, it passes on the exception object to the
handler. If an appropriate handler is not found, the program terminates.
The method that creates an exception may itself provide a code to deal with it.
The try and catch blocks are used to deal with exceptions.
The code that is likely to create an exception is kept in the try block, which may
include statements that may create or throw exceptions.
The exception object has a data member that keeps information about the type of
exception and it becomes an argument for another block of code that is meant to deal
with the exception.
There may be more than one catch blocks.
• There are basically two models of exception handling.
1. Termination Model
• According to termination model, when the method encounters an exception, further
processing in that method is terminated and control is transferred from the point where
an exception occurs to the point where its nearest matching exception handler (i.e., the
catch block) is located.
• This model is analogous to the real-life situation when the gas in the cylinder gets over
while cooking.
• Under the termination model, the cooking process will stop, whereas in resumption
model, you would change the cylinder with a new one and continue with the cooking
process.
2. Resumption model
• Thus, the alternative approach is based on the resumption model wherein the
exception handler tries to rectify the exception situation and resume the program.
• Resumption model was mostly used in earlier languages including PL/I, Mesa, and
BETA.
• The implementation of resumption model in contemporary languages such as C++ and
WWW.JNTUKNOTES.COM
Java is rarely found as the effort to implement this model is quite high.
• This is because the program code becomes quite cumbersome and difficult to
understand, and further, it is more error prone.
• However, there are situations where the resumption model is quite useful.
• Examples
OutOfMemoryError occurs when the JVM runs out of memory and
StackOverflowError occurs when the stack overflows.
• Exception class represents exceptions that are mainly caused by the application itself.
• It is not possible to recover from an error using try–catch blocks.
• The only option available is to terminate the execution of the program and recover
from exceptions using either the try–catch block or throwing an exception.
• The exception class has several subclasses that deal with the exceptions that are caught
and dealt with by the user’s program.
• The Error class includes such errors over which a programmer has less control.
WWW.JNTUKNOTES.COM
• A programmer cannot do anything about these errors except to get the error message and
check the program code.
• A programmer can have control over the exceptions (errors) defined by several
subclasses of class Exception.
The subclasses of Exception class are broadly subdivided into two categories.
Unchecked exceptions These are subclasses of class RuntimeException, derived from
Exception class. For these exceptions, the compiler does not check whether the method that
throws these exceptions has provided any exception handler code or not.
Checked exceptions These are direct subclasses of the Exception class and are not subclasses
of the class RuntimeException. These are called so because the compiler ensures (checks)
that the methods that throw checked exceptions deal with them.
WWW.JNTUKNOTES.COM
Example: TryCatchDemo.java
class TryCatchDemo
{
public static void main(String args[])
{
int i=6,j=0,k;
try {
System.out.println("Entered try block");
k=i/j;
System.out.println("Exiting try block");
}
catch (ArithmeticException e)
{
System.out.println("e = " + e);
}
System.out.println("End of the Program ");
}
}
Output:
C:\ >javac TryCatchDemo.java
WWW.JNTUKNOTES.COM
4. try catch and finally Blocks
try {} Block
• The program code that is most likely to create exceptions is kept in the try block,
which is followed by the catch block to handle the exception.
• In normal execution, the statements are executed and if there are no exceptions, the
program flow goes to the code line after the catch blocks.
• However, if there is an exception, an exception object is thrown from the try block.
• Its data members keep the information about the type of exception thrown.
• The program flow comes out of the try block and searches for an appropriate catch
block with the same type as its argument.
catch {} Block
• A catch block is meant to catch the exception if the type of its argument matches with
the type of exception thrown.
• If the type of exception does not match the type of the first catch block, the program
flow checks the other catch blocks one by one.
• If the type of a catch block matches, its statements are executed.
• If none matches, the program flow records the type of exception, executes the finally
block, and terminates the program.
WWW.JNTUKNOTES.COM
Example: TryCatchDemo2.java
class TryCatchDemo2
{
public static void main(String args[])
{
int i=6,j=0,k;
try {
System.out.println("Entered try block");
k=i/j;
System.out.println("Exiting try block");
}
catch (ArithmeticException e)
{
System.out.println("e = " + e);
}
Output:
WWW.JNTUKNOTES.COM
finally {} Block
• This is the block of statements that is always executed even when there is an
exceptional condition, which may or may not have been caught or dealt with.
• Thus, finally block can be used as a tool for the clean up operations and for recovering
the memory resources.
• For this, the resources should be closed in the finally block.
• This will also guard against situations when the closing operations are bypassed by
statements such as continue, break, or return.
•
Finalize() in Exception Handling
• finalize() method releases system resources before the garbage collector runs for a
specific object.
• JVM allows finalize() to be invoked only once per object
• The syntax for using finalize() method is given as follows:
@Override //
protected void finalize() throws Throwable
{
try{
……………….
} catch(Throwable t)
{
throw t;
}finally{
super.finalize();
}
}
• Following points need to be taken into consideration when using finalize() method:
1. super.finalize() method is always called in finalize() method.
2. Time critical application logic should not be placed in finalize() method.
Example: MultiCatchExample.java
class MultiCatchExample
{
public static void main(String args[])
{
try {
int a=0, b=56, c;
WWW.JNTUKNOTES.COM
int aray[] = {4,5,6,7};
System.out.println("The Array elements are : ");
Output:
C:\>java MultiCatchExample
The Array elements are :
4
5
6
7
6. Class Throwable
• The class is declared as
public class Throwable extends Object
implements serializable
The class Throwable is super class to all the error and exception classes.
• The program code can throw only objects of this class or objects of its subclasses.
• Only the object of Throwable class or its subclasses can be the arguments of catch
clause.
• It would be a bad programming practice to throw Throwable or make Throwable as
argument of catch blocks because it will hide desirable information.
WWW.JNTUKNOTES.COM
Methods in Throwable Class:
Throwable getCause()
String getMessage ()
String getLocalizedMessage()
StackTraceElement[] getStackTrace()
void printStackTrace()
void setStackTrace(
StackTraceElement[] stackTrace)
String toString()
WWW.JNTUKNOTES.COM
Example: TryCatchDemo3.java
} finally{
System.out.println("It is finally block");
System.out.println("The class is : " + ct.getClass());
}
WWW.JNTUKNOTES.COM
7. Unchecked Exceptions
The unchecked exception classes are subclasses of class
RuntimeException, which is further a subclass of class Exception.
The runtime exceptions are not checked by the compiler.
These exceptions form a subgroup of classes that are subclasses of class
Exception.
It is not checked by the compiler whether the programmer has handled them or
not.
Example: UnCheckedDemo.java
class UnCheckedDemo
{
public static void main(String args[])
{
int a =12,b = 0, c = 14;
int sum, d;
sum = a+b+c;
System.out.println("Sum = " +sum);
try {
System.out.println("Entered try block");
d=a/b;
System.out.println("d = " + d);
System.out.println("Exiting try block");
}
catch (ArithmeticException e)
{
System.out.println("Do not divide by Zero, Exception =" + e);
WWW.JNTUKNOTES.COM
}
System.out.println("End of the Program ");
}
}
Output:
C:\>javac UnCheckedDemo.java
C:\>java UnCheckedDemo
Sum = 26
Entered try block
Do not divide by Zero, Exception =java.lang.ArithmeticException: /
by zero
8. Checked Exceptions
Checked exceptions are direct subclasses of the Exception class and are not subclasses of
the class RuntimeException. These are called so because the compiler ensures (checks)
that the methods that throw checked exceptions deal with them
WWW.JNTUKNOTES.COM
Example: MyThread.java
class MyThread
{
public static void main(String args[])
{
MyThread obj = new MyThread();
obj.method2();
System.out.println("End of the Program ");
}
t2.sleep(200);
System.out.println("Square root of 64 = "
+Math.sqrt(64));
t1.sleep(1000);
t2.notify();
Output:
C:\ >javac MyThread.java
WWW.JNTUKNOTES.COM
9. try-with-resources
Generally, the resources such as file, data bases, or Internet connections that are
opened in try block are closed in finally block, which is always executed.
This makes a sure-shot method for recovery of sources and memory.
It is seen that programmers who otherwise are adept at opening sources such as
data bases and files often forget to close these sources when their relevance is
over.
These heavyweight sources keep lurking in JVM, and thus, overloading JVM and
creating problems in memory allocation.
In order to redress the problem, Java 7 has added AutoCloseable.
Example: AutoCloseExample.java
Output:
C:\>javac AutoCloseExample.java
C:\>java AutoCloseExample
Entered in Try Block
The SourceX is closed
Exit from Try Block
End of the Program
WWW.JNTUKNOTES.COM
10. Catching Subclass Exception
If the super class method does not declare any exception, then subclass overridden method
cannot declare (or throws) checked exceptions but it can declare (or throws) unchecked
exceptions. This is illustrated in the following Programs.
import java.io.*;
class A
{
void display()
{
System.out.println("Super class display method");
}
}
Output:
C:\>javac SubClass.java
SubClass.java:13: error: display() in SubClass cannot override
display() in A
void display() throws IOException
^
overridden method does not throw IOException
1 error
WWW.JNTUKNOTES.COM
Example2 : SubClass.java - Sub Class can throws Unchecked Exception
import java.io.*;
class A
{
void display()
{
System.out.println("Super class display method");
}
}
Output:
C:\>javac SubClass2.java
C:\>java SubClass2
Super class display method
Sub class display method
WWW.JNTUKNOTES.COM
11. Custom Exceptions
It is also called as user defined exception.
A programmer may create his/her own exception class by extending the
exception class and can customize the exception according to his/her needs.
Using Java custom exception, the programmer can write their own exceptions and
messages.
Example: ExceptionEx.java
class ExceptionEx
{
public static void main(String args[])
{
byte a = 4, b = 9;
try
{
if(a/b== 0)
throw new UserException("It is integer division.");
}catch (UserException Ue)
{
System.out.println("The exception has been caught.");
System.out.println(Ue.getMessage());
}
}
}
Output:
C:\>javac ExceptionEx.java
C:\>java ExceptionEx
The exception has been caught.
It is integer division.
WWW.JNTUKNOTES.COM
12. Nested try and catch Blocks
In nested try–catch blocks, one try–catch block can be placed within another try’s body.
Nested try block is used in cases where a part of block may cause one error and the entire
block may cause another error.
In such cases, exception handlers are nested.
If a try block does not have a catch handler for a particular exception, the next try
block’s catch handlers are inspected for a match.
If no catch block matches, then the Java runtime system handles the exception.
Example: NestedTry.java
class NestedTry
{
public static void main (String args[])
{
int [] array = {6, 7};
//outer try block
try {
System.out.println("Entered outer try block.");
// inner try block
try {
System.out.println("Entered inner try block.");
for (int i = 0; i<= 2; i++)
System.out.println("Array Element["+i+"]= " + array[i]);
System.out.println ("Exiting try block.");
}
WWW.JNTUKNOTES.COM
// inner catch block
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException caught");
System.out.println("Exiting inner catch block.");
}
int n = 5, j=2 ;
for (j =2; j>=0; j--)
System.out.println ("n/j= " + n/j);
}
// outer catch block
catch (ArithmeticException E)
{
System.out.println ("Arithmetic Exception caught");
}
}
}
Output:
C:\>javac NestedTry.java
C:\>java NestedTry
Entered outer try block.
Entered inner try block.
Array Element[0]= 6
Array Element[1]= 7
ArrayIndexOutOfBounds Exception caught
Exiting inner catch block.
n/j= 2
n/j= 5
Arithmetic Exception caught
WWW.JNTUKNOTES.COM
13. Rethrowing Exception
An exception may be thrown and caught and also partly dealt within a catch
block, and then, rethrown.
In many cases, the exception has to be fully dealt within another catch block,
and throw the same exception again or throw another exception from within
the catch block.
When an exception is rethrown and handled by the catch block,
- the compiler verifies that the type of re-thrown exception is meeting
the conditions that the try block is able to throw
- and there are no other preceding catch blocks that can handle it.
Example: Rethrow.java
class Rethrow
{
public static void main (String Str[])
{
int[] array = {6, 7};
try {
System.out.println ("Entered inner try block.");
for (int i = 0; i<= 2; i++)
System.out.println ("Array Element["+i+"]= " + array[i]);
System.out.println ("Exiting try block.");
}catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("ArrayIndexOutOfBounds Exception caught");
System.out.println ("Throwing e and exiting inner catch block.");
throw e;
}
}
}
Output:
C:\ >javac Rethrow.java
WWW.JNTUKNOTES.COM
14. Throws Clause
The throws clause specifies that the method can throw an exception. throws is a 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.
WWW.JNTUKNOTES.COM
Example: Computation.java
Output:
C:\ >javac Computation.java
WWW.JNTUKNOTES.COM