0% found this document useful (0 votes)
15 views

Java Module5 Bplck205c

Module-5 of the Basis of Java Programming covers two main topics: Packages and Interfaces, and Exception Handling. It includes detailed explanations of defining packages, access protection, importing packages, and the fundamentals of exception handling, including the use of try, catch, throw, throws, and finally. The module also discusses exception types, uncaught exceptions, and provides examples to illustrate the concepts.

Uploaded by

pavxo23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Module5 Bplck205c

Module-5 of the Basis of Java Programming covers two main topics: Packages and Interfaces, and Exception Handling. It includes detailed explanations of defining packages, access protection, importing packages, and the fundamentals of exception handling, including the use of try, catch, throw, throws, and finally. The module also discusses exception types, uncaught exceptions, and provides examples to illustrate the concepts.

Uploaded by

pavxo23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Basis of Java Programming Module-5 BPLCK205C

MODULE-5

Chapter 1: Packages and Interfaces


Chapter 2: Exception Handling

Syllabus:
Chapter 1:
1. Packages
(i) Defining a Package
(ii) Finding Packages and CLASSPATH
(iii) A Short Package Example
2. Access Protection
(i) An Access Example
3. Importing Packages
4. Interfaces
(i) Defining an Interface
(ii) Implementing Interfaces
(iii) Interface Can Be Extended

Chapter 2:
1. Exception-Handling Fundamentals
2. Exception Types
3. Uncaught Exceptions
4. Using try and catch
(i) Displaying a Description of an Exception
5. Multiple catch Clauses
6. Nested try Statements
7. throw
8. throws
9. finally
10. Java’s Built-in Exceptions

Prof. Ashwini G Dept. of CS&E, MITT Page 1


Basis of Java Programming Module-5 BPLCK205C

Chapter 1: Packages
1. Packages
 Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.
 The package is both a naming and a visibility control mechanism. You can define
classes inside a package that are not accessible by code outside that package.
 You can also define class members that are only exposed to other members of the
same package.
 Benefits of packages:
 The classes in the packages can be easily reused.
 In the packages, classes are unique compared with other classes in the other
packages.
 Packages provide a way to hide classes thus prevent classes from accessing by
other programs.
 Packages also provide way to separate "design" from "coding".

(i) Defining a Package


 To create a package: simply 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.
 General form of the package statement:

// General form of package


package pkg;

 Here, pkg is the name of the package.


 For example, the following statement creates a package called MyPackage.
package MyPackage;

(ii) Finding Packages and CLASSPATH


 Packages are mirrored by the directories. This raises an import question: how
does Java-Run time system look for the packages that you create?
 The answer has three parts:
1. By default, Java Run time system uses the current working directory as its
starting point. Thus your package is in a subdirectory of your directory, it
will be found.

Prof. Ashwini G Dept. of CS&E, MITT Page 2


Basis of Java Programming Module-5 BPLCK205C

2. You can specify a directory path by setting the CLASSPATH environment


variable.
3. You can use - classpath option with java and javac to specify the path for
the classes.
(iii) A Short Package Example

// A simple package save it as: Balance.java


package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("Your balance is nil");
else
System.out.println("The name is" +name+ "and amount is $"+bal);
}
}

 Open a notepad or text editor, write the above code and save it as
"Balance.java" in the folder name "Mypackage”. Here, the package name and
subdirectory (folder) name must be same.
 This subdirectory (Folder) must be part of your main current directory (current
Folder) in which you write the main class PackTest1.java. That means the
"PackTest1.java" source file and "MyPackage" will be in the same directory
(Folder).

Prof. Ashwini G Dept. of CS&E, MITT Page 3


Basis of Java Programming Module-5 BPLCK205C

 The "Balance.java" file must be compiled to generate the ".class" file in the
same directory (folder), which will be accessed in another program by importing
the package.

//PackTest1.java
OUTPUT
import MyPackage.Balance;
The name is ABCD and amount is $1234.0
class PackTest1
{
public static void main(String[] args)
{
Balance b=new Balance ("ABCD",1234);
b.show();
}
}

2. Access Protection
 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.
 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.
 The three access specifiers, private, public, and protected, provide a variety of
ways to produce the many levels of access required by these categories.
Private Default Protected Public
Same class Yes Yes Yes Yes
Same package
No Yes Yes Yes
subclass
Same package
No Yes Yes Yes
non-subclass
Different package
No No Yes Yes
subclass
Different package
No No No Yes
non-subclass

Prof. Ashwini G Dept. of CS&E, MITT Page 4


Basis of Java Programming Module-5 BPLCK205C

(i) An Access Example


 Refer Lab program: 09

3. 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:

import pkg1[.pkg2].(classname|*);

 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 (.)
 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.*;
4. Interfaces
 Using interface, you can specify what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
 Java does not allow acquiring properties from more than one class, which we call it
as "multiple inheritance". We know that large number of real-life applications
require the use of multiple inheritance.
 Java provides an alternative approach known as "interface" to support the concept
of multiple inheritance.
(i) Defining an Interface
 An interface is basically a kind of class. Like classes, interfaces contain the
methods and variables but with major difference.
 The difference is those interfaces define only abstract methods and final fields.
This means that interface do not specify any code to implement these methods
and data fields contain only constants. It is the responsibility of the class that
implements an interface to define the code for these methods.
 The general form of an interface will be as follows:

interface Interface_Name
{
return-type method-name(parameter-list);
type final-varname=value;
}

Prof. Ashwini G Dept. of CS&E, MITT Page 5


Basis of Java Programming Module-5 BPLCK205C

(ii) Implementing Interfaces


 Once an interface has been defined, one or more classes can implement that
interface.
 To implement an interface, include the implements clause in a class definition,
and then create the methods defined by the interface.
 The general form of a class that includes the implements clause looks like this:

class classname [extends superclass] [implements interface]


{
//class-body
}

//Example program to demonstrate the use of interface


interface Area
{
static final double pi=3.14;
double compute(double x, double y);
}
//class definition starts here
class Rectangle implements Area
{
public double compute(double x, double y)
{
return(x*y);
}
}
class Circle implements Area
{
public double compute(double x, double y)
{
return(pi*x*x); OUTPUT
} The area of the rectangle is 200.0
} The area of the Circle is 314.0
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rec= new Rectangle();
Circle c=new Circle();
Area area;
area=rec; //reference double
double a=area.compute(10,20);
System.out.println("The area of the rectangle is "+a);
area=c;
a=area.compute(10,5);
System.out.println("The area of the Circle is "+a);
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 6


Basis of Java Programming Module-5 BPLCK205C

(iii) Interfaces Can Be Extended


 One interface can inherit another by use of the keyword extends.
 The syntax is the same as for inheriting classes. When a class implements an
interface that inherits another interface, it must provide implementations for all
methods defined within the interface inheritance chain.
 Following is an example:

// One interface can Extend another


interface A
{
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A
{
void meth3();
}
// This class must implement all of A and B
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class InterfaceTest
{
public static void main(String arg[])
{
MyClass ob = new MyClass(); OUTPUT
ob.meth1(); Implement meth1().
ob.meth2(); Implement meth2().
ob.meth3(); Implement meth3().
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 7


Basis of Java Programming Module-5 BPLCK205C

Chapter 2: Exception Handling

1. Exception Handling Fundamentals


 A Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a piece of code.
 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:
1. try
 Program statements that you want to monitor for exceptions are placed
within a try block.
2. catch
 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.
3. throw
 System-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw.
4. throws
 Any exception that is thrown out of a method must be specified as such by a
throws clause.
5. Finally
 Any code that absolutely must be executed after a try block completes is put
in a finally block.
 General form of exception-handling block:

try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
finally
{
// block of code to be executed after try block ends
}

 Here, ExceptionType is the type of exception that has occured

Prof. Ashwini G Dept. of CS&E, MITT Page 8


Basis of Java Programming Module-5 BPLCK205C

2. 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. This chapter
will not be dealing with exceptions of type Error, because these are typically created
in response to catastrophic failures that cannot usually be handled by your program.

3. Uncaught Exceptions
 Before you learn how to handle exceptions in your program, it is useful to see what
happens when you don’t handle them. 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;
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 9


Basis of Java Programming Module-5 BPLCK205C

 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 the above program we have not provided any exception handler, in this context
the exception is caught by the default handler. The default handler displays string
describing the exception.
 Here is the exception generated when this example is executed:

java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:6)

 Notice how the class name, Exc0; the method name, main; the filename, Exc0.java;
and the line number, 6, are all included in the simple stack trace. Also, notice that
the type of exception thrown is a subclass of Exception called
ArithmeticException, which more specifically describes what type of error
happened.

4. Using try and catch


 Although the default exception handler provided by the Java run-time system is
useful for debugging, you will usually want to handle an exception yourself. Doing so
provides two benefits.
 First, it allows you to fix the error.
 Second, it prevents the program from automatically terminating.
 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 that processes the ArithmeticException generated by the
division-by-zero error.
Note:
 println() statement inside the "try" will never execute, because once the
exception is raised the control is transferred to the "catch" block.
 Here is catch is not called, hence it will not return the control back to the "try"
block.
 The "try" and "catch" will form like a unit.
 A catch statement cannot handle the exception thrown by another "try" block.

Prof. Ashwini G Dept. of CS&E, MITT Page 10


Basis of Java Programming Module-5 BPLCK205C

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.");
}
}

OUTPUT
Division by zero.
After catch statement.

(i) 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.
 For example, the catch block in the preceding program can be rewritten like this:

catch (ArithmeticException e)
{
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}

 When this version is substituted in the program, and the program is run, each
divide-byzero error displays the following message:
Exception: java.lang.ArithmeticException: / by zero

Prof. Ashwini G Dept. of CS&E, MITT Page 11


Basis of Java Programming Module-5 BPLCK205C

5. 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:

// Demonstrate multiple catch statements.


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.");
}
}

OUTPUT 1:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

Prof. Ashwini G Dept. of CS&E, MITT Page 12


Basis of Java Programming Module-5 BPLCK205C

OUTPUT 2:
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
6. Nested try Statements
 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.
7. throw
 So far, you have only been catching exceptions that are thrown by the Java run-time
system implicitly.
 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;

// Demonstrate throw.
class ThrowDemo
{ OUTPUT
static void demoproc() java.lang.Exception: The value
{ of j cannot be Zero
try
{
int j=0;
if(j==0)
throw new Exception("The value of j cannot be Zero");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
demoproc();
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 13


Basis of Java Programming Module-5 BPLCK205C

8. throws
 If the function is not capable of handling the Exception then it can ask the calling
method to handle it by simply putting throws at the function declaration.
 It gives information to the caller method that there may be occur an exception so it
is better for the caller method to provide the exception handling code, so that the
normal flow can be maintained.
 The general form of a method that includes a throws clause:

type method-name(parameter-list) throws exception-list

class ThrowsDemo
{
static void throwone() throws IllegalAccessException
{
System.out.println("Inside Throw");
throw new IllegalAccessException("Demo");
}
public static void main(String args[])
{
try OUTPUT
{ Inside Throw
throwone(); Caughtjava.lang.IllegalAccessException: Demo
}
catch(IllegalAccessException e)
{
System.out.println("Caught"+e);
}
}
}

9. finally
 The finally block is always is executed. It is always used to perform housekeeping
operations such as releasing the resources, closing the files that already opened etc,.
 That means the statement that put inside the finally block are executed
compulsorily.
 It is always followed by the try-catch statements.
 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.
 The finally clause is optional. However, each try statement requires at least one
catch or a finally clause.
Prof. Ashwini G Dept. of CS&E, MITT Page 14
Basis of Java Programming Module-5 BPLCK205C

 Syntax
try
{
//statements
}
catch (Exception e)
{
//Handlers
}
finally
{
//statements
}

10. Java’s Built-in Exceptions


 Inside the standard package java.lang, Java defines several exception classes.

Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined
enumeration value
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state
llegalThreadStateException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds
NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference


NumberFormatException Invalid conversion of a string to a numeric
format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.
Table1: Java’s Unchecked RuntimeException Subclasses Defined in java.lang

Prof. Ashwini G Dept. of CS&E, MITT Page 15


Basis of Java Programming Module-5 BPLCK205C

Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
llegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class
or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist
Table2: Java’s Checked Exceptions Defined in java.lang

Prof. Ashwini G Dept. of CS&E, MITT Page 16

You might also like