Autoboxing Flashcards
What is the difference between Autoboxing and Unboxing ?
In Java, autoboxing and unboxing are mechanisms that simplify the conversion between primitive types and their corresponding wrapper classes.
Autoboxing
Autoboxing is the automatic conversion of a primitive type (like int, char, double, etc.) to its corresponding wrapper class (like Integer, Character, Double, etc.) by the Java compiler.
Example: If you assign an int to an Integer object, Java will automatically convert the int to an Integer object.
Unboxing
Definition: Unboxing is the automatic conversion of a wrapper class (like Integer, Character, Double, etc.) back to its corresponding primitive type (like int, char, double, etc.) by the Java compiler.
Integer N = new Integer(20);
int a= N; // Unboxing
List<Integer> liste = new ArrayList<Integer> ();
liste.add(33);
method(new Integer(127));//Unboxing</Integer></Integer>
Give a pitfull related to autoboxing, the null reference and unboxing !
List<Integer> liste = new ArrayList<Integer> ();
liste.add(null);
System.out.println(liste);// Prints [null]
System.out.println(liste.get(0));// null
int n =liste.get(0);// java.lang.NullPointerException</Integer></Integer>
Java expects an int value, but null cannot be converted to int.
The Java compiler and runtime system do not handle null values for primitives, leading to a NullPointerException.