This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Karthikeyan Ramaswamy wrote:
what is the main advantage of using wrapper classes?
and when should we use wrapper class?
Do you mean the wrapper classes corresponding to the Java primitives?
They should be used in situations when primitives cannot be used. The main situation is when you want to store primitives in one of the Java collections (which cannot handle primitives).
The use of the wrapper classes is greatly simplified by something called autoboxing. This means that Java automatically determines whether a primitive or a corresponding wrapper should be used. So it's rare that you need to use the wrapper classes explicitly.
Wrapper classes were introduced with the discussion of the primitive data types. Primitive values in Java are not
objects. In order to manipulate these values as objects, the java.lang package provides a wrapper class for each of the primitive data
types. All wrapper classes are final. The objects of all wrapper classes that can be instantiated are immutable, that is, their state cannot be
Although the Void class is considered a wrapper class, it does not wrap any primitive value and is not instantiable (i.e., has npou blic
constructors). It just denotes the Class object representing the keyword void. The Void class will not be discussed further in this section.
In addition to the methods defined for constructing and manipulating objects of primitive values, the wrapper classes also define useful
constants, fields, and conversion methods.
1) It is sometimes easier to deal with primitives as objects.
2) Moreover most of the collection classes store objects and not primitive data types.
3) The wrapper classes provide many utility methods also.
Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.