JAVA Unit 3
JAVA Unit 3
Packages:
package pack;
public class Subtraction
{
2
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}
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();
}
}
Note: Don’t place Addition.java, Subtraction.java files parallel to the pack directory. If
you place JVM searches for the class files in the current working directory not in the
pack directory.
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 (public)
4
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
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.
Name of the package: pkg1
This file is Protection.java
package pkg1;
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);
}
}
/* class only
* System.out.println("n_priv = "4 + n_priv); */
package pkg1;
class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
System.out.println("same package - other constructor");
System.out.println("n = " + pro.n);
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
package pkg2;
6
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
/* class only
* System.out.println("n_priv = " + n_priv); */
class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();
/* 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;
8
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
9
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
Exception
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios
where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code. When an exceptional condition arises, an object representing
that exception is created and thrown in the method that caused the error. That method may
choose to handle the exception itself, or pass it on. Either way, at some point, the exception is
caught and processed.
Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally. Briefly, here is how they work. Program statements that you want
to monitor for exceptions are contained within a try block. If an exception occurs within the try
block, it is thrown. Your code can catch this exception (using catch) and handle it in some
rational manner. System-generated exceptions are automatically thrown by the Java runtime
system. To manually throw an exception, use the keyword throw. Any exception that is thrown
out of a method must be specified as such by a throws clause. Any code that
absolutely must be executed after a try block completes is put in a finally block.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
10
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
}
Here, ExceptionType is the type of exception that has occurred. The remainder of
this
chapter describes how to apply this framework.
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.
Uncaught Exception:
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 this example, we haven’t supplied any exception handlers of our
own, so the exception is caught by the default handler provided by the Java run-time
system. Any exception that is not caught by your program will ultimately be processed by the
default handler. The default handler displays a string describing the exception, prints a stack
trace from the point at which the exception occurred, and terminates the program.
11
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
Example:
class UsingTry_Catch
{
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:
• In some cases, more than one exception could be raised by a single piece of code.
• To handle this type of situation, you can specify two or more catch clauses, each
catching a different type of exception.
• When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed.
• If one catch statement is executed, the others are bypassed, and execution continues after
the try / catch block.
• When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their super classes. This is because a catch
12
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
statement that uses a super class will catch exceptions of that type plus any of its
subclasses. Subclass would never be reached if it came after its super class.
• A subclass must come before its super class in a series of catch statements. If not
unreachable code will be created and a compile time error will result.
Example:
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(Exception e)
{
System.out.println("Array index out of bounds: " +
e);
}
System.out.println("After try/catch blocks.");
}
}
• The try block within a try block is known as nested try block in java.
Syntax:
try{
try {
statement 1;
statement 2;
try
{
13
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
statement 1;
statement 2;
}
catch(Exception e) { }
}
}
catch(Exception e){}
• 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 all of the nested try
statements are exhausted. If no catch statement matches, then the Java run-time system
will handle the exception (default handler).
Example:
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
/* If no command-line args are present, the following statement
will
generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
if(a==1)
a = a/(a-a); // division by zero
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
finally block:
• Java finally block is a block that is used to execute important code such as closing
connections (databases, network, disks, commit in databases) etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
Example 1:
class Finally_Case1 //exception not occured
{
public static void main(String args[])
{
try{
int data=25/25;
System.out.println(data);
15
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
}
finally
{
System.out.println("finally block is always
executed");
}
System.out.println("rest of the code...");
}
}
Example 2:
class Finally_Case2 //exception occured and not handled.
{
public static void main(String args[])
{
try{
int data=25/0;
System.out.println(data);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always
executed");
}
System.out.println("rest of the code...");
}
}
Example 3:
class Finally_Case3 //exception occured and handled.
{
public static void main(String args[])
{
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
16
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
finally
{
System.out.println("finally block is always
executed");
}
System.out.println("rest of the code...");
}
}
Use of throw
• So far, you have only been catching exceptions that are thrown by the Java run-time
system. 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;
• Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
Example:
/*
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.*/
17
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
Use of throws: If you are not in a position to handle the exception use throws clause
to intimate to the caller.
Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
18
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
ception
19
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
• We can also create our own exception by creating a sub class simply by extending java
Exception class.
• Define a constructor for Exception sub class (not compulsory) and override the
toString() method to display customized message in catch clause.
– Exception();
– Exception(parameter);
• The first form creates an exception that has no description. The second form lets you
specify a description of the exception.
Syntax of toString():
• String toString( )
- Returns a String object containing a description of the exception.
- This method is called by println( ) when outputting a Throwable object.
- belongs to Object class
Example:
class MyException extends Exception
{
String s ;
MyException( String s)
{
this.s=s;
}
public String toString()
{
return ("User Defined " +s) ;
}
}
class UserDefinedException
{
public static void main(String args[])
{
try{
throw new MyException("Exeption"); // throw is used to
create //a new exception and throw it.
}
catch(MyException e)
{
System.out.println(e) ;
}
20
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 3 Packages
}
}
21
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.