What is a wrapper class?
A wrapper class is a class whose object wraps around a basic primitive data types. When we create an object to a wrapper class, it contains a field which could store a primitive data type.
Why do we need a wrapper class?
- Primitive types doesn’t allow to store “null” as a value which is possible through a wrapper class.
- Java Collection API stores only object, not primitive types.
- An object is needed to support synchronization in multi-threading.
Wrapper classes in Java
Primitive data types | Wrapper Class |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
Wrapper classes are immutable in Java
All primitive wrapper classes are immutable in Java, so operations like addition/subtraction results in a new object instead of modifying the old object.
package wrapper;
public class Immutability {
public static void main(String[] args) {
Integer num = new Integer("100");
System.out.println("Number before increment: " + num);
increment(num);
System.out.println("Number after increment: " + num);
}
private static void increment(Integer num) {
num += 1;
}
}
Output of the above program –
Number before increment: 100
Number after increment: 100