Wrapper Classes
Autoboxing
Unboxing
Java Wrapper classes provide a mechanism to use primitive data types as objects.
Primitive Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
Why do we need wrapper classes ?
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<int> arr = new ArrayList<int>(); // Error
}
}
Why do we need wrapper classes ?
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
}
}
Why do we need wrapper classes ?
2. Synchronization
Java synchronization works with objects in Multithreading.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
class Main {
public static void main(String[] args) {
int x = 5;
float y = 3.14F;
long z = 10000;
Integer intObj = x;
Float floatObj = y;
Long longObj = z;
}
}
The automatic conversion of a wrapper object to its corresponding primitive data type is known as Unboxing.
class Main {
public static void main(String[] args) {
Integer x = 5;
Float y = 2.4F;
Long z = 10000L;
int a = x;
float b = y;
long c = z;
}
}