Skip to main content

Posts

Showing posts from September 17, 2019

What is a NullPointerException? And how to fix it?

When you declare a reference variable (object) you are actually making a pointer to an object. Consider a variable of primitive type int: int x; x = 10; In this sample, the variable x is an int and Java will initialize it to 0 for you. When you allocate it the value of 10 on the next line, your value of 10 is written into the memory location denoted by x. But, when you attempt to declare a reference type, slightly different happens. Take the following code: Integer num; num = new Integer(10); The 1 st declares a variable named num, but it does not truly hold a primitive value yet. In its place, it has a pointer (because the type is Integer which is a reference type). Meanwhile you have not yet said what to point to, Java sets it to null, which means "I am pointing to nothing". In the 2 nd line, the new keyword is used to instantiate (or generate) an object of type Integer and the pointer variable num is allocated to that Integer object.