You are on page 1of 39

Module 5- Packages and Interfaces

Exception handling
By
Mrs. Nagarathna Rajendra,
Department of Electronics and Telecommunication Engineering
Dayananda Sagar College of Engineering.
Packages
• A Package can be defined as a grouping of related types(classes,
interfaces)
• A package represents a directory that contains related group of
classes and interfaces.
• Packages are used in Java in order to prevent naming conflicts.
• There are two types of packages in Java. 1. Pre-defined
Packages(built-in) 2. User defined packages
Pre-defined Packages
Defining a Package(User defined 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.
• If you omit the package statement, the class names are put into the
default package, which has no name.
• This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package.
For example, the following statement creates a package called
MyPackage:
package MyPackage;
• Java uses file system directories to store packages.
• For example, the .class files for any classes you declare to be part of
MyPackage must be stored in a directory called MyPackage.
• 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:
package pkg1[.pkg2[.pkg3]];
• A package hierarchy must be reflected in the file system of your Java
development system. For example, a package declared as package
java.awt.image;
Creation of package- an example
package pack; // define a package called pack
public class Addition // include class Addition inside
this package
{
int x,y;
public Addition(int a, int b)
{
x=a;
y=b;
}
public void sum() { System.out.println("Sum :"+(x+y));
} }
Step 1: Save the above file with Addition.java
package pack;
public class Subtraction
// include class Subtraction inside this pack
{
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{ System.out.println("Difference :"+(x-y));
}
}
Step 2: Save the above file with Subtraction.java
Step 3: Compilation
To compile the java files use the following commands javac -d
directory_path name_of_the_java file Javac –d . name_of_the_java file

Note: -d is a switching options creates a new directory with package


name. Directory path represents in which location you want to create
package and . (dot) represents current working directory.
Access package from another package

There are three ways to use package in another package:


1. With fully qualified name.
class UseofPack {
public static void main(String arg[])
{
pack.Addition a=new pack.Addition(10,15);
a.sum();
pack.Subtraction s=new pack.Subtraction(20,15);
s.difference();
}
}
2. By importing: import package.classname;
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. By importing: 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 in Java
Interfaces
An interface is defined much like a class. This is the general form of an interface:
access interface name
{
type final-varname1 = value;
type final-varname2 = value;
…………………
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
…………………
}
Few key-points about interface:
 When no access specifier is mentioned for an interface, then it is treated as default and the
interface is only available to other members of the package in which it is declared. When an
interface is declared as public, the interface can be used by any other code.
• All the methods declared are abstract methods and hence are not defined inside interface. But, a
class implementing an interface should define all the methods declared inside the interface.
• Variables declared inside of interface are implicitly final and static, meaning they cannot be
changed by the implementing class.
• All the variables declared inside the interface must be initialized.
• All methods and variables are implicitly public
Implementing Interface
interface ICallback
{
void callback(int param);
}

class Client implements ICallback output: callback called with 42


{
public void callback(int p) //note public
{
System.out.println("callback called with " + p);
}
void test()
{
System.out.println(“ordinary method”);
}
}
class TestIface
{
public static void main(String args[])
{
ICallback c = new Client();
c.callback(42);
// c.test() //error!!
}}
interface ICallback
{
void callback(int param);
}
class Client implements ICallback
{
public void callback(int p) //note public
{
System.out.println("callback called with " + p);
}
}
class Client2 implements ICallback
{
public void callback(int p)
{
System.out.println("Another version of ICallBack");
System.out.println("p squared " + p*p);
}
}
class TestIface
{
public static void main(String args[])
{
ICallback x1=new Client(),;
ICallback x2=new Client2()};
x1.callback(5);
x2.callback(5); }} Output: callback called with 5 Another version of ICallBack p squared 25
Variables in interfaces
interface SharedConst
{
int FAIL=0; //these are final by default
int PASS=1;
}
class Result implements SharedConst
{
double mr;
Result(double m)
{
mr=m;
}
int res()
{
if(mr<40)
return FAIL;
else return PASS;
}
}
Extending interfaces
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
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().");
Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.


non-abstract methods. Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
interface AnimalEat { // example of multiple inheritance using interfaces
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}
Output
Animal is eating
Exceptions
Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a run-time error. In computer languages that do not support exception handling, errors must
be checked and handled manually—typically through the use of error codes. This approach is as
cumbersome as it is troublesome. Java’s exception handling avoids these problems and, in the process,
brings run-time error management into the object oriented world.
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. 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. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language
or the constraints of the Java execution environment. Manually generated exceptions are typically used
to report some error condition to the caller of a method.
Java exception handling is managed using five keywords:
 try: A suspected code segment is kept inside try block.
 catch: The remedy is written within catch block.
 throw: Whenever run-time error occurs, the code must throw an
exception.
 throws: If a method cannot handle any exception by its own and some
subsequent methods
needs to handle them, then a method can be specified with throws keyword
with its declaration.
 finally: block should contain the code to be executed after finishing
try-block.
Types of exceptions
• Built-in Exceptions
• Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to
explain certain error situations. Below is the list of important built-in exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or
greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or greater than the size of the
string
try
{
// block of code to monitor 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
}
Handling of uncaught exceptions
public class Testtrycatch1{
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
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. Since, in the above program, we have not supplied any
exception handlers of our own, so the exception is caught by the
default handler provided by the Java run-time system.
Any un-caught exception is handled by 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. Hence in this program prints reason for exception as
Exception in thread main java.lang.ArithmeticException:/ by zero
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...");
}}
1. Output : Exception in thread main java.lang.ArithmeticException:/ by
zero rest of the code..
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.");
}
}
Output:
Division by zero.
After catch statement
Multiple catches
class MultiCatch //example for multiple catch
{
public static void main(String args[])
{
try
{
int a = 0; // or take 0 as input from keyboard
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.");
}
}
Multiple errors with single catch
Multiple errors single catch example
finally
Uncaught Exceptions
Let us see, what happens if we do not handle exceptions.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
} Output:5 finally block is always executed rest of the code...
Throw
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw
keyword. The throw
keyword is mainly used to throw custom exception. We will see custom
exceptions later.
The syntax of java throw keyword is given below.
1. throw exception;
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
} } Output: Exception in thread main java.lang.ArithmeticException:not valid

You might also like