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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class BoxingDemo { public static void method1(Integer no){ //number 5 passed is boxed to Integer value System.out.println(no); } public static void main(String[] args) { new BoxingDemo().method1(5); //int is passed to a method which expects Integer } } |
Example for Unboxing:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class BoxingDemo { public static void main(String[] args) { Integer num1 = new Integer(10); int num2 = num1; //Auto -unboxing int num3 = num1.intValue(); //converting Integer to int using intValue() } } |