What will be the output of this code? Please explain how the Autoboxing or unboxing id done here.
class MyBoolean
{
Boolean[] bool = new Boolean[5];
public static void main(String[] args)
{
new MyBoolean().myMethod();
}
public void myMethod()
{
if(bool[1]==true)
{
System.out.println("It's true");
}
else
{
System.out.println("It's false");
}
}
}
The code fails with a NullPointerException
because bool[1]
contains null
. According to the Java Language Specification, Section 5.1.8, the unboxing of a Boolean
is done by calling booleanValue()
on the Boolean
reference. Since in this case, the reference is null
, you get an NPE.
In a comment on another answer, you wrote:
The reason to ask this question is to understand if we get the NPE via AutoUnBoxing or via AutoBoxing. In my understanding its due to AutoBoxing.
It's due to unboxing (extracting a primitive from a reference type), not boxing (wrapping a primative in a reference type). Specifically, from JLS Section 15.21.2 (Boolean Equality Operators ==
and !=
):
If one of the operands is of type
Boolean
, it is subjected to unboxing conversion (§5.1.8).
Run fails: bool[1] is null and comparison throw NullPointerException.
Boolean
in bool[1]
to a boolean
primitive (lower case). It's that conversion that causes the NPE, because there's no Boolean
in bool[1]
at all - T.J. Crowder 2012-04-05 22:01
Explanation. bool is an array of Boolean objects, but since it is not initialized all the elements in the array are "null". Remember "null" is not an object. Now when we try to access the elements of the bool array using bool[1] at that point the compiler try to Autobox nulls to Boolean objects and then we get NPE - Vibhor 2012-04-05 22:15