OOPTJ Unit4 Packages, Exception Handling
OOPTJ Unit4 Packages, Exception Handling
Packages
Introduction
In the packages, classes are unique compared with other classes in the other
packages. Hence resolves the name space collision.
Packages provide a way to hide classes thus prevent classes from accessing by
other programs.
A package that is not part of any other package can have a simple name. Example:
java, and javax
All the java programs usually refer one or more packages in the source code.
We can use the packages in the program using the keyword ‘import’.
If a program need several classes of a package, then it is better to import the entire
package.
This can be done as follow: import java.util.*;
Importing class in programs
Packages are organized in hierarchical structure that means a package can contain
another package, which in turn contains several classes for performing different
tasks.
There are two ways to import the classes of the packages.
1. fully qualified class name- this is done by specifying package name
containing the class and appending the class to it with dot (.) operator.
Example: java.util.StringTokenizer(); Here, "java.util" is the package
and "StringTokenizer()" is the class in that package. This is used when
we want to refer to only one class in a package.
2. import statement –this is used when we want to use a class or many
classes in many places in our program. Example: (1) import java.util.*;
Example : import java.util.StringTokenizer;
Example program : Using the fully qualified name
RandomTest.java
class RandomTest
{
public static void main(String
arg[])
{
java.util.Random rn=new java.util.Random();
int n=rn.nextInt(50);
System.out.println("Random number is:"+n);
}
}
Example Program : Using import statement
RandomTest.java
import java.util.Random;
class RandomTest
{
public static void main(String arg[])
{
Random rn=new
Random();
int n=rn.nextInt(50);
System.out.println("Random number is:"+n);
}
}
m.add(12,13);
m.sub(23,4);
}
}
Adding a class to a Package
It is simple to add a class to already existing package. Consider the following
Package:
A.java
package p1;
public class A
{ // body of the class
}
Access Control
Note: Nested interfaces and classes can have all access modifiers.
Object Class
The Object class is one of the important classes of java because it is the super
class of all classes.
Enumeration
The enumeration facility is added with Java 5.
In other programming languages such as C and C++, we have been using enumeration.
In C and C++ enumeration is just a named constant. The Enumeration in java is
different from C and C++. In Java, we can also add variables, methods and
constructors to it.
In the java ‘enum’ keyword is used which has the status like class, but with limited
facilities.
Like class, enum type also has instance, constructor, methods, and inner classes.
The instance is not done with new operator.
The instance are declared like primitive data types.
Declaration of enum in java
enum week
{
SUNDAY,MONDAY;
}
week w=week.SUNDAY;
//here w is the instance of the enum
Enum type encapsulates fixed set of constants, any other constant cannot be added
later.
The enum can be declared inside or out side the class.
The following pointes must be noted for declaration:
The new operator will not be used for declaration
The enum type reference is required whenever the member is declared as in the
2nd line.
The values that variable w may have is one of the constants declared in the
declaration. It cannot have any value other than the ones in the declaration.
Members of enum
By using ordinal() method, each enum constant index can be found, just like
array index which starts with 0.
valueOf() method returns the enum constant of the specified string value, if
exists.
Example program with constants and methods
EnumTest.java
enum Color
{
RED,GREEN,BLUE,YELLOW,VIOLET;
}
class EnumTest
{
public static void main(String arg[])
{
for(Color c:Color.values())
{
System.out.println(c+"is at index:"+c.ordinal()); }
System.out.println("The value of yellow is :"+Color.valueOf("YELLOW"));
}
}
output
C:\Users\JP>javac TestEnum.java
C:\Users\\JP>java TestEnum
RED is at index:0
GREEN is at index:1
BLUE is at index:2
YELLOW is at index:3
VIOLET is at index:4
The value of yellow is :YELLOW
General enum declaration
The general declaration of enum begin with access modifier followed by enum
keyword and followed by name of the enum.
The enum constant declaration contains a constant and its argument in the
parenthesis. EX: RITA(10)
class Math
Write a java program to calculate the power of the given number raised to a
number.
Write a java program to determine the greater number of three numbers. (a,b,c)
class Test4
{
public static void main(String arg[]) {
System.out.println("The area of circle with radius 5 is :"+Math.PI*5*5);
System.out.println("The power(8,3) is :"+Math.pow(8,3));
System.out.println("The greater of 17,2,21 is :"+Math.max(Math.max(17,2),21));
}
}
class Test4
{
public static void main(String arg[])
{
System.out.println("Binry representation of 4 is:"+Integer.toBinaryString(4));
System.out.println("Hex string of 27 is :"+Integer.toHexString(27));
System.out.println("Octal string of 9 is :"+Integer.toOctalString(9));
}
}
C:\Users >java Test4
Binry representation of 4 is:100
Hex string of 27 is :1b
Octal string of 9 is :11
Auto-boxing and Auto-unboxing
The automatic conversion of the primitive type into its corresponding wrapper
types so that the value may be represented by the reference is called “auto-
boxing”.
The process of converting the wrapper class objects into primitive type is called
“auto-unboxing”
Example
Integer x=20; here x is an object (auto-boxing)
int y=x; //here object x is assigned to primitive type variable y (auto-unboxing)
class Test4
{
public static void main(String arg[])
{
For instance, Array, and Vector classes are used for working with arrays and
variable length arrays.
Along with above classes it also contains Scanner and Formatter classes, the date
and time also part of java.util package.
Java Scanner class is text scanner class that breaks the input into tokens using the
delimiter, which is white space by default.
Delimiter is not part of the string, it will be at the beginning or at the end.
The resulting tokens can then be converted into various types of data using the
next() methods.
The following code allows the user to read input of type int from the keyboard.
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads an int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Returns true if the next token in this scanner's input can be interpreted as an
hasNextInt()
int value in the default radix using the nextInt() method.
Returns true if the next token in this scanner's input can be interpreted as a
hasNextDouble()
double value using the nextDouble() method.
Returns true if the next token in this scanner's input can be interpreted as a
hasNextFloat()
float value using the nextFloat() method.
Formatter Class
The class Formatter supports the formatting of output for Characters, strings and
numbers.
We already have used printf() method to avoid string concatenation using the
println() method.
The Formatter class is used to specify the justification, alignment, formats for
numbers, and strings etc.
The method format() is used to format the output. The Formatter object is then
passed as an argument to println() method as shown in the following example.
Example Program
Specification of Field Width
The minimum field can be specified which the output must be formatted using the
filed width.
This is specified between % and conversion character (Ex: %4d, %6.3f), Here for
integer 4 represents the minimum field width. For floating point number the
integer part contains 6 digits and fractional part contains 3 digits.
The %n is used to insert \n in the output , and %% is used to append % at the end
of number.
import java.util.*;
class ScanTest
{
public static void main(String arg[])
{
Formatter ft=new Formatter();
int i=12;
double d=123.456788;
String s="Hello Format";
ft.format("%5d %4.3f %20s",i,d,s);
System.out.println(ft);
}}
C:\Users >java ScanTest
12 123.457 Hello Format
Random Class
The class Random is used to generate random numbers of different types such as
int, double, float, long, and byte.
The random() method of the Math class also can be used to generate random
numbers from 0.0 to 1.0.
import java.util.*;
class TestRandom
{ public static void main(String arg[])
{
Random rand=new Random();
rand.setSeed(10);
System.out.println("The Random long is :"+rand.nextLong());
System.out.println("The Random Integer is :"+rand.nextInt());
System.out.println("The Random double is :"+rand.nextDouble());
System.out.println("The Random boolean is :"+rand.nextBoolean());
System.out.println("Ten random numbers are:");
for(int i=0;i<10;i++)
{
System.out.print(rand.nextInt(10)+"\t");
}}}
C:\Users>java TestRandom
The Random long is :-4972683369271453960
The Random Integer is :1107254586
The Random double is :0.4129126974821382
The Random boolean is : true
Ten random numbers are:
7 8 1 4 3 9 1 8 5 0
Time Package
The time package provides support for date and time features for developers.
It contains classes that represent date/time concepts including instants, duration,
date, time, time zones, and periods.
This date/time framework prior to java 8 are provided by java.util.Date
class, java.util.Calendar class, and java.util.SimpleDateFormatter
class which have some problems as follow:
These classes are not Thread safe.
Poor design
It is difficult to work with different Calendar systems.
This has led a third party to create ‘Joda-Time’ package.
New Time Package (java.time)
This was introduced in java8.
It has four sub packages like java.time.format, java.time.chrono,
java.time.temporal, and java.time.zone.
There are some terms to understand the time as follow:
Instant- time since 1st jan 1970
Time zone – region of the earth where same time standard is followed.
Time zoneID – It is an identifier of time zone (region)
Zone offset – it is the difference between time zone and Greenwich time.
Classes of Time package : java.time package contains many classes; the most
commonly used classes are as follows:
Clock – supports access to instant, time, date
Duration –deals with time in terms of seconds, and nanoseconds.
Instant – data time instance sincs 1 st jan 1970
LocalDate- returns the local date of the system.
LocalTime- gives the local time of the system.
LocaDateTime- gives date and time combination of local system.
ZonedDateTime- returns the date and time of the zone with zone id also.
ZoneId-gets the Zone Id from the current ZonedDateTime
The object return by this class is expressed in terms of seconds since 1 st jan 1970,
which is also called Epoch.
Any instant before Epoch has a negative value and any instant after Epoch has
positive value.
We can convert the seconds into years, day, hours, and minutes as follow:
LocalDateTime t=
LocalDateTime.ofInstant(timestamp,ZoneId.SystemDefault());
Methods of Instant class
isAfter (Instant) –Compares two instants, and returns true if the instant is
after given Instant, otherwise false.
isBefore(Instant) -Compares two instants, and returns true if Instant is before
given instant, Otherwise false.
plusMinutes(), plusHours() – adds time to instant like hours or minutes.
minusMinutes(),minusHours() –subtracts the times
Until() –returns the time left between two instants.
Example Program
import java.time.Instant;
class InstantDemo
{
public static void main(String arg[])
{
Instant now=Instant.now();
System.out.println("The value of present time is :"+now);
Instant before=Instant.now().minusSeconds(500);
System.out.println("The value of before current time is :"+before);
Instant later=Instant.now().plusSeconds(600);
System.out.println("The value of future time is :"+later);
System.out.println("Testing isAfter:"+later.isAfter(now));
}
Output
ISO_DATE 2015-08-22
ISO_DATE_TIME 2015-08-22 11:20:40
ISO_INSTANT Ex:2015-10-03T10:15:24
ISO_LOCAL_DATE 2015-11-20
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
class FormatDateDemo
{ public static void main(String arg[])
{
LocalDateTime t=LocalDateTime.now();
System.out.println("Local Date Time is:"+t);
System.out.println("User format Format:"
+t.format(DateTimeFormatter.ofPattern("dd-MMM-
yyyy hh:mm:ss")));
System.out.println("User format 2:"
+t.format(DateTimeFormatter.ofPattern("yyyy-
MMM-dd hh:mm:ss")));
}
}
The methods of this class are useful to determine first day of month, last day of year
among others.
import java.time.*;
import java.time.temporal.TemporalAdjusters;
class TemporalTest
{ public static void main(String arg[]) {
LocalDate date1=LocalDate.of(2015,Month.NOVEMBER,20);
DayOfWeek dw=date1.getDayOfWeek();
System.out.println("The day of the week :"+dw);
System.out.println("The last day of November is:"
+date1.with(TemporalAdjusters.lastDayOfMonth()));
}
}
Exception: The error raised when the program is in execution is called Exception or Runtime
Error. This is raised due the mistake made by the user or system.
An exception is an unexpected event that occurs during program execution. It affects the flow of
the program instructions which can cause the program to terminate abnormally.
Some of the exceptions are as follow:
🞑 Giving negative number as array size.
🞑 Giving negative as argument for method to find square root.
🞑 Opening a file that does not existing.
🞑 When the file is not found.
🞑 Dividing a number by zero
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 given to the runtime system, which searches for the
appropriate code that can handle the exception.
The exception handling code is called exception handler.
Exception handling is a mechanism that is used to handle Runtime Errors such as divide by
zero error,classNotFound and IO.
This ensures that the normal flow of application program 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 generates an exception may itself provide a code to deal with it.
Exception handling is managed by Java via five keywords:
try
catch
throw
throws
finally.
Working Exception handling Techniques:
1. Briefly, here is how they work. Program statements that you want to
monitor forexceptions are placed within a try block.
2. If an exception occurs within the try block, it is thrown. Your code can
catch thisexception (using catch) and handle it in some rational manner.
3. System-generated exceptions are automatically thrown by the Java run-
time system.To manually throw an exception, use the keyword throw.
4. Any exception that is thrown out of a method must be specified as such by a throws
clause.
5. Any code that absolutely must be executed after a try block completes is put in a
finally block.
Syntax:
try
{
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
}
The try and catch blocks
🞑 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 none matches, the program flow records the type of exception, executes the finally
block, and terminates the program.
try {
// code
}
catch(Exception e) {
// code
}
Here, we have placed the code that might generate an exception inside the try block. Every try
block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block cannot be used
without the try block. There may be more than one catch blocks.
class Exp {
public static void main(String[] args) {
try {
The finallyblock:
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.
import java.util.*;
class ThrowExcep
{
int a,b,c;
void read() throws InputMismatchException,ArithmeticException
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a and b values:");
a=in.nextInt();
b=in.nextInt();
c=a/b;
System.out.println("Division is:"+c);
}
}
class ThrowTest
{
public static void main(String args[])
{
ThrowExcep t=new ThrowExcep();
try
{
t.read();
}
Catch (Exception e)
{
System.out.println("Exception is:"+e);
}
finally
{
System.out.println("End of the main program");
} }}
Output1: Enter a and b values:
4
0
Exception is:java.lang.ArithmeticException: / by zero
End of the main program
Output2: Enter a and b values:
4b
Exception is:java.util.InputMismatchException
End of the main program
Hierarchy of Standard Exception Classes
In Java, exceptions are instances of classes derived from the class Throwable which in turn
is derived from class Object.
Whenever an exception is thrown, it implies that an object is thrown.
Only objects belonging to class that is derived from class Throwable can be thrown as
exceptions.
Some of the examples of Error including 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.
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.
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. Ex; IOException in main
method.
This can be done in two ways:
1. The method provides the exception handler in the form of appropriate try–catch blocks.
2. The method may simply declare the list of exceptions that the method may throw with
throws clause in the header of the method.
🞑In this case, the method need not provide any exception handler.
🞑It is the responsibility of the caller to handle the exception in its code.
Note: If a method does not follow either of the aforementioned ways, the compilation will
result in an error.
Throwable class: All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy.The Throwable has several methods. The
three commonly usedmethods for getting information about the exceptions are as follow:
Throws:
If a method can cause one or more checked exceptions directly or indirectly by calling other
methods and throw exceptions and does not handle with them, it must declare the list of
exceptions it can throw by using the throws clause.
By doing this, the caller of the method can ensure that appropriate arrangements are made to
handle with the exceptions. The caller may be other method or JVM.
For this, keep the method in a try block, and provide suitable catch blocks.
The program will not compile if this is not done.
The throws clause comprises the keyword throws followed by the list of exceptions that the
method is likely to throw separated by commas.
The method declaration with throws clause is
type methodname(type parameters) throws list-of-Exceptions
{ /* Body of Method*/ }
Throw keyword
The throw keyword in Java is used to explicitly throw an exception from a method or any
block of code.
The throw keyword is mainly used to throw custom exceptions or user defined exceptions.
Syntax: throw Instance;
Example: throw new ArithmeticException("/ by zero");
Uncaught exceptions
Whenever an exception is thrown it must be handle by the handler.
If no catch block is provided or an exception is not caught, it is handled by the JVM
by default which usually terminates the program execution and display an error
message at the end.
Note: After try block, the finally block will be executed if catch block is not present.
try {
//statements
}
finally { }
Finalize() in Exception Handling
The finalize() method is called by garbage collector thread, and thereby memory
allocated to the object is reclaimed.
Any exception thrown by finalize method is ignored by the garbage collector thread
and it is not logged into the log files.
Multiple Catch Clauses
Often the programs throw more than one type of exception.
The programmer has to provide a catch block for each type of exception.
One way to reduce this use hierarchy of classes and super class as argument of catch
block, so that the number of exceptions are caught.
However it is not suitable because it hides the information about what really went
wrong.
Since Java 7, a modification has been done in the language so that one catch block
can catch more than one type of exception.
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.
Constructors of class Throwable
The Throwable class has several methods. Since the Throwable is the super class, all the
Sub classes can access these methods. Some of the methods are as follows:
Unchecked Exceptions
It is not checked by the compiler whether the programmer has handled them or not.
These exceptions form a subgroup of classes that are subclasses of class Exception.
Unchecked subclasses of RuntimeException
Checked Exceptions
These are the exceptions that are checked by the compiler and these are also called
compiled time exceptions.
The programmer has to handle these exceptions, if not handle these exceptions will
give compilation errors.
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 (guaranteed) method for recovery of sources and memory.
It is observed that programmers who are not skillful often forget to close files, and data
bases what they have opened when their work is over.
In order to redress the problem, Java 7 has added AutoCloseable interface along with it
another try block called “try-with_resources”.
This AutoCloseable interface has one method called close() which will be automatically
invoked by the sources that implement the interface and are managed by try-with-sources.
Catching Subclass Exception
When this method is overridden in the sub class with exception handling, then following
points must be considered.
🞑 If the super class method does not declare any exception, then subclass overridden
method cannot declare checked exceptions, but it can declare unchecked exceptions.
Java user-defined exception is a custom exception created by user and throws that exception
using a keyword ‘throw’. It is done by extending a class ‘Exception’. Java allows us to create our
own exception class, which provides own exception class implementation. Such exceptions are
called user-defined exceptions or custom exceptions.
To implement a user-defined exception in Java, follow these steps:
Create a custom exception class that extends the base exception class
(java.lang.Exception).
Define the constructor for the custom exception class. The constructor can accept
parameters to provide more information about the error.
Override the toString() method to provide a custom error message.
Use the "throw" keyword to throw an instance of the custom exception when the error
condition occurs.
Use a "try-catch" block to catch the exception and handle it appropriately.
import java.util.*;
//user defined exception
class NegativeExp extends Exception
{
//constructor
NegativeExp(String msg)
{
super(msg);
}
}
Nested try and catch blocks
In nested try-catch blocks, one try catch can be placed within another try’s body.
Nested try-block is used where a part of the body may cause one error, and the entire part
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.
Syntax
try
{ //main try block
//Statements here try{//try block 1
//statements here
try{ //try block 2
//statements here
} catch(Exception e1)
{
//Statements of Innermost catch block
}
} catch(Exception e2)
{//Statements of Middle catch block
}
}
catch(Exception e)
{
//Outer most catch block
}
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.