Unit IV
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> {
Or
There are mainly three reasons to use interface. They are given below.
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");
}
}
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.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
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) {
System.out.println("Enter username");
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
Syntax:
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:
or
or
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();
}
}
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:
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
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.
Output:
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.
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...");
}
}
Syntax:
}
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:
MyException(){ }
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: