You are on page 1of 29

UNIT 2

Interface, Packages and Exceptions

An interface declares a set of methods and their signatures. The methods that are declared in an
interface should not have implementation codes.
A Class that makes use of an interface should provide the codes for the methods declared in that
interface.

An interface is similar to a class, but there are several important differences

1. Methods should be only declared in an interface. In other words, the implementation


codes for all methods should not be provided in an interface.
2. All Methods that are declared in an interface are automatically public.
3. An interface does not have instance variables. But an interface can have constants. Such
constants will be inherited by the class that implements the interface

Rules for using Interface

• Methods inside Interface must not be static, final, native or strictfp.


• All variables declared inside interface are implicitly public static final
variables(constants).
• All methods declared inside Java Interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.
• Interface can extend one or more other interface.
• Interface cannot implement a class.
• Interface can be nested inside another interface.

Structure of an Interface

The general form of an interface is as follows

Interface name
{
type variable-name1=value1;
-
-
type variable n= value n;
return type method name1(args list 1);
-
-
return type method name n(args list n);
}

Implementation of Interface
A class shall make use of an interface by implementing the same. A class that implements an
interface will look as follows

class class name implements interface name


{
…….
…….
}

A class can implement more than one interface. In such case , the names of interfaces should be
separated by commas

class class name implements interface name1,….interface name n


{
…….
…….
}

A class shall extend another class and at the same time, it shall also implement one or more
interfaces.

Examples:

class circle extends shape implements Rect


{
…..
…..
}

class circle extends shape implements Rect, triangle


{
…..
…..
}

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.


Java Interface Examples
Example 1:

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Example 2
interface MyInterface
{
public void method1();
public void method2();
}
class XYZ implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new XYZ();
obj. method1();
}
}

Example 3

interface Moveable
{
int AVG-SPEED = 40;
void move();
}
class Vehicle implements Moveable
{
public void move()
{
System .out. print in ("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle();
vc.move();
}
}

Java Nested Interface


An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.

Syntax of nested interface which is declared within the interface


interface interface_name{
...
interface nested_interface_name{
...
}
}

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
o Nested interfaces are declared static implicitly.
Example of interface implementation

Interface Addtion
{
Void add();
}
Class Find implements Addition
{
Public void add()
{
int a=2,b=5,c;
c=a+b;
System.out.println(“Addition is =”+c);
}
Public static void main(String args[])
{
Find f=new Find();
f.add();
}
}

Interfaces supports Multiple inheritance

Though classes in java doesn't suppost multiple inheritance, but a class can implement
more than one interface.
Interface Moveable
{
boolean isMoveable();
}
Interface Rollable
{
boolean isRollable();
}
Class Tyre implements Moveable, Rollable
{
Int width;
boolean isMoveable()
{
return true;
}
boolean isRollable()
{
return true;
}
Public static void main(String args[])
{
Tyre tr=new
Tyre();
System.out.println
(tr.isMovable());
System.out.println
(tr.isRollable());
}
}

Inheritance Interface

Example

Import java.io.*;

Interface intface1

int j=10;

int j1();

Interface intface2

double k1();

Interface intface3 extends interface1,interafce2

boolean b1();

Class Sample implements intface3

{
public int j1()

return 100;

public double k1()

return 12.8;

Public Boolean l1()

return true;

public static void main( String args[])

Sample s=new sample();

System.out.println(s.j);

System.out.println(s.j1());

System.out.println(s.k1());

System.out.println(s.l1());

Packages

• It is a mechanism to encapsulate a group of classes, interfaces and sub packages.

• Package in java can be categorized in two types,

– Built-in package
• E.g. lang, awt, javax, swing, net, io, util, sql etc.

– User-defined package

– E.g. MyPack

• Advantage

– Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

– Java package provides access protection.

– Java package removes naming collision.

Creating a Package

• The keyword package helps to create a package.

• The package statement should be the first line in the source file.

• There can be only one package statement in each source file, and it applies to all types in
the file.

• Syntax

package package-name;
• E.g.

package myPack;

• E.g.

package mypack;

public class Simple

public static void main(String args[])

System.out.println("Welcome to package");

• Compile java package

– Syntax: javac -d directory javafilename

– E.g. javac -d . Simple.java

• Run java package program

– Syntax: java mypack.Class-name

– E.g. java mypack.Simple

• The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination.

• The dot( .) represents the current folder.

Access Modifiers

• The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.

• There are 4 types of access modifiers

– private

– default
– protected

– public

Private

• Create two classes A and Simple.

• A class contains private data member and private method.

• Try to access these private members from outside the class, so there is compile time error.

//A.Java

package pack;

class A{

private int data=40;

private void msg() {

System.out.println("Hello java");

//Sample.java

package myPack;

import pack.*;

public class Simple {

public static void main(String args[]) {

A obj=new A();
System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

Default

• Create two packages pack and mypack.

• We are accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.

//A.java

package pack;

class A {

default void msg(){

System.out.println("Hello");

//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

Protected
• Create the two packages muthuPack and myPack.

• The Sample class of muthuPack package is public, so can be accessed from outside the
package.

• But msg() method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.

• E.g.

package muthuPack;

public class Sample

protected void msg()

System.out.println("Hello");

package myPack;

import muthuPack.*;

class DemoSample extends Sample {

public static void main(String args[])

DemoSample obj=new DemoSample();

obj.msg();

}
Public

• The public access modifier is accessible everywhere.

• It has the widest scope among all other modifiers.

• E.g.

package myAddPack;

public class Add

public void sum()

int x, y;

x=10;

y=20;

System.out.println("Sum is: "+(x+y));

package demoPack;
import myAddPack.*;

class AddDemo {

public static void main(String args[])

Add obj=new Add();

obj.sum();

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.

1. 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.

//A.java
package pack;

public class A {

public void msg() {

System.out.println("Hello");

//B.java

package mypack;

import pack.*;

class B {

public static void main(String args[]) {

A obj = new A();

obj.msg();

2. Using packagename.classname

• If you import package.classname then only declared class of this package will be
accessible.

//A.java

package pack;

public class A{

public void msg(){

System.out.println("Hello");

}
//B.java

package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

3. Using fully qualified name

• If you use fully qualified name then only declared class of this package will be accessible.

• Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

//A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//B.java

package mypack;

class B{

public static void main(String args[]){

//using fully qualified name

pack.A obj = new pack.A();

obj.msg();
}

Sequence of the program must be package then import then class.

Subpackages

• Package inside the package is called the subpackage. It should be created to categorize the
package further.

– E.g. Sun has definded a package named java that contains many classes like
System, String, Reader, Writer, Socket etc.

– These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc
and so on.

– So, Sun has subcategorized the java package into subpackages such as lang, net, io
etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.

• E.g.

//Class_A.java

package myFirst;

public class Class_A

public void hi()

System.out.println("Hi...");
}

//Class_B.java

package myFirst.mySecond;

import myFirst.*;

public class Class_B

public void hello()

System.out.println("Hello...");

//Class_C.java

package myFirst.mySecond.myThird;

import myFirst.mySecond.*;

public class Class_C

public void morning()

System.out.println("Good Morning...");

//DemoPackage.java

package mySubPack;

import myFirst.mySecond.myThird.*;
import myFirst.mySecond.*;

import myFirst.*;

class DemoPackage

public static void main(String args[])

Class_C objc=new Class_C();

objc.morning();

Class_B objb=new Class_B();

objb.hello();

Class_A obja=new Class_A();

obja.hi();

}
Exception Handling

What is an exception?

An Exception can be anything which interrupts the normal flow of the program. When an
exception occurs program processing gets terminated and doesn’t continue further. In such cases
we get a system generated error message. The good thing about exceptions is that they can be
handled. We will cover the handling part later in this same tutorial.

When an exception can occur?


Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known
Compile-time exceptions).

Reasons for Exceptions


There can be several reasons for an exception. For example, following situations can cause an
exception – Opening a non-existing file, Network connection problem, Operands being
manipulated are out of prescribed ranges, class file missing which was supposed to be loaded and
so on.

Difference between error and exception

Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal circumstances
by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –

• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
Advantages of Exception Handling

• Exception handling allows us to control the normal flow of the program by using
exception handling in program.
• It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
• It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then program execution can
get terminated and system prints a non user friendly error message.

Types of exceptions

There are two types of exceptions

1)Checked exceptions
2)Unchecked exceptions

Below is a brief about each however if you want a detailed tutorial with examples then you can
refer Checked and Unchecked exceptions in Java.

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, it will give compilation error.

Examples of Checked Exceptions :-


ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check
whether the programmer has handled them or not but it’s the duty of the programmer to handle
these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not
check to see if a method handles or throws these exceptions.

Examples of Unchecked Exceptions:-


ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.

What is Try Block?

The try block contains a block of program statements within which an exception might occur. A
try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must followed by a Catch block or Finally block or both.
Syntax of try block

try{
//statements that may cause an exception
}
What is Catch Block?

A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic
exception occurs in try block then the statements enclosed in catch block for arithmetic
exception executes.

Syntax of try catch in java

try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}

Flow of try catch block

1. If an exception occurs in try block then the control of execution is passed to the catch
block from try block. The exception is caught up by the corresponding catch block. A
single try block can have multiple catch statements associated with it, but each catch block
can be defined for only one exception class. The program can also contain nested try-
catch-finally blocks.
2. After the execution of all the try blocks, the code inside the finally block executes. It is
not mandatory to include a finally block at all, but if you do, it will run regardless of
whether an exception was thrown and handled by the try and catch blocks.
An example of Try catch in Java

class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:

Error: Don't divide a number by zero


I'm out of try-catch block in Java.

Multiple catch blocks in Java

1. A try block can have any number of catch blocks.


2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:

catch(Exception e){
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block should
be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and
the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.

Example of Multiple catch blocks

class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:

Warning: ArithmeticException
Out of try-catch block...

Example 1: Arithmetic exception

Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when an integer is
divided by zero.

class ExceptionDemo1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result = " +output);
}
catch(ArithmeticException e){
System.out.println ("Arithmetic Exception: You can't divide an integer by 0");
}
}
}
Output of above program:

Arithmetic Exception: You can't divide an integer by 0

Explanation: In the above example I’ve divided an integer by a zero and due to
which ArithmeticException is thrown.

Example 2: ArrayIndexOutOfBounds Exception

Class: Java.lang.ArrayIndexOutOfBoundsException
This is a built in class present in java.lang package. This exception occurs when the referenced
element does not exist in the array. For e.g. If array is having only 5 elements and we are trying
to display 7th element then it would throw this exception.

Example:

class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}

Output:

ArrayIndexOutOfBounds

In the above example the array is initialized to store only 10 elements indexes 0 to 9. Since we
are invoking index 11 that’s why it is throwing this exception.

Example 3: NumberFormat Exception

Class: Java.lang.NumberFormatException

The object of the above built-in class gets created whenever a string is parsed to any numeric
variable.
For E.g. The statement int num=Integer.parseInt ("XYZ") ; would
throw NumberFormatException because String “XYZ” cannot be parsed to int.

Complete Code:

class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:

Number format exception occurred

Example 4: StringIndexOutOfBound Exception

Class: Java.lang.StringIndexOutOfBoundsException

• An object of this class gets created whenever an index is invoked of a string, which is not
in the range.
• Each character of a string object is stored in a particular index starting from 0.
• To get a character present in a particular index of a string we can use a method
charAt(int) of java.lang.String where int argument is the index.
E.g.

class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="easysteps2buildwebsite";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}

Output:
22
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the String.

Example 5: NullPointer Exception

Class: Java.lang.NullPointer Exception

An object of this class gets created whenever a member is invoked with a “null” object.

Example:

package beginnersbook.com;
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}

Output:

NullPointerException..

Here, length() is the function, which should be used on an object. However in the above
example String object str is null so it is not an object due to
which NullPointerException occurred.

User Defined Exception Handling Mechanism

Syntax:

try
{
.
.
.
}
catch(ExceptionType 1 parameters1)
{
.
.
.
.}
catch(Exception Type2 Parameter 2)
{
.
.
.
}
finally
{
.
.
.}

Example

class ExceptionDemo1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result = " +output);
}
catch(ArithmeticException e){
System.out.println ("Arithmetic Exception: You can't divide an integer by 0");
}
finally
{
System.out.println(“Finally Block”);
}
}

Output:
Arithmetic Exception: You can't divide an integer by 0
Finally Block

Throws CLAUSE

Import java.io.*;
Class test
{
public static void main(String args[])
{
try{
System.out.print(“Enter a String”);
String s=valueReader1();
System.out.println("Result = " +s);
}
catch(IOException e){
System.out.println ("IO error has occurred");
}
{
Static string valueReader1() throws IOException
{
InputStreamReader reader=new InputStreamReader(System.in);
BufferedReader input=new BufferedReader(reader);
String text=input.readLine();
return text;}}

You might also like