I have a class with an array as an instance variable/field, which is passed through from another class to the first method in this one.
I was under the impression that I should also be able to access it from another method without also passing it to that method but when I try, I get an NPE.
Here’s the code:
public class PLoop {
// instance variable
public Memory[] memList;
// method 1
public void memPass(Memory[] memLocList) {
memList = memLocList;
System.out.println(memList.length);
}
// method 2
public void accessArray() {
System.out.println(memList.length);
}
}
When the first method is called I get an integer printed to the console representing the length of the array but when the second method is called it’s NPE, suggesting not the same array.
The second method is called by clicking a button on a GUI. The method associated with this button only has a call along the lines of:
PLoop.accessArray();
Can anyone tell from this what I’m doing wrong?
-EDIT-
The calls to these methods come from two different classes, each of which declares an instance of PLoop:
proc = new PLoop();
The Methods in your PLoop classes are not static
Still you are calling
PLoop.accessArray();Can u please tell what is the real Scenario?
Just like @Jon Skeet told the code seems to be fine.The only possibility is that you may be
executing them out of sequence or you may be messing up with memLocList after the first
method is called.