Understanding Java Exceptions

download Understanding Java Exceptions

of 43

Transcript of Understanding Java Exceptions

  • 8/3/2019 Understanding Java Exceptions

    1/43

    Understanding Java Exceptions

    Exceptions in java are any abnormal, unexpected events or extraordinary conditions thatmay occur at runtime. They could be file not found exception, unable to get connectionexception and so on. On such conditions java throws an exception object. Java Exceptionsare basically Java objects. No Project can never escape a java error exception.

    Java exception handling is used to handle error conditions in a program systematically bytaking the necessary action. Exception handlers can be written to catch a specific exceptionsuch as Number Format exception, or an entire group of exceptions by using a genericexception handlers. Any exceptions not specifically handled within a Java program arecaught by the Java run time environment

    An exception is a subclass of the Exception/Error class, both of which are subclasses of theThrowable class. Java exceptions are raised with the throw keyword and handled within acatch block.

    A Program Showing How the JVM throws an Exception at runtime

    public class DivideException {

    public static void main(String[] args) {division(100,4); // Line 1division(100,0); // Line 2

    System.out.println("Exit main().");}

    public static void division(int totalSum, int totalNumber) {System.out.println("Computing Division.");int average = totalSum/totalNumber;

    System.out.println("Average : "+ average);

    }}

    D ownload DivideException.java

  • 8/3/2019 Understanding Java Exceptions

    2/43

    An ArithmeticException is thrown at runtime when Line 11 is executed because integerdivision by 0 is an illegal operation. The Exit main() message is never reached in the mainmethod

    Output

    Computing Division. java.lang.ArithmeticException: / by zeroAverage : 25Computing Division.at DivideException.division(DivideException.java:11)at DivideException.main(DivideException.java:5)Exception in thread main

    Exceptions in Java

    Throwable Class

    The Throwable class provides a String variable that can be set by the subclasses to providea detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

    The class Throwable provides getMessage() function to retrieve an exception. It has aprintStackTrace() method to print the stack trace to the standard error stream. Lastly Italso has a toString() method to print a short description of the exception. For more

    information on what is printed when the following messages are invoked, please refer the java docs.

    Syntax

    String getMessage()

    void printStackTrace()

    String toString()

    Class Exception

    The class Exception represents exceptions that a program faces due to abnormal or specialconditions during execution. Exceptions can be of 2 types: Checked (Compile timeExceptions)/ Unchecked (Run time Exceptions).

    Class RuntimeException

  • 8/3/2019 Understanding Java Exceptions

    3/43

    Runtime exceptions represent programming errors that manifest at runtime. For exampleArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the

    java.lang.RuntimeException class, which is a subclass of the Exception class. These arebasically business logic programming errors.

    Class Error

    Errors are irrecoverable condtions that can never be caught. Example: Memory leak,LinkageError etc. Errors are direct subclass of Throwable class.

    Ch ecked and Unc h ecked Exceptions Ch ecked exceptions are subclasss of Exception excluding class RuntimeException and itssubclasses. Checked Exceptions forces programmers to deal with the exception that may bethrown. Example: Arithmetic exception. When a checked exception occurs in a method, the

    method must either catch the exception and take the appropriate action, or pass theexception on to its caller

    Unc h ecked exceptions are RuntimeException and any of its subclasses. Class Error and itssubclasses also are unchecked. Unchecked exceptions , however, the compiler doesnt forcethe programmers to either catch the exception or declare it in a throws clause. In fact, theprogrammers may not even know that the exception could be thrown. Example:ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the programshould not attempt to deal with them, or they are logical programming errors. (RuntimeExceptions). Checked exceptions must be caught at compile time. Runtime exceptions donot need to be. Errors often cannot be.

    Exception Statement Syntax

    Exceptions are handled using a try-catch-finally construct, which has the Syntax

    try {} catch ( ) { // 0 or more}} finally { // finally block}

    try BlockThe java code that you think may produce an exception is placed within a try block for asuitable catch block to handle the error.

  • 8/3/2019 Understanding Java Exceptions

    4/43

    If no exception occurs the execution proceeds with the finally block else it will look for thematching catch block to handle the error. Again if the matching catch handler is not foundexecutionproceeds with the finally block and the default exception handler throws an exception.. If anexception isgenerated within the try block, the remaining statements in the try block are not executed.

    catch BlockExceptions thrown during execution of the try block can be caught and handled in a catchblock. On exit from a catch block, normal execution continues and the finally block isexecuted(Though the catch block throws an exception).

    finally BlockA finally block is always executed, regardless of the cause of exit from the try block, or

    whether any catch block was executed. Generally finally block is used for freeing resources,cleaning up, closing connections etc. If the finally clock executes a control transferstatement such as a return or a break statement, then this controlstatement determines how the execution will proceed regardless of any return or controlstatement present in the try or catch.

    The following program illustrates the scenario.

    try {

    } catch ( ) { // 0 or more

    }} finally { // finally block

    }

    Download DivideException2.java

    Output

    Computing Division.Exception : / by zeroFinally Block Executes. Exception Occurredresult : -1

  • 8/3/2019 Understanding Java Exceptions

    5/43

    Below is a program showing the Normal Execution of the Program.

    Please note that no NullPointerException is generated as was expected by most people

    public class DivideException2 {

    public static void main(String[] args) {int result = division(100,0); // Line 2

    System.out.println("result : "+result);}

    public static int division(int totalSum, int totalNumber) {int quotient = -1;System.out.println("Computing Division.");try{

    quotient = totalSum/totalNumber;

    }catch(Exception e){

    System.out.println("Exception : "+ e.getMessage());}finally{

    if(quotient != -1){System.out.println("Finally Block Executes");System.out.println("Result : "+ quotient);

    }else{System.out.println("Finally Block Executes.

    Exception Occurred"); return quotient;}

    }return quotient;

    }}

    Output

    null (And not NullPointerException)

  • 8/3/2019 Understanding Java Exceptions

    6/43

    The C ommon Language Runtime is the underpinning of the .NET Framework. CLRtakes care of code management at program execution and provides various beneficialservices such as memory management, thread management, security management,code verification, compilation, and other system services. The managed code that targetsCLR benefits from useful features such as cross-language integration, cross-languageexception handling, versioning, enhanced security, deployment support, and debugging.

    C ommon Type System (CTS) describes how types are declared, used and managed inthe runtime and facilitates cross-language integration, type safety, and high performancecode execution.

    The C ommon Language Specification (CLS) is an agreement among languagedesigners and class library designers to use a common subset of basic language featuresthat all languages have to follow.

    CLR Execution Model:

    To know more about C LR / C TS/ C LS, articles and books - C lick h ere!

    Latest Resources:

  • 8/3/2019 Understanding Java Exceptions

    7/43

    Common Language Runtime Overview Good introduction to the CLR.

    The Common Language Infrastructure (CLI) The Shared Source CLI provides developerswith the source code for a working CLI implementation.

    Common Language Runtime (CLR) Fundamentals To understand the fundamental

    concepts of programming in the Common Language Runtime (CLR) environment.

    This article About the Common Language Runtime (CLR) provides fine, clear points aboutthe CLR.

    Wh at is Common Language Runtime?

    The Common Language Runtime is the engine that compiles the source code in to anintermediate language. This intermediate language is called the Microsoft IntermediateLanguage.

    During the execution of the program this MSIL is converted to the native code or themachine code. This conversion is possible through the Just-In-Time compiler. Duringcompilation the end result is a Portable Executable file (PE).

    This portable executable file contains the MSIL and additional information called themetadata. This metadata describes the assembly that is created. Class names, methods,signature and other dependency information are available in the metadata. Since the CLRcompiles the source code to an intermediate language, it is possible to write the code in anylanguage of your choice. This is a major advantage of using the .Net framework.

    The other advantage is that the programmers need not worry about managing the memorythemselves in the code. Instead the CLR will take care of that through a process calledGarbage collection. This frees the programmer to concentrate on the logic of the applicationinstead of worrying about memory handling.

    Difference between Dynamic Binding & Static Binding in Java

    Dynamic Binding or Late Binding

    Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is

    done at runtime only. Let's try to understand this. Suppose we have a class named ' SuperClass ' andanother class named ' SubClass ' extends it. Now a ' SuperClass ' reference can be assigned to anobject of the type ' SubClass ' as well. If we have a method (say ' someMethod() ') in the ' SuperClass 'which we override in the ' SubClass ' then a call of that method on a ' SuperClass ' reference can onlybe resolved at runtime as the compiler can't be sure of what type of object this reference would bepointing to at runtime.

    ...

  • 8/3/2019 Understanding Java Exceptions

    8/43

    SuperClass superClass1 = new SuperClass(); SuperClass superClass2 = new SubClass(); ...

    superClass1.someMethod(); // SuperClass version is called superClass2.someMethod(); // SubClass version is called ....

    Here, we see that even though both the object references superClass1 and superClass2 are oftype ' SuperClass ' only, but at run time they refer to the objects of types ' SuperClass ' and'SubClass ' respectively.

    Hence, at compile time the compiler can't be sure if the call to the method ' someMethod() ' on thesereferences actually refer to which version of the method - the super class version or the sub classversion.

    Thus, we see that dynamic binding in Java simply binds the method calls (inherited methods only as

    they can be overriden in a sub class and hence compiler may not be sure of which version of themethod to call) based on the actual object type and not on the declared type of the object reference.

    Static Binding or Early Binding

    If the compiler can resolve the binding at the compile time only then such a binding is called StaticBinding or Early Binding. All the instance method calls are always resolved at runtime, but all the staticmethod calls are resolved at compile time itself and hence we have static binding for static methodcalls. Because static methods are class methods and hence they can be accessed using the class nameitself (in fact they are encourgaed to be used using their corresponding class names only and not byusing the object references) and therefore access to them is required to be resolved during compile

    time only using the compile time type information. That's the reason why static methods can notactually be overriden. Read more - Can you override static methods in Java?

    Similarly, access to all the member variables in Java follows static binding as Java doesn't support (infact, it discourages) polymorphic behavior of member variables. For example:-

    class SuperClass{ ... public String someVariable = "Some Variable in SuperClass"; ... }

    class SubClass extends SuperClass{ ... public String someVariable = "Some Variable in SubClass"; ... } ... ...

  • 8/3/2019 Understanding Java Exceptions

    9/43

    SuperClass superClass1 = new SuperClass(); SuperClass superClass2 = new SubClass();

    System.out.println(superClass1.someVariable); System.out.println(superClass2.someVariable); ...

    Ou tp u t:- Some Variable in SuperClass Some Variable in SuperClass

    We can observe that in both the cases, the member variable is resolved based on the declared type ofthe object reference only, which the compiler is capable of finding as early as at the compile time onlyand hence a static binding in this case. Another example of static binding is that of ' private 'methods as they are never inherited and the compile can resolve calls to any private method atcompile time only.

    U pdate[June 24, 2008]: Read more to understand how field hiding in Java works? How is it differentfrom static method hiding? - Field Hiding in Java >>

    Liked the article? You may like to Su bscribe to this blog for regular updates. You may also like tofollow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. Youcan find the ' Followers ' widget in the rightmost sidebar

    Question

    H ow do I use the Vector class, from the java.util package?

    Answer

    Using the Vector class, rather than creating your own linked-list structure is a goodidea. Vectors are extremely easy to use, and implement the Enumeration interfacewhich makes traversing the contents of a Vector extremely easy.

    Creating a vector is easy. Simply define a variable of type Vector, and call the vector

    constructor.

    // Create an instance of class Vector ....Vector myVector = new Vector ();

    // ... or suggest an initial vector sizemyVector = new Vector(50);

  • 8/3/2019 Understanding Java Exceptions

    10/43

    Vector instances, like linked-lists, can grow dynamically. Once the vector reaches itsmaximum limit, it dynamically allocated resources and increases its maximum.H owever, if you know you're going to insert a large amount of data, you may want tospecify an initial estimate.

    Vector instances can store any type of object - you simply insert an object via theaddElement method.

    for (int i = 1; i

  • 8/3/2019 Understanding Java Exceptions

    11/43

    Vectors (the j ava.util.Vector class) are commonly used instead of arrays, because they expandautomatically when new data is added to them. The Java 2 Collections API introduced the similar ArrayListdata structure. ArrayLists are unsynchronized and therefore faster than Vectors, but less secure in amultithreaded environment. The Vector class was changed in Java 2 to add the additional methodssupported by ArrayList. See below for a reasons to use each. The description below is for the (new) Vectorclass.

    Vectors can hold only Objects and not primitive types (eg, int ). If you want to put a primitive type in aVector, put it inside an object (eg, to save an integer value use the Integer class or define your ownclass). If you use the Integer wrapper, you will not be able to change the integer value, so it is sometimesuseful to define your own class.

    To C reate a Vector

    You must import either import j ava.util.Vector; or import j ava.util.*; . Vectors areimplemented with an array, and when that array is full and an additional e lement is added, a new arraymust be allocated. Because it takes time to create a bigger array and copy the elements from the old arrayto the new array, it is a little faster to create a Vector with a size that it will commonly be when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical sections of code

    programmers typically don't specify an initial size.

    y C reate a Vector wit h default initial size Vector v = new Vector();

    y C reate a Vector wit h an initial size Vector v = new Vector(300);

    To Add elements to t h e end of a Vector

    v.add(s); // adds s to the end of the Vector v

    To get t h e elements from a Vector (ListIterator)

    You can use a for loop to get all the elements from a Vector, but another very common way to go over allelements in a Vector is to use a ListIterator. The advantage of an iterator is that it it can be used with otherdata structures, so that if you later change to using a linked list for example, you won't have to change yourcode. Here is an example of using an iterator to print all elements (Strings) in a vector. The two most usefulmethods are hasNext() , which returns true if there are more e lements, and next() , which returns thenext element.

    Li stIterator i ter = v.l i stIterator();

    whi le ( i ter.hasNext()) {

    System.out.pr i ntln((Str i ng) i ter.next());

    }

    C ommon Vector Met h ods

    There are many useful methods in the Vector class and its parent classes. Here are some of the mostuseful. v is a Vector, i is an int index, o is an Object.

    Method Description

  • 8/3/2019 Understanding Java Exceptions

    12/43

    v.add(o) adds Object o to Vector v

    v.add(i, o) Inserts Object o at index i, shifting elements up as necessary.

    v.clear() removes all elements from Vector v

    v.contains(o) Returns true if Vector v contains Object o

    v.firstElement(i) Returns the first element.

    v.get(i) Returns the object at int index i.

    v.lastElement(i) Returns the last element.

    v.listIterator() Returns a ListIterator that can be used to go over the Vector. This is a usefulalternative to the for loop.

    v.remove(i) Removes the element at position i, and shifts all following elements down.

    v.set(i,o) Sets the element at index i to o.

    v.size() Returns the number of elements in Vector v.

    v.toArray(Ob j ect[])

    The array parameter can be any Object subclass (eg, String). This returns thevector values in that array (or a larger array if necessary). This is useful whenyou need the generality of a Vector for input, but need the speed of arrays whenprocessing the data.

    O ld and New Vector Met h ods

    When the new Collections API was introduced in Java 2 to provide uniform data structure classes, the Vectorclass was updated to implement the List interface. Use the List methods because they are common to otherdata structure. If you later decide to use something other than a Vector (eg, ArrayList, or LinkedList, yourother code will not need to change.

    Even up thru the first several versions of Java 2 (SDK 1.4), the language had not entirely changed to usethe new Collections methods. For example, the DefaultListModel still uses the old methods, so if youare using a JList , you will need to use the old method names. There are hints that they plan to changethis, but still and interesting omission.

    Replacements for old met h ods

    The following methods have been changed from the old to the new Vector API.

    Old Method New Method

    void addElement (Object) boolean add (Object)

    void copyInto (Object[]) Object[] toArray ()

  • 8/3/2019 Understanding Java Exceptions

    13/43

    Object elementAt (int) Object get (int)

    Enumeration elements ()Iterator iterator ()ListIterator listIterator()

    void insertElementAt (Object, int) void add (index, Object)

    void removeAllElements () void clear ()

    boolean removeElement (Object) boolean remove (Object)

    void removeElementAt (int) void remove (int)

    void setElementAt (int) Object set (int, Object)

    Insuring use of t h e new API

    When you create a Vector, you can assign it to a List (a Collections interface). This will guarantee that onlythe List methods are called.

    Vector v1 = new Vector(); // allows old or new methods.

    Li st v2 = new Vector(); // allows only the new ( Li st) methods.

    Answer

    A checked exception is any subclass of Exception (or Exception itself), excluding class

    RuntimeException and its subclasses.

    Making an exception checked forces client programmers to deal with the possibility that the

    exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method

    Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its

    subclasses also are unchecked.

    With an unchecked exception, however, the compiler doesn't force client programmers either

    to catch the exception or declare it in a throws clause. In fact, client programmers may not

  • 8/3/2019 Understanding Java Exceptions

    14/43

    even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by

    String's charAt() method.

    Checked exceptions must be caught at compile time. Runtime exceptions do not need to be.

    Errors often cannot be, as they tend to be unrecoverable.

    Checked versus unchecked exceptions

    Unchecked exceptions :

    represent defects in the program (bugs) - often invalid arguments passed to a non-private method. Toquote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtimeexceptions represent conditions that, generally speaking, reflect errors in your program's logic andcannot be reasonably recovered from at run time."

    are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException,NullPointerException, or IllegalStateException

    a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation(and they almost always do not do so)

    Checked exceptions :

    represent invalid conditions in areas outside the immediate control of the program (invalid user input,database problems, network outages, absent files)

    are subclasses of Exception

    a method is obliged to establish a policy for all checked exceptions thrown by its implementation (eitherpass the checked exception further up the stack, or handle it somehow)

    It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).

    Example 1

  • 8/3/2019 Understanding Java Exceptions

    15/43

    Model Objects are the data-centric classes used to represent items in a particular domain. Model Objectconstructors need to handle both arbitrary user input, and input from underlying database ResultSets.

    Model Object constructors should throw checked exceptions :

    the program may have no direct control over user input. This is particularly true in web applications. Itseems safest for a Model Object to treat user input as having arbitrary, unvalidated content.

    it is not safe for an application to make any assumptions about the state of the database. The databaseis an independent entity, and its data may be changed by various means, outside of any particularapplication. For example, data load tools are commonly used to create an initial state for a newdatabase. Such data can easily violate the constraints built into a calling application. Thus, the safestassumption is to treat database ResultSets as having arbitrary, unvalidated content.

    Here is an example Model Object, taken from the WEB4J example application. Its constructor throwsModelCtorException (a checked exception) :

    package hirondelle.fish.main.resto;

    import hirondelle.web4j.model.ModelCtorException;

    import hirondelle.web4j.model.ModelUtil;

    import hirondelle.web4j.model.Id;

    import hirondelle.web4j.security.SafeText;

    import hirondelle.web4j.model.Decimal;

    import static hirondelle.web4j.model.Decimal.ZERO;

    import hirondelle.web4j.model.Check;

    import hirondelle.web4j.model.Validator;

    import static hirondelle.web4j.util.Consts.FAILS;

    /** Model Object for a Restaurant. */

  • 8/3/2019 Understanding Java Exceptions

    16/43

    public final class Resto {

    /**

    Full constructor.

    @param aId underlying database internal identifier (optional) 1..50 characters

    @param aName of the restaurant (required), 2..50 characters

    @param aLocation street address of the restaurant (optional), 2..50 characters

    @param aPrice of the fish and chips meal (optional) $0.00..$100.00

    @param aComment on the restaurant in general (optional) 2..50 characters

    */

    public Resto(

    Id aId, SafeText aName, SafeText aLocation, Decimal aPrice, SafeText aComment

    ) throws ModelCtorException {

    fId = aId;

    fName = aName;

    fLocation = aLocation;

    fPrice = aPrice;

    fComment = aComment;

    validateState();

    }

    public Id getId() { return fId; }

    public SafeText getName() { return fName; }

    public SafeText getLocation() { return fLocation; }

  • 8/3/2019 Understanding Java Exceptions

    17/43

    public Decimal getPrice() { return fPrice; }

    public SafeText getComment() { return fComment; }

    @Override public String toString(){

    return ModelUtil.toStringFor(this);

    }

    @Override public boolean equals(Object aThat){

    Boolean result = ModelUtil.quickEquals(this, aThat);

    if ( result == null ) {

    Resto that = (Resto) aThat;

    result = ModelUtil.equalsFor(

    this.getSignificantFields(), that.getSignificantFields()

    );

    }

    return result;

    }

    @Override public int hashCode(){

    if ( fHashCode == 0 ){

    fHashCode = ModelUtil.hashCodeFor(getSignificantFields());

    }

    return fHashCode;

    }

  • 8/3/2019 Understanding Java Exceptions

    18/43

    // PRIVATE //

    private final Id fId;

    private final SafeText fName;

    private final SafeText fLocation;

    private final Decimal fPrice;

    private final SafeText fComment;

    private int fHashCode;

    private static final Decimal HUNDRED = Decimal.from("100");

    private void validateState() throws ModelCtorException {

    ModelCtorException ex = new ModelCtorException();

    if ( FAILS == Check.optional(fId, Check.range(1,50)) ) {

    ex.add("Id is optional, 1..50 chars.");

    }

    if ( FAILS == Check.required(fName, Check.range(2,50)) ) {

    ex.add("Restaurant Name is required, 2..50 chars.");

    }

    if ( FAILS == Check.optional(fLocation, Check.range(2,50)) ) {

    ex.add("Location is optional, 2..50 chars.");

    }

    Validator[] priceChecks = {Check.range(ZERO, HUNDRED), Check.numDecimalsAlways(2)};

    if ( FAILS == Check.optional(fPrice, priceChecks)) {

    ex.add("Price is optional, 0.00 to 100.00.");

    }

  • 8/3/2019 Understanding Java Exceptions

    19/43

    if ( FAILS == Check.optional(fComment, Check.range(2,50))) {

    ex.add("Comment is optional, 2..50 chars.");

    }

    if ( ! ex.isEmpty() ) throw ex;

    }

    private Object[] getSignificantFields(){

    return new Object[] {fName, fLocation, fPrice, fComment};

    }

    }

    Example 2

    Args is a convenient utility class. It performs common validations on method arguments. If a validationfails, then it throws an unchecked exception. It is suitable for checking the internal consistency of program, but not for checking arbitrary user input.

    package hirondelle.web4j.util;

    import java.util.regex.*;

    /**

    Utility methods for common argument validations.

    Replaces if statements at the start of a method with

  • 8/3/2019 Understanding Java Exceptions

    20/43

    more compact method calls.

    Example use case.

    Instead of :

    public void doThis(String aText){

    if (!Util.textHasContent(aText)){

    throw new IllegalArgumentException();

    }

    //..main body elided

    }

    One may instead write :

    public void doThis(String aText){

    Args.checkForContent(aText);

    //..main body elided

    }

    */

    public final class Args {

    /**

    If aText does not satisfy {@link Util#textHasContent}, then

    throw an IllegalArgumentException.

  • 8/3/2019 Understanding Java Exceptions

    21/43

    Most text used in an application is meaningful only if it has visible content.

    */

    public static void checkForContent(String aText){

    if( ! Util.textHasContent(aText) ){

    throw new IllegalArgumentException("Text has no visible content");

    }

    }

    /**

    If {@link Util#isInRange} returns false, then

    throw an IllegalArgumentException.

    @param aLow is less than or equal to aHigh.

    */

    public static void checkForRange( int aNumber, int aLow, int aHigh ) {

    if ( ! Util.isInRange(aNumber, aLow, aHigh) ) {

    throw new IllegalArgumentException(aNumber + " not in range " + aLow + ".." + aHigh);

    }

    }

    /**

    If aNumber is less than 1, then throw an

    IllegalArgumentException.

    */

  • 8/3/2019 Understanding Java Exceptions

    22/43

    public static void checkForPositive(int aNumber) {

    if (aNumber < 1) {

    throw new IllegalArgumentException(aNumber + " is less than 1");

    }

    }

    /**

    If {@link Util#matches} returns false, then

    throw an IllegalArgumentException.

    */

    public static void checkForMatch(Pattern aPattern, String aText){

    if ( ! Util.matches(aPattern, aText) ){

    throw new IllegalArgumentException(

    "Text " + Util.quote(aText) + " does not match '" +aPattern.pattern()+ "'"

    );

    }

    }

    /**

    If aObject is null, then throw a NullPointerException.

    Use cases :

    doSomething( Football aBall ){

    //1. call some method on the argument :

  • 8/3/2019 Understanding Java Exceptions

    23/43

    //if aBall is null, then exception is automatically thrown, so

    //there is no need for an explicit check for null.

    aBall.inflate();

    //2. assign to a corresponding field (common in constructors):

    //if aBall is null, no exception is immediately thrown, so

    //an explicit check for null may be useful here

    Args.checkForNull( aBall );

    fBall = aBall;

    //3. pass on to some other method as parameter :

    //it may or may not be appropriate to have an explicit check

    //for null here, according the needs of the problem

    Args.checkForNull( aBall ); //??

    fReferee.verify( aBall );

    }

    */

    public static void checkForNull(Object aObject) {

    if ( aObject == null ) {

    throw new NullPointerException();

    }

    }

    // PRIVATE //

  • 8/3/2019 Understanding Java Exceptions

    24/43

    private Args(){

    //empty - prevent construction

    }

    }

    The Wrapper class of java represents the base class for a set of data sources. The javawrapper class doesn't comprises the constructors. All of the primitive wrapper classes inJava are immutable. Wrapper class offers library initialization services as well as the accessfor to the data source servers that the wrapper supports.Wrapper classes are used torepresent primitive values when an Object is required. I hope now you have understood

    what is wrapper class.

    Java is an object-oriented language and as said everything in java is an object. But what about theprimitives? They are sort of left out in the world of objects, that is, they cannot participate in the object activities, such as being returned from a method as an object, and being added to a Collection of objects,etc. . As a solution to this problem, Java allows you to include the primitives in the family of objects byusing what are called wrapper classes .

    There is a wrapper class for every primitive date type in Java. This class encapsulates a single value forthe primitive data type. For instance the wrapper class for int is Integer, for float is Float, and so on.Remember that the primitive name is simply the lowercase name of the wrapper except for char, whichmaps to Character, and int, which maps to Integer.

    The wrapper classes in the Java API serve two primary purposes:

    y To provide a mechanism to wrap primitive values in an object so that the primitives can beincluded in activities reserved for objects, like as being added to Collections, or returned from amethod with an object return value.

    y To provide an assortment of utility functions for primitives. Most of these functions are related tovarious conversions: converting primitives to and from String objects, and converting primitivesand String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

    The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapperclass with the new operator or by invoking a static method on the wrapper class. We will explore thisfurther in this article.

  • 8/3/2019 Understanding Java Exceptions

    25/43

    C reating Wrapper Objects with the new Operator

    Before we can instantiate a wrapper class, we need to know its name and the arguments its constructoraccepts. The name of the wrapper class corresponding to each primitive data type, along with the

    arguments its constructor accepts, is listed below:

    Primitive datatype-->Wrapper Class-->Constructor arguments

    y boolean--> Boolean--> boolean or String y byte--> Byte--> byte or Stringy char--> Character--> chary short--> Short--> short or Stringy int-->Integer--> int or Stringy long--> Long--> long or Stringy float-->Float--> float double or Stringy double-->Double--> double or String

    All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.Allthe wrapper classes except Boolean and Character are subclasses of an abstract class called Number,whereas Boolean and Character are derived directly from the Object class.All of the wrapper classesexcept Character provide two constructors: one that takes a primitive of the type being constructed, andone that takes a String representation of the type being constructed for example,

    Code:

    Boolean wboo = new Boolean("false");Boolean yboo=new Boolean(false);Byte wbyte = new Byte("2");Byte ybyte=new Byte(2);Short wshort = new Short("4");Short yshort = new Short(4);Integer wint = new Integer("16");Integer yint = new Integer(16);Long wlong = new Long("123");Long ylong = new Long(123);Float wfloat = new Float("12.34f");Float yfloat = new Float(12.34f);Double wdouble = new Double("12.56d");Double wdouble = new Double(12.56d);Character c1 = new Character('c');

    The value may also be passed as a variable, as shown in the following example:

    Code:

    boolean boo = false;Boolean wboo = new Boolean(boo);byte b = 2;Byte wbyte = new Byte(b);short s = 4;Short wshort = new Short(s);int i = 16;

  • 8/3/2019 Understanding Java Exceptions

    26/43

    Integer wint = new Integer(i);long l = 123;Long wlong = new Long(l);float f = 12.34f;Float wfloat = new Float(f);double d = 12.56d;

    Double wdouble = new Double(d);Note that there is no way to modify a wrapped value that is, the wrapped values are immutable. Towrap another value, you need to create another object.

    Wrapping Primitives Using a static Method

    All wrapper classes offers static valueOf() methods which give you another approach to creating wrapperobjects. Because it's a static method, it can be invoked directly on the class (without instantiating it), andwill return the corresponding object that is wrapping what you passed in as an argument.

    Both methods take a String representation of the appropriate type of primitive as their first argument, thesecond method (when provided) takes an additional argument, int radix, which indicates in what base(for example binary, octal, or hexadecimal) the first argument is represented for example,

    Code:

    Integer i2 = Integer.valueOf("101011", 2); // converts 101011 to 43 andassigns the

    // value 43 to the Integer ob j ecti2

    or

    Code:

    Float f2 = Float.valueOf("3.14f"); // assigns 3.14 to the Float ob j ect f2

    Methods to C reate Wrapper Objects

    Wrapper class-->method Signature-->method arguments

    y Boolean--> static Boolean valueOf( )-->boolean or String y Character--> static Character valueOf( )-->Chary Byte--> static Byte valueOf( )-->byte, String, or String and radixy Short--> static Short valueOf( )-->short, String, or String and radixy Integer--> static Integer valueOf( )-->int, String, or String and radixy Long--> static Long valueOf( )-->long, String, or String and radixy Float--> static Float valueOf( )-->float or Stringy Double--> static Double valueOf( )-->double or String

    The valueOf( ) method in the Character class accepts only char as an argument, while any otherwrapper class will accept either the corresponding primitive type or String as an argument.ThevalueOf( ) method in the integer number wrapper classes (Byte, Short, Integer, and Long) also acceptstwo arguments together: a String and a radix, where radix is the base.

  • 8/3/2019 Understanding Java Exceptions

    27/43

    Using Wrapper C onversion Utilities

    A storage capability without the corresponding retrieval capability is not of much use. Once you store aprimitive in a wrapper object, often you will want to retrieve the stored primitive at a later time.

    xxxV alue() method

    When you need to convert the value of a wrapped numeric to a primitive, use one of the manyxxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numericwrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numerictype.

    Code:

    Integer i2 = new Integer(42); // make a new wrapper ob j ectbyte b = i2.byteValue(); // convert i2's value to a byte primitive

    short s = i2.shortValue(); // another of Integer's xxxValue methodsdouble d = i2.doubleValue(); // yet another of Integer's xxxValue methods

    or

    Code:

    Float f2 = new Float(3.14f); // make a new wrapper ob j ectshort s = f2.shortValue(); // convert f2's value to a short primitiveSystem.out.println(s); // result is 3 (truncated, not rounded)

    xxx Parse xxx (String) method

    If you do not need to store a value in a wrapper but just want to perform a quick operation on it, such as

    converting the type, you can do it by using an appropriate static method of the appropriate wrapperclass. For example, all the wrapper classes except Character offer a static method that has the followingsignature:

    static parse(String s)

    The may be any of the primitive types except char (byte, short, int, long, float, double, orboolean), and the is the same as with the first letter uppercased; for example:

    static int parseInt (String s)

    Each of these methods parses the string passed in as a parameter and returns the correspondingprimitive type.

    For example, consider the following code:

    Code:

    String s = "123";int i = Integer.parseInt(s);

  • 8/3/2019 Understanding Java Exceptions

    28/43

    The second line will assign an int value of 123 to the int variable i.

    Methods to C onvert Strings to Primitive Types

    Wrapper Class--> Method Signature--> Method Arguments

    y Boolean--> static boolean parseBoolean( )--> String y Character--> Not Availabley Byte static byte parseByte( )--> String, or String and radixy Short--> static short parseShort( )--> String, or String and radixy Integer--> static int parseInt( )--> String, or String and radixy Long--> static long parseLong( )--> String, or String and radixy Float--> static float parseFloat( )--> Stringy Double--> static double parseDouble( )--> double or String

    parseX xx () and valueOf()

    The six parseXxx() methods (one for each numeric wrapper type) are closely related to the valueOf()method that exists in all of the numeric wrapper classes (plus Boolean). Both parseXxx() and valueOf()take a String as an argument, throw a NumberFormatException if the String argument is not properlyformed, and can convert String objects from different bases (radix), when the underlying primitive type isany of the four integer types.

    The difference between the two methods is:

    y parseXxx() returns the named primitive. y valueOf() returns a newly created wrapped object of the type that invoked the method.

    Some examples of these methods in action:

    Code:

    double d4 = Double.parseDouble("3.14"); // convert a String to aprimitiveSystem.out.println("d4 = " + d4); // result is "d4 = 3.14"Double d5 = Double.valueOf("3.14"); // create a Double ob j ectSystem.out.println(d5 instanceof Double ); // result is "true"

    The next examples involve using the radix argument, (in this case binary):

    Code:

    long L2 = Long.parseLong("101010", 2); // binary String to a primitive

    System.out.println("L2 = " + L2); // result is "L2 = 42"Long L3 = Long.valueOf("101010", 2); // binary String to Long ob j ectSystem.out.println("L3 value = " + L3); // result is "L2 value = 42"

    toString() method

    The class Object, the super class of all classes, has a toString() method. Since we know that all otherJava classes inherit from class Object, we also know that all other Java classes have a toString() method.The idea of the toString() method is to allow you to get some meaningful representation of a given

  • 8/3/2019 Understanding Java Exceptions

    29/43

    object. For instance, if you have a Collection of various types of objects, you can loop through theCollection and print out some sort of meaningful representation of each object using the toString()method, which is guaranteed to be in every class. All of the wrapper classes have a no-arg, nonstatic,instance version of toString(). This method returns a String with the value of the primitive wrapped in theobject for instance,

    Code:

    Double d = new Double("3.14");System.out.println("d = " + d.toString() ); // result is "d = 3.14"

    All of the numeric wrapper classes provide an overloaded, static toString() method that takes a primitivenumeric of the appropriate type (Double.toString() takes a double, Long.toString() takes a long, etc.),and, of course, returns a String with that primitive s value for example,

    Code:

    System.out.println("d = " + Double.toString(3.14); // result is "d = 3.14"

    Finally, Integer and Long provide a third toString() method. It is static, its first argument is the

    appropriate primitive, and its second argument is a radix. The radix argument tells the method to takethe first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, thenreturn the result as a String for instance,

    Code:

    System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe"

    toX xx String() method(Binary, He x adecimal, Octal)

    The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. Theseconversion methods, toXxxString(), take an int or long, and return a String representation of theconverted number, for example,

    Code:

    String s3 = Integer.toHexString(254); // convert 254 to hexSystem.out.println("254 in hex = " + s3); // result is "254 in hex = fe"String s4 = Long.toOctalString(254); // convert 254 to octalSystem.out.println("254 in octal = "+ s4); // result is "254 in octal = 376"

    You want to see an exampleprogram that usesthe indexer property in the C#language to provide a clear wayto access the internal elements

  • 8/3/2019 Understanding Java Exceptions

    30/43

    of the class. Properties such asindexers often access a backingstore, and with indexers youoften accept a parameter of inttype and access a backing storeof array type. Here we look at anexample of an indexer.

    A n indexer is a member that enables an object to beindexed in the same way asan array. Hejlsberg et al., p.

    498

    ExampleLet's look at a program thatcontains a class that has anindexer member, which itself contains a get accessor and a setaccessor. These accessors are

    implicitly used when you assignthe class instance elements inthe same way as you can assignelements in an array. Theindexer provides a level of indirection where you can insertbounds-checking, and in this wayyou can improve reliability and

    simplicity with indexers.Pr og r am that uses i ndexe r wi th i nt [C#]

    using System;

  • 8/3/2019 Understanding Java Exceptions

    31/43

    class Layout

    {

    string[] _values = new string[100]; // Backing store

    p ubl ic st r i n g th i s[ i nt numbe r ]

    {

    g et

    {

    // This is invoked when accessing Layout instanceswith the [ ].

    if (number >= 0 && number < _values.Length)

    {

    // Bounds were in range, so return the storedvalue.

    return _values[number];

    }

    // Return an error string.

    return "Error";

    }

    set

    {

    // This is invoked when assigning to Layout instanceswith the [ ].

    if (number >= 0 && number < _values.Length)

    {

    // Assign to this element slot in the internalarray.

    _values[number] = value;

    }

    }

  • 8/3/2019 Understanding Java Exceptions

    32/43

    }

    }

    class Program

    {

    static void Main()

    {

    // Create new instance and assign elements

    // ... in the array through the indexer.

    Layout layout = new Layout();

    layout[1] = "Frank Gehry";layout[3] = "I. M. Pei";

    layout[10] = "Frank Lloyd Wright";

    layout[11] = "Apollodorus";

    layout[-1] = "Error";

    layout[1000] = "Error";

    // Read elements through the indexer.

    string value1 = layout[1];

    string value2 = layout[3];

    string value3 = layout[10];

    string value4 = layout[11];

    string value5 = layout[50];

    string value6 = layout[-1];

    // Write the results.

    Console.WriteLine(value1);

    Console.WriteLine(value2);

    Console.WriteLine(value3);

  • 8/3/2019 Understanding Java Exceptions

    33/43

    Console.WriteLine(value4);

    Console.WriteLine(value5); // Is null

    Console.WriteLine(value6);

    }

    }

    Out p ut

    Frank Gehry

    I. M. Pei

    Frank Lloyd WrightApollodorus

    (null)

    Error

    O verview. This programincludes two classes: a Layoutclass containing an indexer wedefine, and a Program class thatcontains the Main entry point.The Layout class contains anindexer that has get and setmethod bodies. The get and setaccessors contain some logicthat ensure the array will not willbe accessed out-of-bounds. Thearray is termed the backing store

  • 8/3/2019 Understanding Java Exceptions

    34/43

    for the indexer property in thisexample.

    Main met h od output. The

    program includes the Main entrypoint, which assigns elements inthe Layout class backing store tovarious string literals. The stringliterals are the names of variousfamous architects from differenttimes and places. The elements -1 and 1000 are used as

    parameters to the indexer, butthese will not result in thebacking store being changedbecause they are not valid.However, no exceptions arethrown by this because of ourlogic.

    String Literal Finally, the program displays thefirst four valid elements from theLayout class, and then anelement that was not changedfrom null and then the result of an invalid access.

    Many parametersThe parameter list of yourindexer can vary depending onyour requirements. In acollection that maps string keysto values, you will want to have

  • 8/3/2019 Understanding Java Exceptions

    35/43

    an indexer that accepts aparameter of type string. Thiswill make the class have alookup function based on theindexer.

    If you are trying to simulate atwo-dimensional collection, youcan use two parameters in theindexer. Because indexers areactually regular methods in theimplementation, there are not

    many limitations regarding theparameter types. However, ref and out parameters are notallowed.

    .NET Framework

    Indexers have been usedthroughout the .NET Frameworkin Microsoft's own code since theframework was released. Almostall of the iterative collections andsearchable collections use

    indexers as an option to accesselements.

    This includes the Dictionarycollection, which allows you tolook up elements with the

  • 8/3/2019 Understanding Java Exceptions

    36/43

    indexer. The indexer for theDictionary often uses a stringparameter as the indexerargument. The ArrayList and Listclasses also use indexers tosimulate the built-in syntax of arrays in the C# language. Thismakes the List able to be used insyntactically the same way as anarray when assigning or readingelements that are allocated.

    D ictionary ExamplesHas h table ExamplesArrayList TipsListExamples

    Intermediate language

    Here we examine theintermediate language for theindexer shown in this article. Youcan see that a separatemetadata table exists that storesthe get_Item and set_Itemmethods, which implement thelogic for the get and setaccessors in the indexer.

  • 8/3/2019 Understanding Java Exceptions

    37/43

    In the .NET Framework, themetadata implements propertiesin the same way as methods butwith an additional table toprovide more information aboutthe type of methods. Thereshould be no performancedifference between an indexeraccess and a method thatinternally contain the same logic.

    Intermediate Language

    I nte r med i ate lan g ua g e f o r exam p le i ndexe r [ IL ]

    .property instance string Item

    {

    .get instance string Layout::get_Item(int32)

    .set instance void Layout::set_Item(int32, string)

    }

    SummaryWe looked at an example of theindexer type in the C# language,which is a property accessortype. Indexers have a somewhatmore complicated syntax thanother properties in the language,but the end result is they providea function that is used when youdo array-like accesses on theclass instance.

  • 8/3/2019 Understanding Java Exceptions

    38/43

    Indexers are very useful forhelping describe and defineintuitive types in a standard waythrough your class libraries.Additionally, they provide auseful level of indirection whereyou can insert bounds-checking,enhancing the reliability of arrayaccesses throughout yourprogram.

    C lass Examples

    Difference between Vector and ArrayList

    Vector: This class implements an array which can grow/shrink at run time depending upon the number

    of elements added or removed from it. Like an array, you can access the elements using an integer

    index.

    This class optimizes the storage management by having two fields capacity and capacityIncrement.

    The capacity is at least as large as the vector size. Its normally larger as the size of the vectorincreases in the chunks of size capacityIncrement.

    This class extends the class AbstractList and implements List , RandomAccess , Cloneable ,

    and Serializable interfaces. This class was retrofitted to implement the interface List as part of

    Java 2 Platform, SE enhancements to make it a part of the Collection framework. Unlike the newcollection implementations, Vector is synchronized.

    Vectors Iterators returned by iterator and listIterator methods (inherited

    from AbstractList ) are fail-fast. This means, if the vector is structurally modified after the creation

  • 8/3/2019 Understanding Java Exceptions

    39/43

    of the Iterator, in any way except by the methods provided by the Iterator itself, then the Iterator willthrow a ConcurrentModificationException i.e., no non-deterministic behavior, but a clean

    failure and that too very quickly. Thats why the name fail-fast. It fails and it fails fast :-) However,

    the Enumerations returned by Vector are not fail-fast.

    A rrayList: this class also implements the four interfaces implemented by Vector . Just like Vector , it

    also implements resizable-array. Most of the methods of thisclass: size , isEmpty , get , set , iterator , listIterator , etc. run in a constant time while the

    method add runs in amortized constant time. This means that O(n) time will be needed to add n

    elements. All other methods take constant time and that is lower than what the methods of theclass LinkedList take.

    Like Vector , this class also has a field called capacity. Its always at least as large as the size of the

    list. How this array should grow is not specified in the specifications except the fact that the addition

    of a new element should always take an amortized constant time.

    Difference between the two: The main difference between Vector and ArrayList is that Vector is

    synchronized while ArrayList is not. So, if multiple threads access an ArrayList concurrently then

    we must externally synchronize the block of code which modifies the list either structurally or simply

    modifies an element. Structural modification means addition or deletion of element(s) from the list.

    Setting the value of an existing element is not a structural modification.

    Collections.synchronizedList is normally used at the time of creation of the list to avoid any

    accidental unsynchronized access to the list.

    List synchronizedArrayList = Collections.synchronizedList(new ArrayList());

    Just like Vector , the Iterators of this class are also fail-fast. Any structural modification through any

    other method than what the Iterators provide will cause a ConcurrentModificationException .

    Wh at is difference between ArrayList and vector?

    Ans: )

    1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. InVector class each method like add(), get(int i) is surrounded with a synchronized

    block and thus making Vector class thread-safe.

  • 8/3/2019 Understanding Java Exceptions

    40/43

    2 ) Data growth - Internally, both the ArrayList and Vector hold onto their contentsusing an Array. When an element is inserted into an ArrayList or a Vector, the objectwill need to expand its internal array if it runs out of room. A Vector defaults todoubling the size of its array, while the ArrayList increases its array size by 50

    percent.

    H ow can Arraylist be sync h ronized wit h out using Vector?

    Ans) Arraylist can be synchronized using:

    Collection.synchronizedList(List list)

    Other collections can be synchronized:

    Collection.synchronizedMap(Map map)

    Collection.synchronizedCollection(Collection c)

    If an Employee class is present and its objects are added in an arrayList. Now Iwant t h e list to be sorted on t h e basis of t h e employeeID of Employee class. Wh atare t h e steps?

    Ans) 1) Implement Comparable interface for the Employee class and override thecompareTo(Object obj) method in which compare the employeeID

    2 ) Now call Collections.sort() method and pass list as an argument.

    Now consider that Employee class is a jar file.

    1) Since Comparable interface cannot be implemented, create Comparator andoverride the compare(Object obj, Object obj1) method .

    2 ) Call Collections.sort() on the list and pass comparator as an argument.

    Wh at is difference between H as h Map and H as hT able?

    Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are

    1. Access to the H ashtable is synchronized on the table while access to the H ashMapisn't. You can add it, but it isn't there by default.

  • 8/3/2019 Understanding Java Exceptions

    41/43

    2 . Another difference is that iterator in the H ashMap is fail-safe while the enumerator for the H ashtable isn't. If you change the map while iterating, you'll know. Fail-safe -if the H ashtable is structurally modified at any time after the iterator is created, inany way except through the iterator's own remove method, the iterator will throw aConcurrentModificationException

    3. H ashMap permits null values and only one null key, while H ashtable doesn't allowkey or value as null.

    Wh at is difference between Arrays and ArrayList ?

    Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means thatonce array is declared as :

    int [] intArray= new int[6];intArray[7] // will give ArraysOutOfBoundException.Also the size of array cannot be incremented or decremented. But with arrayList thesize is variable.Once the array is created elements cannot be added or deleted from it. But withArrayList the elements can be added and deleted at runtime.List list = new ArrayList();list.add(1);list.add(3);list.remove(0) // will remove the element from the 1st location.

    ArrayList is one dimensional but array can be multidimensional.int[][][] intArray= new int[3][ 2 ][1]; // 3 dimensional array

    Wh en to use ArrayList or LinkedList ?

    Ans) Adding new elements is pretty fast for either type of list. For the ArrayList,doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow

    because there's no efficient way to index into the middle of a linked list. Whenremoving elements, using ArrayList is slow. This is because all remaining elements inthe underlying array of Object instances must be shifted down for each removeoperation. But here LinkedList is fast, because deletion can be done simply bychanging a couple of links. So an ArrayList works best for cases where you're doingrandom access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

    Source : Read More - from java.sun

  • 8/3/2019 Understanding Java Exceptions

    42/43

    Consider a scenario. If an ArrayList h as to be iterate to read data only, w h at areth e possible ways and w h ich is t h e fastest?

    Ans) It can be done in two ways, using for loop or using iterator of ArrayList. Thefirst option is faster than using iterator. Because value stored in arraylist is indexedaccess. So while accessing the value is accessed directly from the index.

    Now anot h er question wit h respect to above question is if accessing t h roug h iterator is slow t h en w h y do we need it and w h en to use it.

    Ans) For loop does not allow the updation in the array(add or remove operation)inside the loop whereas Iterator does. Also Iterator can be used where there is no cluewhat type of collections will be used because all collections have iterator.

    Wh ich design pattern Iterator follows?

    Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern.The Iterator pattern is one, which allows you to navigate through a collection of datausing a common interface without knowing about the underlying implementation.Iterator should be implemented as an interface. This allows the user to implement itanyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without

    bothering about underlying implementation.

    Example of Iteration design pattern - Enumeration The class java.util.Enumeration isan example of the Iterator pattern. It represents and abstract means of iterating over acollection of elements in some sequential order without the client having to know therepresentation of the collection being iterated over. It can be used to provide auniform interface for traversing collections of all kinds.

    Wh y is it preferred to declare: List list = new ArrayList();instead of ArrayList = new ArrayList();

    Ans) It is preferred because:

    If later on code needs to be changed from ArrayList to Vector then only at thedeclaration place we can do that.The most important one If a function is declared such that it takes list. E.g voidshowDetails(List list);When the parameter is declared as List to the function it can be called by passing anysubclass of List like ArrayList,Vector,LinkedList making the function more flexible

  • 8/3/2019 Understanding Java Exceptions

    43/43

    H ow to sort list in reverse order?

    Ans) To sort the elements of the List in the reverse natural order of the strings, get areverse Comparator from the Collections class with reverseOrder(). Then, pass thereverse Comparator to the sort() method.

    List list = new ArrayList();

    Comparator comp = Collections.reverseOrder();

    Collections.sort(list, comp)

    H ow to sort list of strings - case insensitive?

    Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

    Can a null element added to a set ?

    Ans) A null element can be added only if the set contains one element because when asecond element is added then as per set defination a check is made to check duplicatevalue and comparison with null element will throw NullPointerException.