Total Pageviews

Thursday, 28 July 2011

Exception Handling

Java exception is an object which is created at the run time due to some error present in the piece of code.Whenever an exceptional condition occurs an object is created and it is thrown in the method that caused the error . The method may handle the object or pass it on.This objects are caught by another method and processed.The main cause behind the generation of exception(object) is due to syntactical error in the piece of code.It can also arise due to the violation of user defined condition in the program.
Java exception handling is nothing but a way to deal with the run time errors and how they can be corrected or skipped depending upon users choice.Exception handling is done with the help of five keywords try,catch,throw,throws and finally.
1.try - This keyword is used to check whether a block of code contains exception or not.
   try{
    //code;
      }
2. catch - If java finds any exception in the try block then it stops there itself and dose not executes further. Java shows an error message at the run time, so instead of getting compilers message we can use catch keyword to show our own message for making our program more user friendly.

   try{
    //code;   
       }catch(exception_type reference){
    //code;
      }
3. throw - system generated exception are automatically thrown by java run time sytem. To do this manually , throw keyword is used.

    throw throwable_instance;

4. throws - Any exception thrown out of a method is specified with the help of throws clause.
    type method_name(parameter_list) throws eception_type{
         //code;
     }
5. finally - Any code written under the finally is executed after the try block is over.It does not depends upon the exception present in the try block.
    try{
    //code;
    }catch(exception_type reference){
    //code;
    }
    finally{
    //code;
    }

example

import java.io.*;

//demonstrate multicatch system

class catch1 {
    public static void main(String arg[]){
        try{
            int a = arg.length;
            System.out.println("a =" +a);
            int b = 42/a;
            int c[] = {1};
            c[42]=99;
           }
                catch(ArithmeticException e)
                {
            System.out.println("divide c by 0:" + e);
                } catch(Exception e){
            System.out.println("array index oob : "+ e);
           }
                System.out.println("after try/catch blocks.");
         }
                }


explaination :Here we have created a class named as catch1 in which we have defined a static main class. The main method has a try block code contains two types of exception(error), (i) ArithemeticException and, (ii) ArrayOutOfBoundException . There are two catch blocks which will catch the two exceptions, the first one will catch ArithemeticException and the second will catch all kinds of exception(error) as "Exception"(class name) is the base class for all run time exception generated.

We have discussed about try and catch keyword , now lets deal with the other three keywords throw , throws and finally.
throw
Till now we were catching the exception at the run time. We can also throw exception explicitly from our program, with the help of throw keyword.
syntax
throw Throwable_instance;

throwable_instance is an object of type throwable class or sub-class of throwable.Primitive types like int , char and non-Throwable classes , such as string and object,cannot be used as exception.
There are two ways of creating a throwable object either by passing as a reference in the parameter of catch statement or with the help of new operator.


class demo{
   static void call(){
    try
    {
        throw new ArithmeticException("error"); //created a instance of type throwable
    }catch(ArithmeticException e){
        System.out.println("error found in call()");
        throw e; //rethrow the exception as a reference
    }
    }

public static void main(String args[]){
    try{
        call();
     }catch(ArithmeticException e){
         System.out.print("recaught :" + e);
     }
    }
}


Explaination :In the above program , we are handling the Arithmetic type exception in two ways , first in the call() method and second in the main() method.call() method has a try block in which a instance is generated of type ArithmeticException , and then it is thrown . The catch block in the call() method catches the Exception and then it enters the catch block for its execution, here in the catch block it is again the reference of ArithmeticException is thrown. Now in second case i.e in the main() method the call() method is being called within try block, and then it is passed to the catch block as normal try and catch.
The reference "e" thrown in the catch block of call() method creates another exception in the try block of main() method , then it is handled by the respective catch block giving "recaught : error" as output. "error" was passed as a argument in the ArithmeticException type instance.



throws
It is a kind of passing message to the caller of a function that a specific type of message can be generated by the called method , which the called method does not handle. So the callers can take care of the exception and proceed further. syntactically this throws clause is defined with the method declaration statement.

type method_name(parameter list) throws exception list{
//body of method;
}

Here exception list is a comma separated list of the exceptions that a method can throw.

finally
We know that exception causes abrupt execution of a program i.e whenever java finds any kind of exception it stops execution there itself . This can create problem in many cases.Let us take an example of a record file , you can perform many functions on it like update , delete etc. but at the end you have to close this file. In java if it finds any exception in the try block of deletion code it will throw that exception and stop , but your file remains open .The opened file need to be closed before proceeding further.This type of problems can be solved with the help of finally keyword.
finally keyword creates a block of code that will be executed after a try/catch block has completed and before the code following the try and catch block.The finally block will execute whether or not an exception is thrown.If an exception is thrown , the finally block will execute even if or not the catch block excepton matches with the thrown exception.However , finally block is optional and it does not delay the execution tome. It returns with the completion of try/catch block.

// demonstrate finally
class FinallyDemo{
static void procA(){
try{
System.out.println("inside procA");
throw new RuntimeException("demo");
}finally{
System.out.println("procA's finally");
}
}
static void procB(){
try{
System.out.println("inside procB");
return;
}finally{
System.out.println("procB's finally");
}
}
static void procC(){
try{
System.out.println("inside procC");
}finally{
System.out.println("procC's finally");
}
}

public static void main(String args[]){
try{
procA();
}catch(Exception e){
system.out.println("Exception caught");
}
procB();
procC();
}
}


Types of Exception

All the exception types are subclass of the built in class THROWABLE. Throwable is then sub classed into two distinct types i.e exception and error. The exception class is used for exceptional conditions that user should catch. There is an important subclass of exception called RuntimeException.Exception of this types are automatically defined for the program that we write and include things such as division by zero and array indexing.
Error is the second sub class of the throwable class, which defines exception that are not expected to be caught at normal circumstances by our program.Exception of type Error are used by the java run-time system to indicate errors having to di with the run-time environment itself.Stack overflow is an example of such an error.
Java built in exception are divided into two i.e. checked exception and unchecked exception.
checked exception are the compile time exception , i.e. the compiler forces us to handle this exception. eg: IOException
unchecked exception are those that are not forced by the compiler to handle the exception. eg : ArithmeticException.

Thursday, 7 July 2011

Interface

Interface is a keyword which helps us to create a pure abstract class. It consist of variables and a method without body. The syntax of abstract class and the interface are very similar , they both have variables and methods without body . Still there are some difference between them , the abstract class can consist of instance variables and both types of method i.e abstract method (without body ) and methods having body.Whereas , interface consist of variables that are treated as constant and consist of only abstract type methods i.e without body.

syntax :
for abstract class
abstract class class_name{
//access data type variables;
//access return type method_name();
//access return type method_name(parameter list){
//body of method;
}
}
for interface
interface class class_name{
//access final static data type variables;
//access return type method_name();
}

The variables declared in interface are treated as constant, they are declared with the helo of final and static keyword.Interface is very much helpful in creating multiple inheritance type relationship between the classes. This multiple inheritance cannot be achieved without the help of interface, as java dose not support multiple inheritance.

//creating interface
public interface rahul{
int age = 21 ;
public void show();
}
//implementing interface
class mohan implements rahul{
    public void show(){
        System.out.println("Hii my name is rahul.")
    }
    public void show2(){
         System.out.println("Hii my name is mohan.")
    }
}
class friends{
    public static void main(String args[]){
        mohan a1 = new mohan();
        a1.show();
        a1.show2();
    }
}

In the above program we have created an interface "rahul" in which we have declared one integer type variable , and a method show() without any body. Now this interface is implemented  by the class mohan by the use of implements keyword.

Interface can be extended.
One interface can also inherit resources from other interface by the use of extends keyword.The syntax is same as inheriting a class.

interface <name1>{
//access return type variables;
//access return type method();
}

interface <name2> extends interface <name1>{
//access return type variables;
//access return type method();
}

//example of a extending an interface
 interface apple{
    public int area();
    public void show();

}
 interface mango extends apple{
    public int volume();
    public void show2();
}
class input implements mango{
  public  int length, width ,height,orange,grapes;
   public input(int x, int y , int z ){
       length = x ;
       width = y ;
       height = z ;
   }
   public int area(){
   orange = length*width;
   return orange;
   }
   public void show(){
       System.out.println("Length = " + length +" width = " +width + " height = " +height);
       System.out.println(" area = " + orange);
     
   }
   public int volume(){
        grapes = length*width*height;
       return grapes;

   }
   public void show2(){
       System.out.println( " volume = " + grapes);
   }
}
class demo{
    public static void main(String args[]){
        input a1 = new input(4,6,8);
        a1.area();
        a1.show();
        a1.volume();
        a1.show2();
    }
}

Monday, 4 July 2011

Package

In simple words , we can say that package are the folders which contains many classes under one package(folder) name. Package is both naming and a visibility control mechanism.First let us deal with naming part , It creates a name space where classes are stored, and it helps us to resolve class name and method name ambiguity.Second part is the Visibility,the classes stored in the package, are inaccessible by the codes outside the package i.e the classes and the member classes are accessible by the members of the same  package only.
We use the package command to define a name space where classes are stored.If we don't use the package command then it is considered as a default package,which has no name.

package ABC;

Java uses file system directories to store the packages.In the above statement .class files of any class declared to be a part of package ABC must be stored in a directory called ABC.We can store more than one file under the same package name. The Package statement only tells us that the specified class belongs to that package.It dose not harm other files from being the part of that same package.

we can create hierarchy of packages.What we have to do is simply separate each package name by the use of period.
package abc[[.efg][.hij]];

example : java.awt.image;
A package declared above must be stored in the java\awt\image in a windows environment.

//create a package
package NSEC;

public class Fees{
String name;
public int roll , cls;
public Fees(String n,int x , int y){
name = n;
roll = x;
cls = y;
}
void show(){
System.out.println(" name " + name +  " class " + cls + " " + " roll_no " + roll );
}}
public class Depart extends Fees{
int months;
long pay;
public Depart(String n , int x, int y , int z, long p){
super(n, x, y );
months = z;
pay = p;
}
void show(){
System.out.println("your fees structure ");
System.out.println( " name " + name + "class " + cls + " " + " roll_no " + roll);
System.out.println("you have to pay " + pay +"$" + " for " + months + " months");
}
}
class accounts{
public static void main(String aregs[]){
Fees sem =  new Fees("BALA" ,46,6);
Depart cse = new Depart("Biplov " , 43, 5, 6 , 28760);
Fees ref;
ref =sem;
ref.show();
ref =cse ;
ref.show();
}
}
In the above program, we have created a package NSEC, and we have stored the .java and .class files in the NSEC directory.

Importing package.
We know that classes and member classes stored in a package are inaccessible outside the package.So, we have to call a package name to access the classes and other files stored in it. This can be done with the help of import statement.
import pkg1[.pkg2](.classname|*);






* is used to import the entire package.
All the standard classes are stored in package called java.The basic language functions are stored in a package inside of a java.lang. Whenever we create a java program ,the java compiler imports the java.lang package implicitly.

//importing the above NSEC package..
import NSEC.*;
class prac{
    public static void main(String args[]){
Depart  a2 = new Depart("biplov" , 43, 5, 6, 28760);
a2.show(); //using the show method defined in the Depart class , which is a part of NSEC package
    }
}







Friday, 1 July 2011

Method overriding, Dynamic Method Dispatch ,Abstract Class

Method Overriding
When a method in the sub class have the same name and same type of signature as a method in super class, then the method in the sub class is said to overwrite method in super class. When a overridden method is called from within a sub class, it always refer to the method defined in the sub class.The method defined in the super class will be hidden , and we need super keyword to call the method present in the super class.

//example of method overriding
class father{
public int length ,width ;
public  father(int x , int y){
 length = x;
 width = y;
 }
 public void show(){
     System.out.println(" length : " + length + " " + "width : " +width);
 }
}
class son extends father{
    int height;
  son(int x , int y, int z){
  super(x,y);
  height = z;
  }
  public int volume(){
      return height*width*length ;
}
public void show(){
System.out.println("length :" + length + " " + "width :" + width + " " + "height : " + height);
System.out.println("overridden method");
}}
class see{
    public static void main(String args[]){
    son akash = new son(4,5,6);
    int p = akash.volume();
    System.out.println("volume :" + p );
    akash.show();
    }
}


Dynamic Method Dispatch
Dynamic Method Dispatch is an important mechanism in java which helps us to resolve an overridden method at run time, rather than compile time.This mechanism helps us to understand how run time polymorphism occurs.When an overridden method is called by the reference of superclass,Java decides which overridden method is to be executed by looking at the object referred by the superclass reference.


//example of dynamic method dispatch
class student{
   public int roll , marks  ;
   public student(int x, int y){
       roll = x;
       marks = y;
   }
 public void show(){
 System.out.println(" roll no : " + roll + " " + " marks " + marks);
 }}
class studentA extends student{
public int std;
studentA(int x , int y , int z){
  super(x,y);
  std = z;
}
public void show(){
 System.out.println("class " + std + " roll no : " + roll + " " + " marks " + marks);
}
}
class studentB extends student{
public int st;
studentB(int x , int y , int z){
  super(x,y);
  st = z;
}
public void show(){
 System.out.println("class " + st + " roll no : " + roll + " " + " marks " + marks);
}
}
class NewClass{
    public static void main(String args[]){
    student all = new student(12,59);
    studentA A = new studentA(32,95,5);
    studentB B = new studentB(36,96,8);
    student ref; //reference of student class
    ref = all;
    ref.show();
    ref = A ;
    ref.show();
    ref = B;
    ref.show();
}
}

output
roll no : 12 marks 59
class 5 roll no : 32 marks 95
class 8 roll no : 36 marks 95

explanation : Here we have taken a superclass reference "ref" .The superclass's reference is assigned by the objects of superclass and the sub-classes.This reference helps to invoke the show() method. So , the object referred will determine which method is to be executed.

Abstract Class

In the abstract class , we use to declare a generalized form of methods that will be shared by all its sub-classes, leaving it to each sub classes to fill in the details .In other words we can say that , we are just building an empty method in the superclass (abstract class) which will get filled by the methods with same name that are defined in the sub-classes.
syntax :
abstract class <class-name> {
//,,....
abstract void <method-name>();
//;;;
}

note :
# We use the abstract keyword in front of the class keyword to declare the class <class-name> as an   abstract type class.The abstract method declared in the abstract class (superclass) is defined in each sub-classes.
# We cannot create an object of abstract class.
# We can only create the object reference of abstract class because in java, superclass's reference is used to implement run time polymorphism.
# We cannot create abstract constructor and static methods.

//example of abstract class
abstract class student{
   public int roll , marks  ;
   public student(int x, int y){
       roll = x;
       marks = y;
   }
 abstract void show(); //abstract method without body
 }
class studentA extends student{
public int std;
studentA(int x , int y , int z){
  super(x,y);
  std = z;
}
public void show(){
 System.out.println("class " + std + " roll no : " + roll + " " + " marks " + marks);
}
}
class studentB extends student{
public int st;
studentB(int x , int y , int z){
  super(x,y);
  st = z;
}
public void show(){
 System.out.println("class " + st + " roll no : " + roll + " " + " marks " + marks);
}
}
class NewClass{
    public static void main(String args[]){
    studentA A = new studentA(32,95,5);
    studentB B = new studentB(36,96,8);
    student ref; //reference of student class
    ref = A ;
    ref.show();
    ref = B;
    ref.show();
}
}