0% found this document useful (0 votes)
52 views23 pages

Unit IV

The document discusses interfaces, packages, and exception handling in Java. It defines interfaces as blueprints for classes that can only contain abstract methods. Packages are used to organize classes and interfaces to avoid naming collisions. There are two main types of exceptions - checked exceptions that must be declared and unchecked exceptions. The document provides examples and explanations of interfaces, packages, and how to handle exceptions in Java code using try, catch, and finally blocks.

Uploaded by

dhruwchanchal31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views23 pages

Unit IV

The document discusses interfaces, packages, and exception handling in Java. It defines interfaces as blueprints for classes that can only contain abstract methods. Packages are used to organize classes and interfaces to avoid naming collisions. There are two main types of exceptions - checked exceptions that must be declared and unchecked exceptions. The document provides examples and explanations of interfaces, packages, and how to handle exceptions in Java code using try, catch, and finally blocks.

Uploaded by

dhruwchanchal31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit IV

 Interface
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in java.

Syntax :

interface <interface_name> {

// declare constant fields


// declare methods that abstract
// by default.
}

Or

interface <interface name>

final or static data type var=value;

return type <method name>(parameter list);

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.
To declare an interface, use interface keyword. That means all the methods in an
interface are declared with an empty body and are public and all fields are public,
static and final by default. A class that implements an interface must implement
all the methods declared in the interface. To implement interface
use implements keyword.

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 In1
{
final int a = 10;
default void display()
{
System.out.println("hello");
}
}

// A class that implements the interface.


class TestClass implements In1
{
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
}
}

Difference between Class and Interface


Class Interface
In class, you can instantiate variable and In an interface, you can’t instantiate
create an object. variable and create an object.
Class can contain concrete(with The interface cannot contain
implementation) methods concrete(with implementation) methods
The access specifiers used with classes In Interface only one specifier is used-
are private, protected and public. Public.

 Package
PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps
organize your classes into a folder structure and make it easy to locate and use
them. More importantly, it helps improve code reusability.

Each package in Java has its unique name and organizes its classes and interfaces
into a separate namespace, or name group.

Advantage of Java Package

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

2) Java package provides access protection.

3) Java package removes naming collision.


Types of packages:

Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines
primitive data types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

Example:

import java.util.Scanner;

class MyClass {
public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

User defined Package

Just like built in packages, the users of the java can also create their own package,
they are called as user defined package. User defined packages can also be
imported in the same way as the built in packages.

Naming Conventions

Packages can be named using the standard java naming rules. By convention
however packages begin with lowercase letters. We know that all class name,
again by conventions, begin with uppercase letters.

Example:

double y = java.lang.Math.sqrt(x);

Creating a package

To create a package the keyword package is used:

Syntax:

package packagename; // to create a package


package packagename.subpackagename; // To create a sub package within a
package

Importing and Accessing a Package

We use the import statement when there are many references to a particular
package pr the package name is too long.

The same approach is used to access the user defined packages as well. The
import statement is used to search a list of package for a particular class. The
general form of import statement is:

Syntax:

import packagename.classname; // to import a particular class

or

import packagename.package2.packagen.classname; //to import a particular


class in subpackage

or

import packagename.*; // to import all classes in of the package

compile java package


syntax

javac -d directory javafilename;

Example

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
Compilation

javac -d . A.java

//save by B.java
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Compile: javac B.java


Run: java B

Output:
Hello

 Exception Handling
The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can be
maintained.
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.
Exception
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
Types of Errors:

1. Compile time error


2. Run time error

Compile time error


Compile-time errors are the errors that occurred when we write the
wrong syntax. If we write the wrong syntax or semantics of any
programming language, then the compile-time errors will be thrown
by the compiler. The compiler will not allow to run the program until
all the errors are removed from the program. When all the errors are
removed from the program, then the compiler will generate the
executable file.
Run time error
The runtime errors are the errors that occur during the execution and
after compilation. The examples of runtime errors are division by zero,
etc. These errors are not easy to detect as the compiler does not point
to these errors.

Exceptions:
An exception is a condition that is caused by a run time error in the
program. When Java interpreter encounters an error such as divide by
zero, it creates an exception object and throws it.
There are mainly two types of exceptions: checked and unchecked.
1. Checked or caught Exception
2. Unchecked or uncaught Exception

 Checked or caught Exception

The exception that are checked at compilation time by the Java


compiler are called checked exception.
These exceptions are caught at compile time.
Ex. IOException, SQLException.

 UnChecked or uncaught Exception

These exceptions that are checked by the JVM are called Unchecked
Exceptions.
These exceptions are considered as unrecoverable and the
programmer cannot do anything when they occur.
Ex. ArithmeticException, ArrayIndexOutOfBoundsException.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception


hierarchy inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:
Exception Handling
When there is exception the user data may be corrupted. This should
be tackled by the programmer by carefully designing the programs.
For this, we should perform the following steps:
Step 1: The programmer should observe the statements in his code
where there may be possibility of exceptions. Such statement should
be written inside a try block.
Syntax of try block:
try{
statements;
}
A try block contain the statements that may generate exception. If
exception occurs and an object of that exception class type is created
and thrown from try block.
Step 2:
The next step is writing a catch block where we display the exception
details to the user. The programmer should display the message
regarding what can be done to avoid this error.
Syntax:
catch(Exceptionclass ref){
Statements’;
}
Catch block: The Exception object which is thrown from try block is
caught in this block.
The statements related to exception handling may be placed in the
catch block.
Example for try and catch block:

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

Step 3:
Lastly the programmer should perform clean up the threads. The
programmer should write this code in the finally block.
Syntax:
finally{
Statements;
}

Finally block:
It is a block used with try catch block. It is placed after all the catch
block.
The statement inside the finally block is executed in any condition i.e.
if exception occur or if not.
These blocks are used for compulsory statements like:
1. Closing a connection
2. Closing the files
3. Releasing the resources.

Example of try catch and finally block

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Nested try block:


In Java, using a try block inside another try block is permitted. It is
called as nested try block. Every statement that we enter a statement
in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try
block can handle the ArithemeticException (division by zero).

Syntax:

//main try block


try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}

Example:
Exception in thread
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}

Output:
Multiple catch block:
For a single try block, multiple catch block can be managed. The catch
block for the child class should be placed first to exception hierarchy.
Example:
class Multicatch{
public static void main(String arg[]){
try{
int a = Integer.parseInt(arg[0]);
int b = Integer.parseInt(arg[1]);
int c = a/b;
System.out.println(“Sum = ”+c);
}
catch(ArrayIndexOutOfBoundsException a1){
System.out.println(“Enter two values ”);
}
catch(ArithmeticException a2){
System.out.println(“Second value cannot be zero ”);
}
catch(Exception e){
System.out.println(“Other error ”+e);
}
}
}

throw clause
There is also throw statement present in java to throw an exception
explicitly and catch it.
1. It is used to transfer the exception object from one block to
another explicitly.
2. It can manage only one exception at a time
3. It can be used for user defined exception also.
4. The exception object thrown will be managed by program.
5. It can be used to create exception object also.
throws exception:
1. It is used to transfer the exception objects from program to JVM
handles
2. It can manage more than one exception at a time.
3. It is used with methods.
4. The exception object thrown will be managed by JVM.
Types of Exception:

Common Built in Exceptions


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

User defined Exception:


Sometimes, the built-in exceptions in Java are .not able to describe a
certain situation. In such cases, like the built-in exceptions; the
user(programmer)can also create his own exceptions which are called
'user-defined exceptions'. The following steps are followed in creation
of user-defined exceptions:
1. The user should create an exception class as a subclass to
Exception class. Since all exceptions are subclasses of Exception
class, the user should also make his class a subclass to it. This is
done as:

class MyException extends Exception


2. The user can write a default constructor in his own exception
class. He -can use it, in case he does not want to store any
exception details. If the user does not want to create an emp.
object to his exception class, he can eliminate writing the default
constructor.

MyException(){ }

3. The user can create a parameterized constructor with a string as


a parameter. He can use to store exception details. He can call
super class (Exception) constructor from this and se the string
there.

MyException(String str){
super(str);
}

4. When the user wants to raise his own exception, he should create
an object to his excep . class and throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
Example:

You might also like