Autoboxing & Unboxing

Agenda
-
Wrapper Classes
-
Autoboxing
-
Unboxing



Wrapper Classes
Java Wrapper classes provide a mechanism to use primitive data types as objects.

Wrapper Classes
Primitive Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |

Wrapper Classes
Why do we need wrapper classes ?
-
Collections
The Java collections require objects instead of primitive types.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<int> arr = new ArrayList<int>(); // Error
}
}

Wrapper Classes
Why do we need wrapper classes ?
-
Collections
The Java collections require objects instead of primitive types.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
}
}

Wrapper Classes
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.

Autoboxing
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.

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;
}
}
Autoboxing
By Tarun Luthra
Autoboxing
- 3,142