I just spent half an hour trying to figure it out, I managed to fix my code, but I donโt quite understand what was going on, and I wondered if anyone could shed some light on it.
I have a utils class that contains several static fields (for example, the database connection endpoint) that are used by various other programs depending on the task. Essentially a library.
Here's how it looked earlier (still broken);
In short, I use the static spawnDBConnection () method to assign values โโto both myDBConnection and myDBIndex . This works fine, the first output line from my program is always "database connection completed", neither myDBConnection nor myDBIndex are zero at the end of the spawnDBConnection () method, everything is as it should be.
My external program looks like this:
//DoSomethingUsefulWithTheDatabase.java public final class DoSomethingUsefulWithTheDatabase { public static void main(String args[]) { DBUtils.searchDB("John Smith"); //fails with NullPointerException on myDBIndex! } }
This searchDB call occurs after spawnDBConnection completes, I made extensive use of standard output to show this. However, once inside the searchDB method, the value of myDBIndex is null! This is a static field, and it was not null at the end of spawnDBConnection, no other assignments were made, and now it is null :(
A simple fix was to remove "= null" so that the field declaration now looks like;
private static DBIndex myDBIndex;
Why did this make a difference? I am completely confused by this.
lynks
source share