You are on page 1of 43

Understanding Java Exceptions

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are 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 by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch 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 1 division(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); } }

Download DivideException.java

An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The Exit main() message is never reached in the main method Output Computing Division. java.lang.ArithmeticException: / by zero Average : 25 Computing 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 provide a 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 a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also 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 special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions). Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically 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.

Checked and Unchecked Exceptions


Checked exceptions are subclasss of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. 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 the exception on to its caller Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesnt force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. Exception Statement Syntax Exceptions are handled using a try-catch-finally construct, which has the Syntax try { <code> } catch (<exception type1> <parameter1>) { // 0 or more <statements> } } finally { // finally block <statements> } try Block The java code that you think may produce an exception is placed within a try block for a suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception.. If an exception is generated within the try block, the remaining statements in the try block are not executed. catch Block Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed (Though the catch block throws an exception). finally Block A 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 transfer statement such as a return or a break statement, then this control statement determines how the execution will proceed regardless of any return or control statement present in the try or catch. The following program illustrates the scenario.

try { <code> } catch (<exception type1> <parameter1>) { // 0 or more <statements> } } finally { <statements> } // finally block

Download DivideException2.java Output Computing Division. Exception : / by zero Finally Block Executes. Exception Occurred result : -1

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)

The Common Language Runtime is the underpinning of the .NET Framework. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging. Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution. The Common Language Specification (CLS) is an agreement among language designers and class library designers to use a common subset of basic language features that all languages have to follow.

CLR Execution Model:

To know more about CLR /CTS/ CLS, articles and books - Click here!

Latest Resources:

Common Language Runtime Overview Good introduction to the CLR. The Common Language Infrastructure (CLI) The Shared Source CLI provides developers
with 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 about
the CLR.

What is Common Language Runtime?


The Common Language Runtime is the engine that compiles the source code in to an intermediate language. This intermediate language is called the Microsoft Intermediate Language. During the execution of the program this MSIL is converted to the native code or the machine code. This conversion is possible through the Just-In-Time compiler. During compilation the end result is a Portable Executable file (PE). This portable executable file contains the MSIL and additional information called the metadata. This metadata describes the assembly that is created. Class names, methods, signature and other dependency information are available in the metadata. Since the CLR compiles the source code to an intermediate language, it is possible to write the code in any language 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 memory themselves in the code. Instead the CLR will take care of that through a process called Garbage collection. This frees the programmer to concentrate on the logic of the application instead 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' and another class named 'SubClass' extends it. Now a 'SuperClass' reference can be assigned to an object 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 only be resolved at runtime as the compiler can't be sure of what type of object this reference would be pointing to at runtime. ...

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 andsuperClass2 are of type '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 these references actually refer to which version of the method - the super class version or the sub class version. 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 the method 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 Static Binding or Early Binding. All the instance method calls are always resolved at runtime, but all the static method calls are resolved at compile time itself and hence we have static binding for static method calls. Because static methods are class methods and hence they can be accessed using the class name itself (in fact they are encourgaed to be used using their corresponding class names only and not by using 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 not actually 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 (in fact, 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"; ... } ... ...

SuperClass superClass1 = new SuperClass(); SuperClass superClass2 = new SubClass(); System.out.println(superClass1.someVariable); System.out.println(superClass2.someVariable); ... Output: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 of the object reference only, which the compiler is capable of finding as early as at the compile time only and hence a static binding in this case. Anotherexample of static binding is that of 'private' methods as they are never inherited and the compile can resolve calls to any private method at compile time only. Update[June 24, 2008]: Read more to understand how field hiding in Java works? How is it different from static method hiding? - Field Hiding in Java >> Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar

Question

How 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 good idea. Vectors are extremely easy to use, and implement the Enumeration interface which 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 size myVector = new Vector(50);

Vector instances, like linked-lists, can grow dynamically. Once the vector reaches its maximum limit, it dynamically allocated resources and increases its maximum. However, if you know you're going to insert a large amount of data, you may want to specify an initial estimate. Vector instances can store any type of object - you simply insert an object via the addElement method.
for (int i = 1; i <= 20; i++) { myVector.addElement( new String ("I am string " + i)); }

When you wish to access the elements of the vector, you can look at individual elements (via their offset within the vector which is in ascending order), or you can traverse the entire list.
// Peek at element 5 System.out.println ("Element : " + myVector.elementAt(5) );

Traversing the entire vector is a common opperation. Remember, however, that when you insert an object via the addElement, it is implicitly cast to an instance of Object. Object is the base class of all other Java classes, and you'll need to explicitly cast it to another object type.
// Traverse entire list, printing them all out for (Enumeration e = myVector.elements(); e.hasMoreElements();) { String myString = (String) e.nextElement(); System.out.println(myString); }

Traversing a list is made extremely simple through the use of the Enumeration interface. Enumerations are great, because they allow you to easily process all elements, without having to determine the length of the vector, and manually accessing each element. Instead, it returns all the elements through the nextElement method. Vectors provide an easy interface, and have the advantage that they can grow dynamically, whereas arrays are of fixed length. Consider using them in your next Java project!

Java Notes: Vectors

Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand automatically when new data is added to them. The Java 2 Collections API introduced the similar ArrayList data structure. ArrayLists are unsynchronized and therefore faster than Vectors, but less secure in a multithreaded environment. The Vector class was changed in Java 2 to add the additional methods supported by ArrayList. See below for a reasons to use each. The description below is for the (new) Vector class. Vectors can hold only Objects and not primitive types (eg, int). If you want to put a primitive type in a Vector, put it inside an object (eg, to save an integer value use the Integer class or define your own class). If you use the Integer wrapper, you will not be able to change the integer value, so it is sometimes useful to define your own class.

To Create a Vector
You must import either import java.util.Vector; or import java.util.*;. Vectors are implemented with an array, and when that array is full and an additional element is added, a new array must be allocated. Because it takes time to create a bigger array and copy the elements from the old array to 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 y

Create a Vector with default initial size

Vector v = new Vector();


Create a Vector with an initial size

Vector v = new Vector(300); To Add elements to the end of a Vector v.add(s); // adds s to the end of the Vector v To get the 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 all elements in a Vector is to use a ListIterator. The advantage of an iterator is that it it can be used with other data structures, so that if you later change to using a linked list for example, you won't have to change your code. Here is an example of using an iterator to print all elements (Strings) in a vector. The two most useful methods are hasNext(), which returns true if there are more elements, and next(), which returns the next element.

ListIterator iter = v.listIterator(); while (iter.hasNext()) { System.out.println((String)iter.next()); } Common Vector Methods


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

v.add(o) v.add(i, o) v.clear() v.contains(o) v.firstElement(i) v.get(i) v.lastElement(i) v.listIterator() v.remove(i) v.set(i,o) v.size()

adds Object o to Vector v Inserts Object o at index i, shifting elements up as necessary. removes all elements from Vector v Returns true if Vector v contains Object o Returns the first element. Returns the object at int index i. Returns the last element. Returns a ListIterator that can be used to go over the Vector. This is a useful alternative to the for loop. Removes the element at position i, and shifts all following elements down. Sets the element at index i to o. Returns the number of elements in Vector v.

The array parameter can be any Object subclass (eg, String). This returns the v.toArray(Object[]) vector values in that array (or a larger array if necessary). This is useful when you need the generality of a Vector for input, but need the speed of arrays when processing the data.

Old and New Vector Methods


When the new Collections API was introduced in Java 2 to provide uniform data structure classes, the Vector class was updated to implement the List interface. Use the List methods because they are common to other data structure. If you later decide to use something other than a Vector (eg, ArrayList, or LinkedList, your other 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 use the new Collections methods. For example, the DefaultListModel still uses the old methods, so if you are using aJList, you will need to use the old method names. There are hints that they plan to change this, but still and interesting omission.

Replacements for old methods


The following methods have been changed from the old to the new Vector API. Old Method void addElement(Object) void copyInto(Object[]) New Method boolean add(Object) Object[] toArray()

Object elementAt(int)

Object get(int) Iterator iterator() ListIterator listIterator()

Enumeration elements()

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

boolean removeElement(Object) boolean remove(Object) void removeElementAt(int) void setElementAt(int) void remove(int) Object set(int, Object)

Insuring use of the new API


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

Vector v1 = new Vector(); List v2 = new Vector();

// allows old or new methods. // allows only the new (List) 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

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. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot 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 (either pass 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

Model Objects are the data-centric classes used to represent items in a particular domain. Model Object constructors 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. It seems 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 database is an independent entity, and its data may be changed by various means, outside of any particular application. For example, data load tools are commonly used to create an initial state for a new database. Such data can easily violate the constraints built into a calling application. Thus, the safest assumption is to treat database ResultSets as having arbitrary, unvalidated content. Here is an example Model Object, taken from the WEB4J example application. Its constructor throws ModelCtorException (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. */

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; }

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; }

// 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."); }

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 validation fails, 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.

<P>Replaces <tt>if</tt> statements at the start of a method with

more compact method calls.

<P>Example use case. <P>Instead of : <PRE> public void doThis(String aText){ if (!Util.textHasContent(aText)){ throw new IllegalArgumentException(); } //..main body elided } </PRE> <P>One may instead write : <PRE> public void doThis(String aText){ Args.checkForContent(aText); //..main body elided } </PRE> */ public final class Args {

/** If <code>aText</code> does not satisfy {@link Util#textHasContent}, then throw an <code>IllegalArgumentException</code>.

<P>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 <code>false</code>, then throw an <code>IllegalArgumentException</code>.

@param aLow is less than or equal to <code>aHigh</code>. */ 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 <tt>aNumber</tt> is less than <tt>1</tt>, then throw an <tt>IllegalArgumentException</tt>. */

public static void checkForPositive(int aNumber) { if (aNumber < 1) { throw new IllegalArgumentException(aNumber + " is less than 1"); } }

/** If {@link Util#matches} returns <tt>false</tt>, then throw an <code>IllegalArgumentException</code>. */ 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 <code>aObject</code> is null, then throw a <code>NullPointerException</code>.

<P>Use cases : <pre> doSomething( Football aBall ){ //1. call some method on the argument :

//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 ); } </pre> */ public static void checkForNull(Object aObject) { if ( aObject == null ) { throw new NullPointerException(); } }

// PRIVATE //

private Args(){ //empty - prevent construction }

The Wrapper class of java represents the base class for a set of data sources. The java wrapper class doesn't comprises the constructors. All of the primitive wrapper classes in Java are immutable. Wrapper class offers library initialization services as well as the access for to the data source servers that the wrapper supports.Wrapper classes are used to represent 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 the primitives? 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 by using what are calledwrapper classes. There is a wrapper class for every primitive date type in Java. This class encapsulates a single value for the 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, which maps 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 be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value. To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and 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 wrapper class with the new operator or by invoking a static method on the wrapper class. We will explore this further in this article.

Creating Wrapper Objects with the new Operator


Before we can instantiate a wrapper class, we need to know its name and the arguments its constructor accepts. 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 y y y y y y y boolean--> Boolean--> boolean or String byte--> Byte--> byte or String char--> Character--> char short--> Short--> short or String int-->Integer--> int or String long--> Long--> long or String float-->Float--> float double or String double-->Double--> double or String

All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the 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 classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one 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;

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. To wrap 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 wrapper objects. Because it's a static method, it can be invoked directly on the class (without instantiating it), and will 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, the second 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); assigns the i2 or


Code:

// converts 101011 to 43 and // value 43 to the Integer object

Float f2 = Float.valueOf("3.14f"); Methods to Create Wrapper Objects

// assigns 3.14 to the Float object f2

Wrapper class-->method Signature-->method arguments y y y y y y y y Boolean--> static Boolean valueOf( )-->boolean or String Character--> static Character valueOf( )-->Char Byte--> static Byte valueOf( )-->byte, String, or String and radix Short--> static Short valueOf( )-->short, String, or String and radix Integer--> static Integer valueOf( )-->int, String, or String and radix Long--> static Long valueOf( )-->long, String, or String and radix Float--> static Float valueOf( )-->float or String Double--> static Double valueOf( )-->double or String

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

Using Wrapper Conversion Utilities


A storage capability without the corresponding retrieval capability is not of much use. Once you store a primitive in a wrapper object, often you will want to retrieve the stored primitive at a later time. xxxValue() method When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numeric wrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numeric type.
Code:

Integer i2 = new Integer(42); // make a new wrapper object byte b = i2.byteValue(); // convert i2's value to a byte primitive short s = i2.shortValue(); // another of Integer's xxxValue methods double d = i2.doubleValue(); // yet another of Integer's xxxValue methods or
Code:

Float f2 = new Float(3.14f); short s = f2.shortValue(); System.out.println(s); xxx Parsexxx(String) method

// make a new wrapper object // convert f2's value to a short primitive // result is 3 (truncated, not rounded)

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 wrapper class. For example, all the wrapper classes except Character offer a static method that has the following signature: static <type> parse<Type>(String s) The <type> may be any of the primitive types except char (byte, short, int, long, float, double, or boolean), and the <Type> is the same as <type> 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 corresponding primitive type. For example, consider the following code:
Code:

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

The second line will assign an int value of 123 to the int variable i. Methods to Convert Strings to Primitive Types Wrapper Class--> Method Signature--> Method Arguments y y y y y y y y Boolean--> static boolean parseBoolean( )--> String Character--> Not Available Byte static byte parseByte( )--> String, or String and radix Short--> static short parseShort( )--> String, or String and radix Integer--> static int parseInt( )--> String, or String and radix Long--> static long parseLong( )--> String, or String and radix Float--> static float parseFloat( )--> String Double--> static double parseDouble( )--> double or String

parseXxx() 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 properly formed, and can convert String objects from different bases (radix), when the underlying primitive type is any of the four integer types. The difference between the two methods is: y y parseXxx() returns the named primitive. 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 a primitive System.out.println("d4 = " + d4); // result is "d4 = 3.14" Double d5 = Double.valueOf("3.14"); // create a Double object System.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); System.out.println("L2 = " + L2); Long L3 = Long.valueOf("101010", 2); System.out.println("L3 value = " + L3); toString() method

// // // //

binary result binary result

String is "L2 String is "L2

to a primitive = 42" to Long object value = 42"

The class Object, the super class of all classes, has a toString() method. Since we know that all other Java 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

object. For instance, if you have a Collection of various types of objects, you can loop through the Collection 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 the object 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 primitive numeric 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 take the first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, then return the result as a String for instance,
Code:

System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe" toXxxString() method(Binary, Hexadecimal, Octal) The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. These conversion methods, toXxxString(), take an int or long, and return a String representation of the converted number, for example,
Code:

String s3 = Integer.toHexString(254); System.out.println("254 in hex = " + s3); String s4 = Long.toOctalString(254); System.out.println("254 in octal = "+ s4);

// // // //

convert 254 to result is "254 convert 254 to result is "254

hex in hex = fe" octal in octal = 376"

You want to see an example program that uses the indexer property in the C# language to provide a clear way to access the internal elements

of the class. Properties such as indexers often access a backing store, and with indexers you often accept a parameter of int type and access a backing store of array type. Here we look at an example of an indexer. An indexer is a member that enables an object to be indexed in the same way as an array.Hejlsberg et al., p. 498

Example
Let's look at a program that contains a class that has an indexer member, which itself contains a get accessor and a set accessor. These accessors are implicitly used when you assign the class instance elements in the same way as you can assign elements in an array. The indexer provides a level of indirection where you can insert bounds-checking, and in this way you can improve reliability and simplicity with indexers.
Program that uses indexer with int [C#]

using System;

class Layout { string[] _values = new string[100]; // Backing store

public string this[int number] { get { // This is invoked when accessing Layout instances with the [ ]. if (number >= 0 && number < _values.Length) { // Bounds were in range, so return the stored value. return _values[number]; } // Return an error string. return "Error"; } set { // This is invoked when assigning to Layout instances with the [ ]. if (number >= 0 && number < _values.Length) { // Assign to this element slot in the internal array. _values[number] = value; } }

} }

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);

Console.WriteLine(value4); Console.WriteLine(value5); // Is null Console.WriteLine(value6); } }

Output

Frank Gehry I. M. Pei Frank Lloyd Wright Apollodorus (null) Error

Overview. This program includes two classes: a Layout class containing an indexer we define, and a Program class that contains the Main entry point. The Layout class contains an indexer that has get and set method bodies. The get and set accessors contain some logic that ensure the array will not will be accessed out-of-bounds. The array is termed the backing store

for the indexer property in this example. Main method output. The program includes the Main entry point, which assigns elements in the Layout class backing store to various string literals. The string literals are the names of various famous architects from different times and places. The elements 1 and 1000 are used as parameters to the indexer, but these will not result in the backing store being changed because they are not valid. However, no exceptions are thrown by this because of our logic. String Literal Finally, the program displays the first four valid elements from the Layout class, and then an element that was not changed from null and then the result of an invalid access.

Many parameters
The parameter list of your indexer can vary depending on your requirements. In a collection that maps string keys to values, you will want to have

an indexer that accepts a parameter of type string. This will make the class have a lookup function based on the indexer. If you are trying to simulate a two-dimensional collection, you can use two parameters in the indexer. Because indexers are actually regular methods in the implementation, there are not many limitations regarding the parameter types. However, ref and out parameters are not allowed.

.NET Framework

Indexers have been used throughout the .NET Framework in Microsoft's own code since the framework was released. Almost all of the iterative collections and searchable collections use indexers as an option to access elements. This includes the Dictionary collection, which allows you to look up elements with the

indexer. The indexer for the Dictionary often uses a string parameter as the indexer argument. The ArrayList and List classes also use indexers to simulate the built-in syntax of arrays in the C# language. This makes the List able to be used in syntactically the same way as an array when assigning or reading elements that are allocated. Dictionary ExamplesHashtable ExamplesArrayList TipsList Examples

Intermediate language

Here we examine the intermediate language for the indexer shown in this article. You can see that a separate metadata table exists that stores the get_Item and set_Item methods, which implement the logic for the get and set accessors in the indexer.

In the .NET Framework, the metadata implements properties in the same way as methods but with an additional table to provide more information about the type of methods. There should be no performance difference between an indexer access and a method that internally contain the same logic. Intermediate Language
Intermediate language for example indexer [IL]

.property instance string Item { .get instance string Layout::get_Item(int32) .set instance void Layout::set_Item(int32, string) }

Summary
We looked at an example of the indexer type in the C# language, which is a property accessor type. Indexers have a somewhat more complicated syntax than other properties in the language, but the end result is they provide a function that is used when you do array-like accesses on the class instance.

Indexers are very useful for helping describe and define intuitive types in a standard way through your class libraries. Additionally, they provide a useful level of indirection where you can insert bounds-checking, enhancing the reliability of array accesses throughout your program. Class 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 vector increases 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 new collection 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

of the Iterator, in any way except by the methods provided by the Iterator itself, then the Iterator will throw a ConcurrentModificationExceptioni.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. ArrayList: this class also implements the four interfaces implemented by Vector. Just like Vector, it also implements resizable-array. Most of the methods of this class: 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 the class 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 ArrayListis 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 aConcurrentModificationException.

What is difference between ArrayList and vector? Ans: ) 1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. How can Arraylist be synchronized without 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 I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps? Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(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 and override the compare(Object obj, Object obj1) method . 2) Call Collections.sort() on the list and pass comparator as an argument. What is difference between HashMap and HashTable? Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are 1. Access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know. Fail-safe if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException 3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null. What is difference between Arrays and ArrayList ? Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once 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 the size is variable. Once the array is created elements cannot be added or deleted from it. But with ArrayList 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 When 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. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random 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

Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest? Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly from the index. Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when 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 clue what type of collections will be used because all collections have iterator. Which 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 data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway 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 is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds. Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>(); Ans) It is preferred because: If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that. The most important one If a function is declared such that it takes list. E.g void showDetails(List list); When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible

How to sort list in reverse order? Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method. List list = new ArrayList(); Comparator comp = Collections.reverseOrder(); Collections.sort(list, comp) How 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 a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.

You might also like