Java Module5 Bplck205c
Java Module5 Bplck205c
MODULE-5
Syllabus:
Chapter 1:
1. Packages
(i) Defining a Package
(ii) Finding Packages and CLASSPATH
(iii) A Short Package Example
2. Access Protection
(i) An Access Example
3. Importing Packages
4. Interfaces
(i) Defining an Interface
(ii) Implementing Interfaces
(iii) Interface Can Be Extended
Chapter 2:
1. Exception-Handling Fundamentals
2. Exception Types
3. Uncaught Exceptions
4. Using try and catch
(i) Displaying a Description of an Exception
5. Multiple catch Clauses
6. Nested try Statements
7. throw
8. throws
9. finally
10. Java’s Built-in Exceptions
Chapter 1: Packages
1. Packages
Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.
The package is both a naming and a visibility control mechanism. You can define
classes inside a package that are not accessible by code outside that package.
You can also define class members that are only exposed to other members of the
same package.
Benefits of packages:
The classes in the packages can be easily reused.
In the packages, classes are unique compared with other classes in the other
packages.
Packages provide a way to hide classes thus prevent classes from accessing by
other programs.
Packages also provide way to separate "design" from "coding".
Open a notepad or text editor, write the above code and save it as
"Balance.java" in the folder name "Mypackage”. Here, the package name and
subdirectory (folder) name must be same.
This subdirectory (Folder) must be part of your main current directory (current
Folder) in which you write the main class PackTest1.java. That means the
"PackTest1.java" source file and "MyPackage" will be in the same directory
(Folder).
The "Balance.java" file must be compiled to generate the ".class" file in the
same directory (folder), which will be accessed in another program by importing
the package.
//PackTest1.java
OUTPUT
import MyPackage.Balance;
The name is ABCD and amount is $1234.0
class PackTest1
{
public static void main(String[] args)
{
Balance b=new Balance ("ABCD",1234);
b.show();
}
}
2. Access Protection
Packages act as containers for classes and other subordinate packages.
Classes act as containers for data and code.
The class is Java’s smallest unit of abstraction.
Java addresses four categories of visibility for class members:
Subclasses in the same package
Non-subclasses in the same package
Subclasses in different packages
Classes that are neither in the same package nor subclasses.
The three access specifiers, private, public, and protected, provide a variety of
ways to produce the many levels of access required by these categories.
Private Default Protected Public
Same class Yes Yes Yes Yes
Same package
No Yes Yes Yes
subclass
Same package
No Yes Yes Yes
non-subclass
Different package
No No Yes Yes
subclass
Different package
No No No Yes
non-subclass
3. Importing Packages
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.)
Specify either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.
This code fragment shows both forms in use:
import java.util.Date;
import java.io.*;
4. Interfaces
Using interface, you can specify what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
Java does not allow acquiring properties from more than one class, which we call it
as "multiple inheritance". We know that large number of real-life applications
require the use of multiple inheritance.
Java provides an alternative approach known as "interface" to support the concept
of multiple inheritance.
(i) Defining an Interface
An interface is basically a kind of class. Like classes, interfaces contain the
methods and variables but with major difference.
The difference is those interfaces define only abstract methods and final fields.
This means that interface do not specify any code to implement these methods
and data fields contain only constants. It is the responsibility of the class that
implements an interface to define the code for these methods.
The general form of an interface will be as follows:
interface Interface_Name
{
return-type method-name(parameter-list);
type final-varname=value;
}
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
finally
{
// block of code to be executed after try block ends
}
2. Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable
is at the top of the exception class hierarchy.
Immediately below Throwable are two subclasses that partition exceptions into
two distinct branches.
One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. This is also the class that you will subclass to
create your own custom exception types. There is an important subclass of
Exception, called RuntimeException. Exceptions of this type are automatically
defined for the programs that you write and include things such as division by zero
and invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not expected
to be caught under normal circumstances by your program. Exceptions of type Error
are used by the Java run-time system to indicate errors having to do with the run-
time environment, itself. Stack overflow is an example of such an error. This chapter
will not be dealing with exceptions of type Error, because these are typically created
in response to catastrophic failures that cannot usually be handled by your program.
3. Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful to see what
happens when you don’t handle them. This small program includes an expression
that intentionally causes a divide-by-zero error:
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of
Exc0 to stop, because once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
In the above program we have not provided any exception handler, in this context
the exception is caught by the default handler. The default handler displays string
describing the exception.
Here is the exception generated when this example is executed:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:6)
Notice how the class name, Exc0; the method name, main; the filename, Exc0.java;
and the line number, 6, are all included in the simple stack trace. Also, notice that
the type of exception thrown is a subclass of Exception called
ArithmeticException, which more specifically describes what type of error
happened.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
OUTPUT
Division by zero.
After catch statement.
catch (ArithmeticException e)
{
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
When this version is substituted in the program, and the program is run, each
divide-byzero error displays the following message:
Exception: java.lang.ArithmeticException: / by zero
OUTPUT 1:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
OUTPUT 2:
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
6. Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is
pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception,
the stack is unwound and the next try statement’s catch handlers are inspected for a
match. This continues until one of the catch statements succeeds, or until the entire
nested try statements are exhausted. If no catch statement matches, then the Java
run-time system will handle the exception.
7. throw
So far, you have only been catching exceptions that are thrown by the Java run-time
system implicitly.
However, it is possible for your program to throw an exception explicitly, using the
throw statement. The general form of throw is shown here:
throw ThrowableInstance;
// Demonstrate throw.
class ThrowDemo
{ OUTPUT
static void demoproc() java.lang.Exception: The value
{ of j cannot be Zero
try
{
int j=0;
if(j==0)
throw new Exception("The value of j cannot be Zero");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
demoproc();
}
}
8. throws
If the function is not capable of handling the Exception then it can ask the calling
method to handle it by simply putting throws at the function declaration.
It gives information to the caller method that there may be occur an exception so it
is better for the caller method to provide the exception handling code, so that the
normal flow can be maintained.
The general form of a method that includes a throws clause:
class ThrowsDemo
{
static void throwone() throws IllegalAccessException
{
System.out.println("Inside Throw");
throw new IllegalAccessException("Demo");
}
public static void main(String args[])
{
try OUTPUT
{ Inside Throw
throwone(); Caughtjava.lang.IllegalAccessException: Demo
}
catch(IllegalAccessException e)
{
System.out.println("Caught"+e);
}
}
}
9. finally
The finally block is always is executed. It is always used to perform housekeeping
operations such as releasing the resources, closing the files that already opened etc,.
That means the statement that put inside the finally block are executed
compulsorily.
It is always followed by the try-catch statements.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.
The finally clause is optional. However, each try statement requires at least one
catch or a finally clause.
Prof. Ashwini G Dept. of CS&E, MITT Page 14
Basis of Java Programming Module-5 BPLCK205C
Syntax
try
{
//statements
}
catch (Exception e)
{
//Handlers
}
finally
{
//statements
}
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined
enumeration value
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state
llegalThreadStateException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds
NegativeArraySizeException Array created with a negative size.
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
llegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class
or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist
Table2: Java’s Checked Exceptions Defined in java.lang