Module 4
Module 4
Packages in JAVA
Packages:
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
To create a package : include a package command as the first statement in a Java source
file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default package, which has
no name.
package MyPackage;
Java uses file system directories to store packages.
For example, the .class files for any classes you declare to be part of MyPackage must be
stored in a directory called MyPackage.
More than one file can include the same package statement.
The package statement simply specifies to which package the classes defined in a file belong.
A package hierarchy must be reflected in the file system of Java development system.
• Third, you can use the -classpath option with java and javac to specify the path
to your classes.
C:\MyPrograms\Java\MyPack
Then the class path to MyPack is
C:\MyPrograms\Jav
Example: Package demonstration
package pack;
public class Addition
{
int x,y;
public Addition(int a, int b)
{
x=a;
y=b;
}
public void sum()
{
System.out.println("Sum :"+(x+y));
}
Access Protection
• Access protection defines actually how much an element (class, method, variable) is
exposed to other classes and packages.
• There are four types of access specifiers available in java:
1. Visible to the class only (private).
2. Visible to the package (default). No modifiers are needed.
3. Visible to the package and all subclasses (protected)
4. Visible to the world (publ
Example:
The following example shows all combinations of the access control modifiers. This example
has two packages and five classes. The source for the first package defines three classes:
Protection, Derived, and SamePackage.
int n = 1;
private int n_priv = 2;
protected int n_prot = 3;
public int n_publ = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}
Derived()
{
/* class only
* System.out.println("n_priv = "4 + n_priv); */
pkg1;
class SamePackage
{
SamePackage()
{
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
package pkg2;
Protection2()
{
/* class only
* System.out.println("n_priv = " + n_priv); */
package pkg2;
class OtherPackage
{
OtherPackage()
{
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
If you want to try these t two packages, here are two test files you can use. The one for
package pkg1 is shown here:
package pkg1;
package pkg2;
}
Importing Packages
import statement is used to include certain classes, or entire packages, into visibility.
Once imported, a class can be directly referred using its name.
pkg1 is the name of a top-level package, and pkg2 is the name of a sub package inside the outer
package separated by a dot (.). There is no practical limit on the depth of a package hierarchy,
except that imposed by the file system.
specify either an explicit classname or a star (*), which indicates that the Java compiler should
import the entire package.
Example:
package pack;
int x,y;
public Addition(int a, int b)
{
x=a;
y=b;
}
public void sum()
{
System.out.println("Sum :"+(x+y));
}
package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
2. import package.classname;
import pack.Addition;
import pack.Subtraction;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new
Addition(10,15); a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
3. import package.*;
import
pack.*; class
UseofPack
{
public static void main(String arg[])
{
Addition a=new
Addition(10,15); a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
Exception handling
Introduction
An Exception, It can be defined as an abnormal event that occurs during program execution and disrupts the
normal flow of instructions. The abnormal event can be an error in the program.
1. Compile- time errors occur when you do not follow the syntax of a programming language.
2. Run-time errors occur during the execution of a program.
Concepts of Exceptions
An exception is a run-time error that occurs during the exception of a java program.
Example :If you divide a number by zero or open a file that does not exist, an exception is raised.
In java, exceptions can be handled either by the java run-time system or by a user- defined code .
When a run-time error occurs, an exception is thrown.
The unexpected situations that may occur during program execution are:
3. throw.
4. throws.
5. finally.
Exceptions are handled using a try-catch-finally construct, which has the Syntax:
try
{
<code>
}
catch(<exceptiontype1> <parameter1>)
{
finally
{
If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error.
Again if the matching catch handler is not found execution proceeds with the finally block and
the default exception handler throws an exception.
2. catch Block: Exceptions thrown during execution of the try block can be caught and
handled in a catch block. On exit from a catch block ,normal execution continues and the finally
block is executed (Though the catch block throws an exception).
3. finally Block: A finally block is always executed, regardless of the cause of exit from the try
block, or whether any catch block was executed. Generally, finally block is used for freeing
resources, cleaning up, closing connections etc.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the
array which throws an exception.
//FileName:ExcepTest.java
importjava.io.*;
try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exceptionthrown:"+e);
System.out.println("Outoftheblock");
A try block can be followed by multiple catch blocks .The syntax for multiple catch blocks looks like the
following:
try
{
//code
}
catch(ExceptionType1 e1)
{
//Catchblock
}
catch(ExceptionType2 e2)
{
//Catchblock
}
catch(ExceptionType3 e3)
{
//Catchblock
}
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try.
Example: Here is code segment showing how to use multiple try/catch statements.
class Multi_Catch
try
int a=args.length;
System.out. println(“a=”+a);
Int b=50/a;
Int c[]={1};
catch(ArithmeticException e)
System.out.println("Divisionbyzero");
catch(ArrayIndexOutOfBoundsException e)
System.out.println("arrayindexoutofbound");
OUTPUT
Division by zero
Just like the multiple catch blocks, we can also have multiple try blocks . These try blocks
may be written independently or we can nest the try blocks within each other, i.e., keep one
try-catch block within another try- block.The program structure for nested try statement is:
Syntax
try
//statements
//statements
try
//statements
//statements
catch(<exception_two> obj)
//statements
//statements
//statements
catch(<exception_two> obj)
//statements
Consider the following example in which you are accepting two numbers from the
command line. After that, the command line arguments, which are in the string format, are
converted to integers.
If the numbers were not received properly in a number format, then during the conversion
a NumberFormatException is raised otherwise the control goes to the next try block. Inside
this second try-catch block the first number is divided by the second number, and during the
calculation if there is any arithmetic error, it is caught by the inner catch block.
Example
class Nested_Try
try
try
quot = a /b;
System.out.println(quot);
}
catch(ArithmeticException e)
System.out.println("dividebyzero");
}
catch(NumberFormatException e)
System.out.println("Incorrectargumenttype");
}
}
}
OUTPUT
Java Nested_Try2 4 6
4
throw Keyword
throw keyword is used to throw an exception explicitly. Only object of throwable class or
its sub classes can be thrown.
Program execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception.
Creating InstanceofThrowableclass
New NullPointerException("test");
class Test
{
try
{
catch(ArithmeticException e)
{
System.out.println("Exceptioncaught");
}
avg();
}
In the above example the avg() method throw an instance of Arithmetic Exception, which is
successfully handled using the catch statement.
throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during
its execution, so that anyone calling that method gets a
prior knowledge about which exceptions to handle. A method can do so by using the throws
keyword.
Syntax:
type method_name(parameter_list)
throws exception_list
//definition of method
}
NOTE: It is necessary for all exceptions, except the exceptions of type Error and
Runtime Exception, or any of their subclass.
class Test
{
System.out.println("Insidecheckfunction");
thrownewArithmeticException("demo");
}
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught"+e);
}
finally
The finally clause is written with the try- catch statement. It is
guaranteed to be executed after a catch block or before the method
quits.
Syntax
try
//statements
catch(<exception> obj)
{
//statements
}
finally
{
//statements
}
Take a look at the following example which has a catch and a finally block. The
catch block catches the Arithmetic Exception which occurs for arithmetic error like
divide-by-zero. After executing the catch block the finally is also executed and
you get the out put for both the blocks
Example:
class Finally_Block
try
catch(ArithmeticExceptione)
System.out.println("Dividebyzero");
}
finally
System.out.println("Inthefinallyblock");
}
class Mypgm
OUTPUT
Divide by zero
In the finally block
Java’s Built in Exceptions
Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported in to all Java programs , most exceptions
derived from RuntimeException are automatically available.
Java defines several other types of
exceptions that relate to its various class
libraries .Followi ng is the list of Java
UncheckedRuntimeException
Exception Description
ArithmeticException Arithmeticerror,suchasdivide-by-zero.
ArrayIndexOutOfBoundsException Arrayindexisout-of-bounds.
Assignmenttoanarrayelementofaninc ompatibletype.
ArrayStoreException
ClassCastException Invalidcast.
IllegalArgumentException Illegalargumentusedtoinvokeamethod.
Exception Description
ArithmeticException Arithmeticerror,suchasdivide-by-zero.
ArrayIndexOutOfBoundsException Arrayindexisout-of-bounds.
Assignmenttoanarrayelementofaninc ompatibletype.
ArrayStoreException
ClassCastException Invalidcast.
IllegalArgumentException Illegalargumentusedtoinvokeamethod.
Requestedoperationnotcompatiblewithcurrentt
IllegalThreadStateException hreadstate.
NegativeArraySizeException Arraycreatedwithanegativesize.
NullPointerException Invaliduseofanullreference.
SecurityException Attempttoviolatesecurity.
UnsupportedOperationException Anunsupportedoperationwasencountered.
Here you can also define your own exception classes by extending Exception. These exception can
represents specific runtime condition of course you will have to throw them yourself, but once
thrown they will behave just like ordinary exceptions.
When you define your own exception classes, choose the ancestor carefully. Most custom exception
will be part of the official design and thus checked, meaning that they extend Exception but not
Runtime Exception.
publicMyException(Stringstr)
{
super(str);
}
if(marks<=40)
msg = "You have failed";
if(marks>40)
msg = "You have Passed";
return msg;
class test
t.add();
try
int i=0;
if(i< 40)
catch(MyException ee1)
System.out.println("Result:"+ ee1);
}OUTPUT
Chained Exception
Chained exceptions are the exceptions which occur one after another i.e.most of the time to response
to an exception are given by an application by throwing another exception.
Whenever in a program the first exception causes an another exception, that is termed as Chained
Exception. Java provides new functionality for chaining exceptions.
Exception chaining (also known as "nesting exception") is a technique for handling the exception,
which occur one after another i.e. most of the time is given by an application to response to an
exception by throwing another exception.
Typically, the second exception is caused by the first exception. There fore chained exceptions help
the programmer to know when one exception causes another.
The constructors that support chained exceptions in Throwable class are: