Unit 4
Unit 4
Unit 4
PACKAGES
Example:
A.java
package mypack;
public class A
{
public void displayA()
{
System.out.println("I A M IN CLASS A");
}
}
B.java
package mypack;
public class B
{
public void displayB()
{
System.out.println("I A M IN CLASS B");
}
}
Compile
javac A.java
javac B.java
Demo.java
import mypack.*;
class Demo
{
public static void main(String args[])
{
A obj=new A();
obj.displayA();
}
}
Compile
javac Demo.java
java Demo
output:
I A M IN CLASS A
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
sub packages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
OUTPUT:
Hello subpackage
Access Protection
Classes and packages are both means of encapsulating and containing the name space and scope
of variables and methods. 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:
The three access modifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories. While Java’s access control mechanism
may seem complicated, we can simplify it as follows. Anything declared public can be accessed
from anywhere. Anything declared private cannot be seen outside of its class. When a member
does not have an explicit access specification, it is visible to subclasses as well as to other classes
in the same package. This is the default access. If you want to allow an element to be seen
outside your current package, but only to classes that subclass your class directly, then declare
that element protected.
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:
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 (.). There is no practical limit on the depth of a
package hierarchy, except that imposed by the file system. Finally, you 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.*;
EXCEPTION HANDLING
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, below given are some scenarios where
exception occurs.
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.
Based on these we have three categories of Exceptions you need to understand them to know
how exception handling works in Java
Checked exceptions: A checked exception is an exception that occurs at the compile time, these
are also called as compile time exceptions. These exceptions cannot simply be ignored at the
time of compilation, the Programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then an FileNotFoundException occurs, and compiler
prompts the programmer to handle the exception.
import java.io.File;
import java.io.FileReader;
If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
For example, if you have declared an array of size 5 in your program, and trying to call the 6th
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
If you compile and execute the above program you will get exception as shown below.
Java exception handling is managed via five keywords: try, catch, throw, throws,and finally.
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 before try block ends
}
To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. To illustrate how easily this can be done, the following
program includes a try block and a catch clause which processes the Arithmetic Exception
generated by the division-by-zero error:
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.");
}
}
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. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block. The following
example traps two different exception types:
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
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. Here is an example
that uses nested try statements:
OUTPUT:
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
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 is a sample program that creates and throws an exception. The handler that
catches the exception rethrows it to the outer handler.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This program gets two chances to deal with the same error. First, main( ) sets up an exception
context and then calls demoproc( ). The demoproc( ) method then sets up another exception-
handling context and immediately throws a new instance of NullPointerException, which is
caught on the next line. The exception is then rethrown. Here is the resulting output:
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
EXAMPLE:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
OUTPUT
inside throwOne
caught java.lang.IllegalAccessException: demo
finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. 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.
EXAMPLE:
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
OUTPUT:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally