Java Static Field Initialization
===

I have just spent half an hour figuring this thing out, I have managed to fix my code, but I don't fully understand what is going on and wondered if someone could shed some light on it.

I have a **utils** type class, that contains a few static fields (a database connection endpoint for example) that are used by various other programs depending on the task at hand. Essentially a library.

This is how it looked previously (while still broken);

    //DBUtils.java
    public final class DBUtils {

        private static DBConnection myDBConnection = spawnDBConnection();
        private static DBIndex myDBIndex = null;

        private static DBConnection spawnDBConnection() {
            //connect to the database
            //assign a value to myDBIndex (by calling a method on the DBConnection object) <- IMPORTANT
            //myDbIndex NOT NULL HERE
            System.out.println("database connection completed");
            //return the DBConnection object
        }

        public static searchDB(String name) {
            //use the myDBIndex to find a row and return it
        }
    }

So briefly, I am using the static spawnDBConnection() method to assign a value to both **myDBConnection** and **myDBIndex**. This works perfectly, the first output line from my program is always "database connection completed", neither myDBConnection or myDBIndex are null 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 call to searchDB happens after the spawnDBConnection has finished, I have used the standard output extensively to show this. However, once inside the searchDB method, the value of myDBIndex is null! It's a static field, and it was not null by the end of spawnDBConnection, no other assignments have been made, and now it's null :(

The simple fix was to remove the "= null" so the field declaration now looks like;

    private static DBIndex myDBIndex;

Why did that make a difference? I'm thoroughly confused by this one.