Module 4
Module 4
By:
Prof. Kavitha B
Asst.Prof ,Dept ISE
Syllabus
Packages: Packages, Packages and Member Access,
Importing Packages.
Exceptions: Exception-Handling Fundamentals,
Exception Types, Uncaught Exceptions, Using try and
catch, Multiple catch Clauses, Nested try Statements,
throw, throws, finally, Java’s Built-in Exceptions,
Creating Your Own Exception Subclasses, Chained
Exceptions.
Packages
A java package is a group of similar types of classes,
interfaces and sub-packages.
Package in java can be categorized in two form,
built-in package and user-defined package.
There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
All classes in Java belong to some package. When no
package has been explicitly specified, the default (or
global) package is used.
To create a package, you will use the package
statement.
General form of the package statement is
package pkg;
Here pkg is the name of the package.
More than one file can include the same package
statement.
You can create hierarchy of packages.
The general form is
package pack1.pack2.pack3…..packN;
Ex:
package alpha.beta.gamma;
must be stored in /alpha/beta/gamma specifies
the path to be specified directories.
Ex:
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
If you want to keep the package within the same
directory, you can use . (dot).
To compile: javac -d directory javafilename
To Run: java packagename.Simple
For above program
to complile: javac –d . Simple.java
to run: java mypack.Simple
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.
Because of the interplay between classes and
packages, 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.
having default access modifier are accessible only within the same package.
protected access modifier
The protected access modifier is accessible within package
and outside the package but through inheritance only.
The protected access modifier can be applied on the data
member, method and constructor. It can't be applied on
the class.
Ex:
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Default
If you don't use any modifier, it is treated as default by
default.
The default modifier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more
restrictive than protected, and public.
EX:
package pack;
class A //save by A.java
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Here,the scope of class A and its method msg() is default
so it cannot be accessed from outside the package
Importing packages
Using import, you can bring one or more members of a
package into view.
The general form of import statement.
import pkg.classname;
Here pkg is the name of the package, which can
include its full path, and classname is the name of the
class being imported.
If you want to import the entire contents of a package,
use an asterisk(*) for the class name.
Ex:
import mypack.MyClass;
import mypack.*;
In the first case,the MyClass is imported from mypack.
In the second,all of the classes in myback are
imported.
EX:
import java.util.Date;
import java.io.*;
All of the standard Java classes included with Java are
stored in a package called java.
The basic language functions are stored in a package
inside of the java package called java.lang.
import java.lang.*;
EX:
import java.util.*;
class MyDate extends Date {}
Subpacka Description
ge
java.lang Contains a large number of general-purpose classes
java.io Contains the I/O classes
java.net Contains those classes that support networking
java.Applet Contains classes for creating applets
java.awt Contains classes that support the Abstract Window
Toolkit
java.util Contains various utility classes, plus the Collections
Framework.
How to access package from another package?
There are three ways to access the package from
outside the package.
import package.*;
import package.classname;
fully qualified name.
package pack18; // packagename.*
public class raghu18
{
public void msg()
{
System.out.println("Hello rnsit");
}
}
------------------------------------------------------
package mypack12;
import pack18.*;
class prasad12
{
public static void main(String args[])
{
raghu18 obj = new raghu18();
obj.msg();
}
}
//save by A.java Using packagename.classname
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
- --------------------------------------------------------------------------
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
//save by A.java Using fully qualified name
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
------------------------------------------------------------------
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified
name
obj.msg();
}
}
Exception Handling
The exception hierarchy:
An exception is an error that occurs at run time.
In java, all exceptions are represented by classes.
All exception class are derived from a class called
Throwable.
Throwable class is the superclass of all exceptions
in the Java language.
When an exception occurs in a program, an object of
some type of exception class is generated.
Exception handling fundamentals
Java exception handling is managed via five
keywords.
They are try, catch, throw, throws and finally.
Programs statements that you want to monitor for
exceptions are contained 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 run-time system.
To manually throw an exception, use the keyword
throw.
Java try block must be followed by either catch or
finally block.
In some cases, an exception that is thrown out of a
method must be specified as such by a throws clause.
Any code that absolutely must be executed upon exiting
from a try block is put in a finally block.
Syntax of java try-catch
try
{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try
{
//code that may throw exception
}
finally{}
Ex:
Without using try-catch(Uncaught Exceptions)
public class testtry
{
public static void main(String args[])
{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main
java.lang.ArithmeticException:/ by zero
EX1: Using java try-catch block.(caught Exceptions)
public class testtry1
{
public static void main(String args[])
{
try{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
EX2:
class Exc2
{
public static void main(String args[])
{
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
The consequences of an uncaught
exception
If your program does not catch an exception, then it
will be caught by the JVM.
The trouble is that the JVM’s default exception handler
terminates execution and displays an error message
followed by a list of the methods calls that lead to the
exception.
Internal working of java try-catch block
Multiple catch Clauses
You can associate more than one catch clause with a
try. Each catch must catch a different type of
exception.
At a time only one Exception is occurred and at a
time only one catch block is executed.
Ex:
public class TestMultipleCatch
{
public static void main(String args[])
{
try{
int a[]=new int[5];
a[5]=30;
} Contd….
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
catch(Exception e)
{
Contd…..
class Example {
public static void main(String args[]) {
try {
System.out.println("Enter age: ");
int age = sc.nextInt();