I am new to Java and getting an error for the following case:
markerObj = null;
markerObj.sections = RowData[1];
But, after removing the first line, it works fine. What is the issue?
I am new to Java and getting an error for the following case:
markerObj = null;
markerObj.sections = RowData[1];
But, after removing the first line, it works fine. What is the issue?
This is exactly what it should do.
By assigning
null
to a variable, you explicitly state that it is no longer bound to an instance.So when you refer to
sections
in your code, you refer to thesections
member of a non-existent instance.you are trying to access the member of a null object.. that is the problem..
if you want a new instance.. then do the following..
Variable names are only references. They point to a space in memory (in the heap) which contains an object.
When you do
MyObj myObject = new MyObj();
, it does two things: create the object in memory, and point the myObject reference to it. So when you domyObject.sections
, it follows the reference, and check the sections part of your object in memory.Then when you do
myObject = null
, you basically destroy the link between your reference and your object in memory. Hence when doingmyObject.sections
, Java cannot follow the reference anymore because it's not pointing to anything. So it throws aNullPointerException
Note that the object itself is not destroyed by
myObject = null
, only the reference is nullified. The Garbage Collector then detects that your object is unreachable (if there's no other reference to it) and reclaims the memory, destroying the object.If you mark an object null you cannot assign values to its member variables.
The issue is that once you say
markerObj = null
it points it memory to null, ie it does not initiate any memory objects to it. So you get a null pointer error.By the way, if you are trying to instantiate its value as null then try to give its internal data property as null, ex.
TextView.setText(null);
Maybe it varies for the class that you are using. Check it out at developer.android.com.
You assign a value to a field of an object which is referred to by
marketObj
. However, sincemarkerObj
doesn't refer to any object (it is set tonull
), the assignment can't take place, and you will get a NullPointerException instead. If you don't want the exception to appear, you should first assign an object tomarketObj
.