A wrapper class wraps(encloses) around a data type (can be any primitive data type such as int, char, byte, long) and makes it an object.
Here are a few reasons why wrapper classes are needed:
- Allows
null
values. - Can be used in collection such as
List
,Map
, etc. - Can be used in methods which accepts arguments of
Object
type. - Can be created like Objects using
new ClassName()
like other objects:Integer wrapperInt = new Integer("10");
- Makes available all the functions that
Object
class has such asclone()
,equals()
,hashCode()
,toString()
etc.
Wrapper classes can be created in two ways:
- Using constructor:
Integer i = new Integer("1"); //new object is created
- Using
valueOf()
static operators:Integer i = Integer.valueOf("100"); //100 is stored in variable
It is advised to use the second way of creating wrapper classes as it takes less memory as a new object is not created.
No comments:
Post a Comment