Autoboxing Flashcards

1
Q

What is the difference between Autoboxing and Unboxing ?

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give a pitfull related to autoboxing, the null reference and unboxing !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly