Unit-3: Exceptions, Nested enum types and Collection framework •


Unit-3: Exceptions, Nested enum types and Collection framework
Runtime stack and execution of application
The return and the throw statements, The return type and throws declaration in methods Checked and the Unchecked exception classes, The Throwable class
Exception chaining, Handling exceptions with try and catch, Use of the finally block, Creating
custom exception classes

Member Types
Top level nested classes and Inner classes, The local class and anonymous classes
The enum type
classes from java.util package
Date, Time Zone, Calendar and the Gregorian Calendar classes
Collection Framework, Collection interface, Set and List interfaces, Map interface
Generics in the Collection Framework
Regular Expressions, Pattern and Matcher classes
Scanner class
Varargs and the Formatter class
1) Runtime stack and execution of application

Let us try to look at how Java executes any application. In JVM we have three important areas. One is known as the heap, another area is known as the method area and yet another is for the runtime stacks. Heap is the area where objects are allocated at runtime, and runtime stack is the area which is used for the execution of methods and constructors. Whenever any class is loaded, an instance of the Class class is created. The instances of the Class class are allocated in the method area. All the classes and interfaces which are used by an application are first loaded, i.e. the instances of the Class class are created for each of them in the method area. From this instance all the information from the class definition is available. It would have space for the static variables in the class, the code for the various methods in the class. Whenever any method is invoked there is a new frame created in the runtime stack for the method. This frame has space for the various parameter variables and the local variables declared in the method. It also maintains a program counter to keep track of which statement in this method is currently being executed. The program counter refers to the method code available from the class definition loaded in the method area. The parameter variables in the frame are initialized by the invocation, whereas the local variables are uninitialized. As execution proceeds within a method, it may need to invoke another method or a constructor. Each invocation of the method or constructor creates a new frame in the same runtime stack, and the execution of the current method waits till the method in the new frame has finished.




2) The return and the throw statements, The return type and throws declaration in methods

 When we declare or define any method, we have modifiers for the method followed by the return type of the method, then the method name followed by the list of parameters required for invoking the method. The return type of the method indicates the type of value which will be returned when the method completes successfully. The return statement in the method is restricted to return an expresssion which matches the return type mentioned for the method.

Similar to the way we mention the return type of a method to indicate the type of expression it returns on successful completion, we can indicate the kind of failures which are possible from the method in a method signature. In a method declaration/definition, after the list of parameters we use the throws declaration to give a list of Throwable classes indicating the kind of exceptions which may possibly be thrown when this method fails.

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

throw someThrowableObject;

Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.

public Object pop() {
    Object obj;

    if (size == 0) {
        throw new EmptyStackException();
    }

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}

The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.

Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur.

Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exceptions as opposed to Errors.

In Java, there two types of exceptions:

1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and prints first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException

To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.

2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.

class MY { public static void main(String argue[]) { int a,b,c; a = 0; b = 10; c = b/a; } }

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
 at MY.main(MY.java:5)
Java Result: 1
3) Exception chaining, Handling exceptions with try and catch, Use of the finally block, Creating custom exception classes

Exception chaining

An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception. It can be very helpful to know when one exception causes another. Chained Exceptions help the programmer do this. The following are the methods and constructors in Throwable that support chained exceptions. Throwable getCause() Throwable initCause(Throwable) Throwable(String, Throwable) Throwable(Throwable) The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause sets the current exception's cause. The following example shows how to use a chained exception. try { } catch (IOException e) { throw new SomeExceptionClass("Exception", e); } In this example, when an IOException is caught, a new SomeExceptionClass exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler.

The try Block

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following: try { code } catch and finally blocks . . . The segment in the example labeled code contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.) To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short. If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it; the next section, The catch Blocks, shows you how.

The catch Blocks

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block. try { } catch (ExceptionType name) { } catch (ExceptionType name) { } Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name. The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument. The following are two exception handlers for the writeList method — one for two types of checked exceptions that can be thrown within the try statement: try { } catch (ExceptionType1 e) { System.err.println("ExceptionType1: " + e.getMessage()); } catch (ExceptionType2 e) { System.err.println("ExceptionType2: " + e.getMessage()); } Catching More Than One Type of Exception with One Exception Handler

Combine Example

public class MyFinallyBlock {
    public static void main(String[] a){
        /**
         * Exception will occur here, after catch block
         * the contol will goto finally block.
         */
        try{
            int i = 10/0;
        } catch(Exception ex){
            System.out.println("Inside 1st catch Block");
        } finally {
            System.out.println("Inside 2st finally block");
        }
        /**
         * In this case exception won't, after executing try block
         * the contol will goto finally block.
         */
        try{
            int i = 10/10;
        } catch(Exception ex){
            System.out.println("Inside 2nd catch Block");
        } finally {
            System.out.println("Inside 2nd finally block");
        }
    }
}

Custom Exception Handling Example

class MyException extends Exception{
   int a;
   MyException(int b) {
     a=b;
   }
   public String toString(){
     return ("Exception Number =  "+a) ;
  }
}
 
class JavaException{
   public static void main(String args[]){
  try{
       throw new MyException(2);
       // throw is used to create a new exception and throw it.
  }
 catch(MyException e){
    System.out.println(e) ;
 }
}
}
4)Member Type

    Member variables in a class—these are called fields.
    Variables in a method or block of code—these are called local variables.
    Variables in method declarations—these are called parameters.

Access Modifiers

    public accessible from all classes.
    private is accessible only within its own class.

5)Top level nested classes and Inner classes, The local class and anonymous classes

The Java  allows you to define a class within another class. Such a class is called a nested class.
example

class Outerclass {
    ...
    class Nestedclass {
        ...
    }
}
 benfit:-
1.Nesting  classes makes their package more streamlined.
2.Increased encapsulation
3.More readable, maintainable programming
  
  Static nested classes:
  OuterClass.StaticNestedClass

 *Local classes 
Local classes are classes that are defined in a block
class 
example:-

class LocalClassExample 
{       
        class Local 
  {
                 Local() 
    {
  ....
                  }
  ......
                 }            

       Local l1 = new Local();
       Local l2 = new Local();
}

*Anonymous Classes
They are like local classes except that they do not have a name
Example:-

 Demo d1 = new Demo() {

            public void method() 
            {
                 ........
            }
 public void method2() 
            {
                 ........
            }
            
        };
d1.method();


    You cannot declare static initializers this class.

    An anonymous class can have static members.
     
    The New Keyword Is used for creating Anonymous  class.
6) The enum type
 class Denom {
            public static final int ONE= 1;
            public static final int FIVE = 5;

      }

class nUMBER {
   int Denom ; //Denom.ONE,Denom .FIVE,

}

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}
 USE IN YOUR PROGRAMM  Day day;
AND USE  DAY.SUNDAY;

7)classes from java.util package
1)Collection interface
The Collection interface is used to pass collection of objects.
Collection interface:-
public interface Collection extends Iterable 
    {
    int size();
    boolean isEmpty();
    boolean contains(Object element);    
    boolean add(E element);
    boolean remove(Object element);
    Iterator iterator();
    boolean containsAll(Collection c);
    boolean addAll(Collection c); 
    boolean removeAll(Collection c);
    boolean retainAll(Collection c);
    void clear();
    Object[] toArray();
     T[] toArray(T[] a);
    }

collection to object array:-
    Object[] a = c.toArray();


2)Java Iterator
Example:-

 
import java.util.ArrayList;
import java.util.Iterator;
 
public class ExampleIterator 
 { 
  public static void main(String args[])
 {
    ArrayList abc = new ArrayList();
    abc.add("a");
    abc.add("b");
    acb.add("c");
 
    Iterator abcitr = abc.iterator();
 
    while(abctr.hasNext()) {
      String text = (String)abcitr.next();
      System.out.println(text);
    }
  }

3)List InterFace

A List is an ordered Collection or sequence.Lists may contain duplicate value. it is inherited from Collection.
List interface:-

    Positional access — elements  numerical position in the list.
    Search — searches for  object in the list and returns its position.
    Iteration — extends Iterator.
    Range-view — Do range operations on the list.

The List interface follows.

public interface List extends Collection 
{

    D get(int index);    
    D set(int index, D element);    
    boolean add(D element);     
    void add(int index, D element);    
    boolean addAll(int index, Collection c);
    D remove(int index);    
    int indexOf(Object o);
    int lastIndexOf(Object o);    
    ListIterator listIterator();
    ListIterator listIterator(int index);    
    List subList(int from, int to);
}

4)Java Map Interface
TreeMap – The map is sorted using its keys or Comparator provided at map creation time, depending on which constructor is used. 

HashMap – This class makes no guarantees as to the order of the map. Uses object equality to check if key already exist in map and replace value if it exist. 

IdentityHashMap - Unlike above HashMap, this uses reference-equality in place of object-equality when comparing keys. As in following example even after key11 equals key1, but as their references are not equals so a new key/value is 

LinkedHashMap -This implementation keeps track of order in which keys were inserted into the map
 
Packages for Map interface
java.util.HashMap
java.util.IdentityHashMap
java.util.LinkedHashMap
java.util.Map
java.util.TreeMap
java.util.WeakHashMap

Examples:-
        // TreeMap
        Map treeMap = new TreeMap();
        treeMap.put(4, "44");
        treeMap.put(5, "55");
        treeMap.put(1, "11");
        System.out.println("TreeMap - " + treeMap);

        // HashMap
        Key key3 = new Key(3);
        Key key1 = new Key(1);
        Key key11 = new Key(1);
        Map map = new HashMap();
        map.put(key1, "1");
        map.put(key11, "el11");
        map.put(key3, "333");
        System.out.println("HashMap - " + map);
        

        // IdentityHashMap
        Map idMap = new IdentityHashMap();
        idMap.put(key1, "O1");
        idMap.put(key11, "e11");
        idMap.put(key3, "333");
        System.out.println("IdentityHashMap - " + idMap);
        

        // LinkedHashMap
        Map linkedMap = new LinkedHashMap(5);
        linkedMap.put(5, "55");
        linkedMap.put(3, "33");
        System.out.println("LinkedHashMap - " + linkedMap);
      
        
        // LinkedHashMap for Caching using access-order
        Map cachedLinkedMap = new CacheUsingLinkedHashMap(5);
        cachedLinkedMap.put(5, "55");
        cachedLinkedMap.put(3, "33");
        cachedLinkedMap.get(5);
        cachedLinkedMap.get(3);

       

        // WeakHashMap
        Map weakMap = new WeakHashMap();
        Key key4 = new Key(4);        Key key5 = new Key(5);
        weakMap.put(key4, "44");
        weakMap.put(key5, "55");
        weakMap.put(key6, "66");      
         key6 = null;
        System.gc();
       
       //iteratoring and Map entry 
       Set set = hashmap.entrySet();
      
       Iterator i = set.iterator();
       // Display elements
       while(i.hasNext()) 
        {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
       }
      
5) queue
Queue works like first in first out (FIFO) policy. Queue does not require any fix dimension like String array and int array
Example:-
 Queue demo=new LinkedList();

        demo.add("c");
        demo.add("e");
        demo.add("d");

        Iterator it=demo.iterator();

        System.out.println("Initial Size of Queue :"+demo.size());

        while(it.hasNext())
        {
            String iteratorValue=(String)it.next();
            System.out.println("Queue Next Value :"+iteratorValue);
        }        
        Queue peek =demo.peek();       
        Queue poll =demo.poll();
        Queue=demo.size();

6)SortedSet
 SortedSet set = new TreeSet(); 

      // Add elements to the set
      set.add("b");
      set.add("c");
      set.add("a");

      // Iterating over the elements in the set
      Iterator it = set.iterator();
      while (it.hasNext()) {
         // Get element
         Object element = it.next();
         System.out.println(element.toString());
      }
8) Date, Time Zone, Calendar and the Gregorian Calendar classes

1)Date
        System.currentTimeMillis()
        Date
        publicDate(longdate)
        publicDate(intyear,intmonth,intdate)
        publicDate(intyear,intmonth,intdate,inthrs,intmin)
        publicDate(intyear,intmonth,intdate,inthrs,intmin,intsec)
            year-yearminus1900.
            month-monthbetween0-11.
            date-thedayofthemonthbetween1-31.
            hrs-thehoursbetween0-23.
            min-theminutesbetween0-59.
            sec-thesecondsbetween0-59.
        publicDate(Strings)    
        publicintgetYear()    
        publicvoidsetYear(intyear)
        publicintgetMonth()
        publicvoidsetMonth(intmonth)
        publicintgetDate()
        publicvoidsetDate(intdate) 
        int getDate()
        int getDay()
        int getHours()
        int getMinutes()
        int getMonth()
        int getSeconds()
        long getTime()
        int getTimezoneOffset()
        int getYear()
        int hashCode()
        staticlong parse(Strings)
        void setDate(intdate)
        void setHours(inthours)
        void setMinutes(intminutes)
        void setMonth(intmonth)
        void setSeconds(intseconds)
        void setTime(longtime)
        void setYear(intyear)
        String toGMTString()
        String toLocaleString()
        String toString()

Example:-
        Date date = new Date();
       System.out.println(date.toString());

2)Time
        int  getDate()
        int  getDay()
        int  getMonth()
        int  getYear()
        void  setDate(int i)
        void  setMonth(int i)
        void  setTime(long time)
        void  setYear(int i)
        String  toString()
        static Time  valueOf(String s)
3) Calander
        abstract  void  add(int field, int amount)
        boolean  after(Object when)
        boolean  before(Object when)
        void            clear()         
        void            clear(int field)
        int             compareTo(Calendar anotherCalendar)
        boolean  equals(Object obj)          
        int             get(int field)
        int             getFirstDayOfWeek()          
        abstract   int  getGreatestMinimum(int field) 
        static Calendar getInstance()         
        TimeZone  getTimeZone()
        void            set(int field, int value)          
        void            set(int year, int month, int date) 
        void            set(int year, int month, int date, int hourOfDay, int minute)
        void            set(int year, int month, int date, int hourOfDay, int minute, int second)
        void            setFirstDayOfWeek(int value)  
        void            setMinimalDaysInFirstWeek(int value)
        void            setTime(Date date)
        void            setTimeInMillis(long millis)
        void            setTimeZone(TimeZone value) 
        String          toString()          
Example:-
      Calendar cal = Calendar.getInstance();
      System.out.println("Current time is :" + cal.getTime());
      Date date = new Date(95, 10, 10);
      cal.setTime(date);   
      System.out.println("After setting Time:  " + cal.getTime());

4)Gregorian Calendar
    Calendar calendar = new GregorianCalendar();
    Date trialTime = new Date();
    calendar.setTime(trialTime);

    System.out.println("ERA: " + calendar.get(Calendar.ERA));
    System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
    System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
    System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
    System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
    System.out.println("DATE: " + calendar.get(Calendar.DATE));
    System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
    System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
    System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
    System.out.println("DAY_OF_WEEK_IN_MONTH: "+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
    System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
    System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
    System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
    System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
    System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
    System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
    System.out.println("ZONE_OFFSET: "+ (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
    System.out.println("DST_OFFSET: "+ (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
    System.out.println("Current Time, with hour reset to 3");
    calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
    calendar.set(Calendar.HOUR, 3);


9) Collection Framework, Collection interface, Set and List interfaces, Map interface
As Above...
10) Generics in the Collection Framework
As Above...
11) Regular Expressions, Pattern and Matcher classes
        import java.util.regex.Pattern;
        import java.util.regex.Matcher;

        public class MatcherDemo 
        {

            private static final String REGEX ="\\bog\\b";
            private static final String INPUT ="og og og boggie bog";

            public static void main(String[] args) {
               Pattern p = Pattern.compile(REGEX);

               Matcher m = p.matcher(INPUT);
               int count = 0;
               while(m.find()) 
                {
                   count++;
                   System.out.println("Match number "+ count);
                   System.out.println("start(): "+ m.start());
                   System.out.println("end(): "+ m.end());
              }
           }
        }

12) Scanner class
Methods:-
        String  findInLine(Pattern pattern)
       String findInLine(Stringpattern)
       String findWithinHorizon(Patternpattern,inthorizon)
       String findWithinHorizon(Stringpattern,inthorizon)
       boolean hasNext()
       boolean hasNext(Patternpattern)
       boolean hasNext(Stringpattern)
       boolean hasNextBigDecimal()
       boolean hasNextBigInteger()
       boolean hasNextBigInteger(intradix)
       boolean hasNextBoolean()
       boolean hasNextByte()boolean hasNextDouble()
       boolean hasNextFloat()boolean hasNextInt()
       boolean hasNextInt(intradix)
       boolean hasNextLine()
       boolean hasNextLong()
       boolean hasNextLong(intradix)
       boolean hasNextShort()
       boolean hasNextShort(intradix)
       IOException ioException()
       Locale locale()
       MatchResult match()
       String next()
       String next(Patternpattern)
       String next(Stringpattern)
       BigDecimal nextBigDecimal()
       BigInteger nextBigInteger()
       BigInteger nextBigInteger(intradix)
       boolean nextBoolean()
       byte nextByte()
       byte nextByte(intradix)
       double nextDouble()
       float nextFloat()
       int nextInt()
       int nextInt(intradix)
       String nextLine()
       long nextLong()
       long nextLong(intradix)
       short nextShort()
       short nextShort(intradix)
       String toString()


String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 

13) Varargs and the Formatter class
2)Formatter class
An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output

 StringBuilder sb = new StringBuilder();
   // Send all output to the Appendable object sb
   Formatter formatter = new Formatter(sb, Locale.US);

   // Explicit argument indices may be used to re-order output.
   formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
2)Vargas
public class Test {
    public static void main(String[] args) 
     {
        for (String className : args) {....}
     ....
    }
public class Varargs 
{
 
    public static void main(String args[]) {
        meth(215, "ia", "Dhi");
        meth(147, "tt", "ewk", "loia");
    }
 
    public static void metg(int some, String... args) {
        System.out.print("\n" + some);
        for(String arg: args) {
            System.out.print(", " + arg);
        }
    }
}

No comments:

Post a Comment