Wednesday, December 19, 2012

Oops in Java and collections, exception handling



## Principle concepts of OOPS-------------------- Abstraction
                                                                              · Polymorphism
                                                                              · Inheritance
                                                                              · Encapsulation
1)** Abstraction:   Abstraction refers to the act of representing essential features without including the background details or explanations.
EX: Abstraction is way of converting real world objects in terms of class
public class Vehicle {
public String color;
public String model;
}
2)**Polymorphism: The ability to define more than one function with the same name is called Polymorphism. (One interface, many implementations)
There are two type of polymorphism: compile time polymorphism (overloading)
                                                                 And
                                                              Run time polymorphism (overriding).

** methods overloading:- In some cases, multiple methods have the same name, but different formal argument lists.
Example: Overloading
Class BookDetails{
            String title;
            String publisher;
            float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}
Rules:
  • Overloaded methods MUST change the argument list
  • Overloaded methods CAN change the return type
  • Overloaded methods CAN change the access modifier
  • Overloaded methods CAN declare new or broader checked exceptions
  • A method can be overloaded in the same class or in a subclass
** methods overriding :_- In other cases, multiple methods have the same name, same return type, and same formal argument list
                             Example: Overriding
class BookDetails{
            String title;
setBook(String title){ }
}
class ScienceBook extends BookDetails{
            setBook(String title){}                                             //overriding
setBook(String title, String publisher,float price){ }  //overloading    }
Note:
  • The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
  • You cannot override a method marked final
  • You cannot override a method marked static
3)**Inheritance: Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. (Only properties with access modifier public and protected can be accessed in child class.)
Example:                  
public class Parent{
public String parentName;
public int parentage;
public String familyName;
}

public class Child extends Parent{
public String childName;
public int childAge;
public void printMyName(){
System.out.println(“ My name is “+ chidName+” “ +familyName)
}}
** family name from the parent class just by inheriting the class
4)** Encapsulation: Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. We can achieve with ACCESS MODIFIERS.


ABSTRACT CLASS  vs  INTERFACE

Abstract Class
Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all,just the signature.
In case of abstract class, a class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods.
All methods of an Interface are abstract.
An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors .
An Interface cannot contain constructors .
Abstract classes are fast.
Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.
EX:
//Abstarct Class
public abstract class Vehicles
      {
        private int noOfWheel;
        private string color;
        public abstract string Engine
        {  
            get;
            set;
        }
        public abstract void Accelerator();}
EX:
//Interface
public interface Vehicles
      {
        string Engine
        {  
            get;
            set;
        }
        void Accelerator();
      }

STATIC
Static variable:
  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<variable-name>
Static method:
  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<method-name>
  • A static method cannot refer to “this” or “super” keywords in anyway
Side Note:
  • main method is static , since it must be be accessible for an application to run , before any instantiation takes place.
Static block:
  • The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM
  • A static block helps to initialize the static data members, just like constructors help to initialize instance members

Constructors VS  Method

Constructors
Methods
Purpose
Create an instance of a class
Group Java statements
Modifiers
Cannot be abstract, final, native, static, or synchronized
Can be abstract, final, native, static, or synchronized
Return Type
No return type, not even void
void or a valid return type
Name
Same name as the class (first letter is capitalized by convention) -- usually a noun
Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
this
Refers to another constructor in the same class. If used, it must be the first line of the constructor
Refers to an instance of the owning class. Cannot be used by static methods.
super
Calls the constructor of the parent class. If used, must be the first line of the constructor
Calls an overridden method in the parent class
Inheritance
Constructors are not inherited
Methods are inherited

this() and super()

'this' is used for pointing the current class instance. It can be used with variables or methods
'super' is used for pointing the super class instance
Any ware in middle of program
If a constructor uses super, it must use it in the first line
class Test{
        private int i=10;
        public void m(){
                System.out.println(this.i);
        }
}

class A
{
        int k = 10;
}
class Test extends A
{
        public void m()
        {
                System.out.println(super.k);
        }}


## String class objects are immutable objects means that they can’t be altered. It always creates a new object when we try to change them. However StringBuffer and StringBuilder classes are mutable and one can change the contents of it.

EX:  To concatenate
 String s1="ABC" and String s2="DEF"
using "+" operator we need another string. 
String s3 = s1+s2 and       s3 ----------will have the value of "ABCDEF".

But using StringBuffer or StringBuilder the same scenario in this case can be s1.append("DEF") and s1 becomes "ABCDEF". They are provided by append() and insert() methods.

2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.

Usage:
1. If your text is not going to change use a string Class because a String object is immutable.

2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.

3. If your text can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.  

Object class(methods)
String Class (methods)
Clone, notify, notifyAll, toString
length()
equals
toLowerCase()
toString
toUpperCase()
finalize
trim()
getClass
substring(Start)
hashCode
harAt(Position)

==   and    .equals

== operator is used to compare the references of the objects.
equals() method can be used to compare the values of two objects.
public boolean equals(Objecto) is the method provided by the Object class. The default
implementation uses == operator to compare two objects.
But since the method can be overridden like for String class. equals() method can be used to compare the values of two objects.
EX:











String str1 = new String("MyName");
String str2 = new String("MyName");
if(str1 ==str2){
   System.out.println("Objects are equal")
}else{
   System.out.println("Objects are not equal")
}

if(str1.equals(str2)){
  System.out.println("Objects are equal")
}else{
  System.out.println("Objects are not equal")
}
Output:
Objects are not equal
Objects are equal
toString()
## Implementing toString method in java is done by overriding the Object’s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class.

StringTokenizer

##  you can StringTokennizer class to split a String into different tokenas by defined delimiter.(space is the default delimiter)
Uses StringTokennizer to split a string by “space” and “comma” delimiter, and iterate the StringTokenizer elements and print it out one by one.

final, finally and finalize

Final:- It is used in the following three cases:
  1. If the final keyword is attached to a variable then the variable becomes constant i.e. its value cannot be changed in the program.
  2. If a method is marked as final then the method cannot be overridden by any other method.
  3. If a class is marked as final then this class cannot be inherited by any other class.
Finally:- If an exception is thrown in try block then the control directly passes to the catch block without executing the lines of code written in the remainder section of the try block. In case of an exception we may need to clean up some objects that we created. If we do the clean-up in try block, they may not be executed in case of an exception. Thus finally block is used which contains the code for clean-up and is always executed after the try ...catch block, except System.exit(0) call.

Finalize:- It is a method present in a class which is called before any of its object is reclaimed by the garbage collector. Finalize() method is used for performing code clean-up before the object is reclaimed by the garbage collector.
COLLECTIONS






Interfaces
Main methods>
  • Set - Extends the Collection
    • The familiar set abstraction.
    • No duplicate elements permitted.
    • At most one null element.
    • May or may not be ordered.interface.
  • Map-
    • A mapping from keys to values.
    • Each key can map to at most one value.
  • put(K key, V value) -
    • replaces  the old value is replaced by the specified value
    • returns the previous value associated with key
  • get(Object key)
  • remove(Object key)
    • returns the previous value associated with key
  • boolean containsKey(Object key)
  • List - Extends the Collection.
    • Ordered collection, also known as a sequence.
    • Duplicates are generally permitted.
    • Allows positional access.

General-Purpose Implementations

  • This class permits the null element.
  • Fast access, assures no duplicates, provides no ordering.
  • Runs nearly as fast as HashSet.
  • No duplicates; iterates by insertion order.
  • not syncronized
  • No duplicates; iterates in sorted order.
-

  • Fast iteration and fast random access
  • synchronised
  • It's like a slower ArrayList, but it has synchronized methods.
  • May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list.
  • Good for adding elements to the ends, i.e., stacks and queues.
  • The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time
  • unbounded. its capacity grows automatically.
  • does not permit null elements
  • The head of this queue is the least element
  • The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
-

  • Essentially an unsynchronized Hashtable that supports null keys and values.
  • Fastest updates (key/values); allows one null key, many null values.
  • Like a slower HashMap (as with Vector, due to its synchronized methods).
  • No null values or null keys allowed
  • Predictable iteration order.
  • Runs nearly as fast as HashMap.
  • Allows one null key, many null values.
  • A sorted map
  • Ascending element order

arraylist vs linkedlist
  1. import java.util.*;  
  2. class ListOp1a {  
  3.  public static void main(String args[]) {  
  4.    LinkedList l = new LinkedList();  
  5.    l.add("This");  
  6.    l.add("is");  
  7.    l.add("a");  
  8.    l.add("test");  
  9.    l.add("test");  
  10.    
  11.    System.out.println(l);  
  12.  }  
  13. }  
  1. import java.util.*;  
  2. class ListOp1a {  
  3.  public static void main(String args[]) {  
  4.    ArrayList l = new ArrayList();  
  5.    l.add("This");  
  6.    l.add("is");  
  7.    l.add("a");  
  8.    l.add("test");  
  9.    l.add("test");  
  10.    
  11.    System.out.println(l);  
  12.  }  

result of both is:
C:\Java\EigeneJavaProgramme>java ListOp1a
[This, is, a, test, test]

Both are similar, though slightly different in terms of goal and implementation. In a LinkedList, each element is linked to its previous and next element making it easier to delete or insert in the middle of the list. A ArrayList is more as its name subjects used as an array.
Performance is similar, though LinkedList is optimized when inserting elements before the end of the list, where ArrayList is optimized when adding elements at the end.

HashMap and HashTable

not synchronized or not thread-safe(it can be made thread-safe by using --> Collections.synchronizedMap() method)
synchronized, thread-safe.
allows one null value as key
does not allow null value as key.
EX:
1
HashMap<Integer,String> productMap = new HashMap<Integer,String>();

2
productMap.put(1, "Keys");

3
productMap.put(2, null);
EX:
Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();

2
cityTable.put(1, "Lahore");

3
cityTable.put(2, "Karachi");

4
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/

5


6
System.out.println(cityTable.get(1));

7
System.out.println(cityTable.get(2));

8
System.out.println(cityTable.get(3));

Iterator            vs             listiterator             vs             enumeration
Only forward directional cursor
can move either to forward or backward direction (child interface of iterator)
This is cursor to retrive the objects one by one
allowed to perform read and remove operation
Allowed to add, remove  and read operation
can get only read-access
any collection implemented class
only for list implemented classes
only for legacy classes
EX: Import java.util.*;
Class IteratorDemo
{
public static void main(String arg[])
{
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++)
{
l.add(new Integer(i);
}
System.out.println(i); // 0,1,2,3,……9
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer i=(Integer)itr.next();
If(i.intValue() % 2==0)
{
System.out.println(i);
}  else    {
itr.remove();
}}
System.out.println(l); [0,2,4,6,8]
}}}
EX: Import java.util.*;
Class ListIterDemo
{
public static void main(String arg[])
{
LikedList l=new LinkedList();
L.add(“laxman”);
l.add(“chandu”);
l.add(“ravi”);
l.add(“raju”);
System.out.println(l);
ListIterator lt=l.listIterator();
While(lt.hasNext())
{
String s=(String)lt.next();
If(s.equals(“laxman”))
{
lt.remove(); or lt.set(“scjp”);
}
}
System.out.println(l);
}
}
EX: Import java.util.*;
Class EnumDemo
{
public static void main(String arg[])
{
Vector v= new Vector();
For(int i=0;i<=10; i++)
{
v.addElement(new Integer(i);
}
System.out.println(v); // [0,1,2,3…….10]
Enumeration e=v.elements();
While(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
If(i.IntValue() % 2 ==0)
{
System.out.println(i);
}
}
}

Comparable vs. Comparator

Classes should implement the Comparable interface to control their natural ordering.
Use Comparator to sort objects in an order other than their natural ordering.
Objects that implement Comparable can be sorted by Collections.sort() and Arrays.sort() and can be used as keys in a sorted map or elements in a sorted set without the need to specify a Comparator.
« Interface »
Comparable
+ compareTo(Object) : int

compareTo() compares this object with another object and returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the other object.




« Interface »
Comparator
+ compare(Object, Object) : int
+ equals(Object) : Boolean
compare() compares its two arguments for order, and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
public class Book implements Comparable {
    String title;
    int    isbn;
 
    Book(String title, int isbn) {
        this.title = title;
        this.isbn  = isbn;
    }
 
    public int compareTo(Object object) {
        Book other = (Book) object;
        if (this.title.equals(other.title)) {
            return this.isbn - other.isbn;
        }
        return this.title.compareTo(other.title);
    }
}

import java.util.*;
 
public class TestCollections {
    public static void main(String[] args) {
        List list = new LinkedList();
        list.add(new Book("Patterns", 12345));
        list.add(new Book("Patterns", 34567));
        list.add(new Book("Examples", 23456));
 
        Collections.sort(list);
 
        Collections.sort(list, new Comparator() {
            public int compare(Object obj1, Object obj2) {
                Book book1 = (Book) obj1;
                Book book2 = (Book) obj2;
                return book1.isbn - book2.isbn;
            }});  }}

Multithreading

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
·         New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
·         Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
·         Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

Above mentioned stages are explained here:
·         Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
·         Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities:

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.
Creating a Thread:
Java defines two ways in which this can be accomplished:
·         You can implement the Runnable interface.
·         You can extend the Thread class, itself.

Example:

Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}
 
class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Thread Methods:
Following is the list of important medthods available in the Thread class.
SN
Methods with Description
1
public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2
public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread
SN
Methods with Description
1
public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled
2
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds
3
public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
5
public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Interthread Communication

To avoid polling, Java includes an elegant interprocess communication mechanism via the following methods:
  • wait( ): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
  • notify( ): This method wakes up the first thread that called wait( ) on the same object.
  • notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c The highest priority thread will run first.
These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context.

Exceptions Handling

To understand how exception handling works in Java, you need to understand the three categories of exceptions:
·         Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
·         Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
·         Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.
Here is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.
SN
Methods with Description
1
public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3
public String toString()
Returns the name of the class concatenated with the result of getMessage()
4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
 
   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
This would produce following result:
Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:
try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example:

Here is code segment showing how to use multiple try/catch statements.
 
try
{
   file = new FileInputStream(fileName);
   x = (byte) file.read();
}catch(IOException i)
{
   i.printStackTrace();
   return -1;
}catch(FileNotFoundException f) //Not valid!
{
   f.printStackTrace();
   return -1;
}

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}
Amethod can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

Example:

public class ExcepTest{
 
   public static void main(String args[]){
      int a[] = new int[2];
      try{
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      finally{
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}
This would produce following result:
Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the followings:
·         A catch clause cannot exist without a try statement.
·         It is not compulsory to have finally clauses when ever a try/catch block is present.
·         The try block cannot be present without either catch clause or finally clause.
·         Any code cannot be present in between the try, catch, finally blocks.

Declaring you own or custom Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:
·         All exceptions must be a child of Throwable.
·         If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
·         If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example:

// File Name InsufficientFundsException.java
import java.io.*;
 
public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
}
To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;
 
public class CheckingAccount
{
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
   public void deposit(double amount)
   {
      balance += amount;
   }
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   public double getBalance()
   {
      return balance;
   }
   public int getNumber()
   {
      return number;
   }
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();
      }
    }

}
Compile all the above three files and run BankDemo, this would produce following result:
Depositing $500...
 
Withdrawing $100...
 
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

Common Exceptions:

In java it is possible to define two catergories of Exceptions and Errors.
·         JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,
·         Programmatic exceptions . These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException.

No comments:

Post a Comment