Module 4 - Object Oriented Programming with JAVA (BCS306A)
CHAPTER 9: Packages
Packages: Packages, Packages and Member Access, Importing Packages
Packages:
In Java, a package is a way to organize and manage a group of related classes and interfaces. Packages
help in avoiding naming conflicts, organizing code, and providing a clear hierarchical structure to your
application.
Package Declaration: At the beginning of a Java source file, we can declare which package the file
belongs to, using the package keyword followed by the package name.
General form of the package statement:
Here, mypack is the name of the package.
Java uses file system directories to store packages. For example, the .class files for any classes you
declare to be part of myPack must be stored in a directory called myPack. Remember that case is
significant, and the directory name must match the package name exactly. 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. It does not exclude other classes in other files from being part of that same package. Most
real-world packages are spread across many files. You can create a hierarchy of packages. To do so,
simply separate each package name from the one above it by use of a period. The general form of a
multileveled package statement is shown here:
A package hierarchy must be reflected in the file system of your Java development system. For example,
a package declared as,
Needs to be stored in java\awt\image in a Windows environment.
Finding Packages and CLASSPATH
What is CLASSPATH:
CLASSPATH is an environment variable that tells the Java Virtual Machine (JVM) and Java
compiler where to find user-defined classes and packages.
It can be set either as a system-wide variable or per individual application.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
How does CLASSPATH work?
When compiling Java code, the compiler looks for classes and packages referenced in your code.
It searches for these classes and packages in the directories specified in the CLASSPATH.
Similarly, when running a Java application, the JVM looks for the required classes and packages
in the directories specified in the CLASSPATH.
If the required class or package is not found in any of the directories specified in the
CLASSPATH, the JVM or compiler will throw a "class not found" error.
Sample Program:
Output:
Access Protection:
Java provides many levels of protection to allow fine-grained control over the visibility of variables and
methods within classes, subclasses, and packages. 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:
Subclasses in the same package
Non-subclasses in the same package
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Subclasses in different packages
Classes that are neither in the same package nor subclasses
The three access modifiers, private, public, and protected, provide a variety of ways to produce the many
levels of access required by these categories. Table 9-1 sums up the interactions.
Another Sample Program:
Output:
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Output:
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
CHAPTER 10: Exception Handling
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.
Exception-Handling Fundamentals
Exception handling in Java is crucial for writing robust and fault-tolerant code.
Types of Exceptions:
1. Checked Exceptions (compile-time): These are checked at compile-time. Methods must either
catch these exceptions or declare that they may throw them using the throws clause.
2. Unchecked Exceptions (Runtime Exceptions): These are not checked at compile-time. Common
examples include NullPointerException, ArrayIndexOutOfBoundsException, etc.
3. Errors: These are typically caused by the environment in which the application is running rather
than a programming mistake. For example, OutOfMemoryError, StackOverflowError, etc.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
1. try: The try block encloses the code that might throw an exception. It's used to define a block of
code where exceptions might occur.
2. catch: The catch block follows the try block and is used to handle exceptions. If an exception
occurs within the try block, it's caught by the corresponding catch block, which contains the code
to handle the exception.
3. throw: The throw keyword is used to manually throw an exception within a method. It's typically
used when a specific condition occurs that warrants an exception, allowing the programmer to
create custom exceptions or throw predefined ones.
4. throws: The throws keyword is used in method signatures to declare that the method might throw
certain types of exceptions. It's used to indicate which exceptions a method can potentially throw,
allowing callers to handle them appropriately.
5. finally: The finally block is used to define a block of code that will always be executed, regardless
of whether an exception occurs or not. It's commonly used for cleanup tasks, such as closing
resources like files or database connections, ensuring they are properly released.
These five keywords together form the foundation of exception handling in Java, allowing developers to
write code that gracefully handles unexpected situations and maintains the stability and reliability of their
applications.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
This is the general form of an exception-handling block:
Here, ExceptionType is the type of exception that has occurred.
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.
1. 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.
2. 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.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Uncaught Exceptions
Before learning how to handle exceptions in java programs, it is useful to see what happens when user
don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero
error:
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.
Here is the exception generated when this example is executed:
Using try and catch
Although the default exception handler provided by the Java run-time system is useful for debugging.
Handle an exception manually provides two benefits.
First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
The following program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Output:
Here, the call to println( ) inside the try block is never executed. Once an exception is thrown, program
control transfers out of the try block into the catch block. Put differently, catch is not “called,” so
execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not
displayed. Once the catch statement has executed, program control.
A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements
specified by the immediately preceding try statement. A catch statement cannot catch an exception
thrown by another try statement (except in the case of nested try statements, described shortly). The
statements that are protected by try must be surrounded by curly braces. (That is, they must be within a
block.) You cannot use try on a single statement.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Output:
Displaying a Description of an Exception
Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of
the exception. You can display this description in a println( ) statement by simply passing the exception as an
argument.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Output:
Multiple catch Clauses
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:
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Output:
Output:
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
When you use multiple catch statements, it is important to remember that exception subclasses must come before
any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type
plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. Further, in Java,
unreachable code is an error. For example, consider the following program:
If you try to compile this program, you will receive an error message stating that the second catch statement is
unreachable because the exception has already been caught. Since ArithmeticException is a subclass of Exception,
the first catch statement will handle all Exception-based errors, including ArithmeticException. This means that the
second catch statement will never execute. To fix the problem, reverse the order of the catch statements.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block of another try. When an
exception occurs within an inner try block and there's no corresponding catch block to handle it, the
exception is propagated to the outer try block. This process continues until either a catch block is found
that can handle the exception or until all nested try blocks are exhausted. If no catch block is found, the
Java runtime system handles the exception. This mechanism provides flexibility in handling exceptions at
different levels of code execution.
Dept. of AIML, GMIT, Davangere
Module 4 - Object Oriented Programming with JAVA (BCS306A)
throw
In Java, the throw statement is used to explicitly throw an exception. It's typically used within methods or
constructors to signal that an exceptional condition has occurred.
Here's a basic syntax example:
Dept. of AIML, GMIT, Davangere