What is a NullPointerException, and how do I fix it?

0 like 0 dislike
25 views

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

by (550 points) | 25 views

1 Answer

0 like 0 dislike

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.

by (1.2k points)
110,608 questions
257,186 answers
0 comments
1,117 users