Autoboxing and Unboxing in Java
Java 1.5 version has introduced Autoboxing and Unboxing in Java.Autoboxing Conversion :
Converting primitive types to corresponding reference wrapper types called as "Autoboxing" and this happens run time implicitly.
Following are Autoboxing conversion in Java allow.
1) boolean to type Boolean
2) byte to type Byte
3) short to type Short
4) char to type Character
5) int to type Integer
6) long to type Long
7) float to type Float
8)double to type Double
Boxing conversion may result in an OutOfMemoryError if new instances are created.
If we have int to Integer.. which means first have to allocate memory for int and than boxing conversion to Integer wrapper class instance memory allocation.
Autoboxing Example :
package org.java.w3schools.autoboxing;
public class AutoboxingExample {
public static void main(String[] args) {
int i = 100;
Integer integer = i; // Autoboxing
double d = 190;
show(d); // Autoboxing
}
public static void show(Double d) {
System.out.println("double : " + d);
}
}
Unboxing Conversion :
Converting reference types to corresponding primitive types called as "Unboxing" and this also happens runtime implicitly.
Following are Unboxing conversion in Java allow.
1) Boolean to type boolean
2) Byte to type byte
3) Short to type short
4) Character to type char
5) Integer to type int
6) Long to type long
7) Float to type float
8) Double to type double
If reference is null, than unboxing result in NulllPointerEception.
Unboxing Example :
package org.java.w3schools.unboxing;
public class UnboxingExample {
/**
* @param args
*/
public static void main(String[] args) {
Integer integer = new Integer(100);
int i = integer; // Unboxing
display(new Boolean(false)); // Unboxing
}
public static void display(boolean status) {
System.out.println("Status :: " + status);
}
}
Note: Garbage Collector has to do cleanup boxing cached objects. Good to avoid boxing techniques for error proneing.
No comments:
Post a Comment
Please do not add any spam links in the comments section.