Boxing and Unboxing, AutoBoxing
In Java, there are primitive data types and Wrapper classes
Primitive data types: int, long, float, double, boolean, etc.Wrapper classes: Integer, Long, Float, Double, Boolean, etc.
-
Boxing-
Converting a Primitive data type to a Wrapper class
int n = 100; Integer num = new Integer(n);
-
-
Unboxing-
Converting a Wrapper class to a Primitive data type
Integer num = new Integer(100); int n = num.intValue();
-
-
Since JDK 1.5, the Java compiler automatically performs conversion when boxing and unboxing are needed ->
Auto Boxing & Auto Unboxing-
This feature is only available when there is a corresponding
Primitive data typefor each Wrapper class// Auto Boxing int n = 100; Integer num = n; // Auto Unboxing Integer num = new Integer(100); int n = num;
-
-
Caution:
Performance- Although Auto Boxing and Auto Unboxing are provided for convenience, since additional computation work is needed internally, it is better to implement
same-type operationsso thatAuto Boxing & Auto Unboxingdoes not occur
- Although Auto Boxing and Auto Unboxing are provided for convenience, since additional computation work is needed internally, it is better to implement