Search code examples
javanullpointerexceptionaccess-modifiers

Java Access Modifier and NullPointerException


I am getting a runtime error in my Java code, and I'm trying to understand the reason behind it. The two static access modifiers between double asterisks are the items in question. The code compiles with or without these modifiers (asterisks removed of course). But at runtime, it only runs without an error when the modifiers are present. Why is this? The error generated at runtime when the static modifiers are not present is pasted below the code. Thank you so much for your help!

Here is the code:

public class Blue {


    public int[][] multiArray(int x, int y){

        int[][] myArray = new int[x][y];
        return myArray;

    }

    static Blue blueObject = new Blue();

    public **static** int[][] one = blueObject.multiArray(3,3); 
    public **static** int[][] two = blueObject.multiArray(3,3);

    public static void main(String[] args){

        System.out.println("Hello world!");

    }

}

Error generated at runtime without the static access modifiers:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
    at Blue.<init>(Blue.java:13)
    at Blue.<clinit>(Blue.java:11)

Solution

  • The issue is related to how JVM deals with class loading and how your class is defined. When you have static int[][] one, it works because JVM read/load static code by the same order as they represented in the class. So when JVM tries to initialize int[][] one, the static Blue blueObject is ready for use.

    However if you declare int[][] one as non-static, when JVM try to create static Blue blueObject, it has to create a fully initialized Blue object and assign it to static blueobject, so it tries to initialize the int[][]; but at this moment, your static blueObject.multiArray(3,3); is not ready yet.

    I hopethis make sense to your question.