x

Java – Wrapper Class

PREV     NEXT

In Java, numbers are usually used as primitive types.


Example:

int a = 5;

double salary = 25000.00;

  • Sometimes, we might need them to be used as objects instead of primitives.
  • Wrapper classes are helpful in this regard. They wrap the primitives in an object.
  • Wrapping is done by the compiler.
  • Converting primitive type to its respective reference type (object) is called boxing.
  • Converting the wrapper class object back to its primitive form is called unboxing. 
Primitive type Wrapper class
int Integer
short Short
long Long
double Double
float Float
byte Byte
char Character

The entire numeric wrapper classes – Integer, Long, Short, Byte, Double, Float are the subclasses of the class Number.


Methods of Number class Description
xxxValue() Converts the value of the given Number object to the primitive data type and the same is returned.
compareTo(xxx value) Compares the Number object to the argument. Returns 0 if the values are equal, +1 if value of calling Number is greater than value of argument Number, returns -1 otherwise
boolean equals(Object obj) Checks whether the value of calling Number “object” is equal to the value of object specified in the argument

Boxing / Unboxing is done in the following scenarios

  • When a method expects an object an argument but we pass a primitive type and vice versa.
  • Assignment of primitive type to a wrapper object and vice versa

Example:

Integer num = 5;

Float num2 = 1.2f;

  • While using the collection framework

Example:

ArrayList<Integer>  al = new ArrayList<Integer>();

al.add(5);

  • To use class methods for converting values to and from primitives / strings / other number systems

Example for Boxing:

Example for Unboxing:

PREV     NEXT



Like it? Please Spread the word!