The first line declares a variable named num
, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you have not yet said what to point to, Java sets it to null
, which means "I am pointing to nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer
and the pointer variable num
is assigned to that Integer
object.
The NullPointerException
occurs when you declare a variable but did not create an object and assign to the variable before trying to use the contents of the variable (called dereferencing). So you are pointing to something that does not actually exist.
Dereferencing usually happens when using .
to access a method or field, or using [
to index an array.
If you attempt to dereference num
BEFORE creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized
," but sometimes you may write code that does not directly create the object.