Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why using static keyword in Java in the following case works differently?

When the following code is executed, an exception java.lang.StackOverflowError is thrown.

main() method in a class Something:

class Something {
    public static void main(String args[]) {
        System.out.println(Color.RED);
        System.out.println(Color.GREEN);
        System.out.println(new Color().BLUE);
    }
}

Here is the class Color:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Color {
    public static final Color RED = new Color();
    public static final Color GREEN = new Color();
    public final Color BLUE = new Color();
}

But when I put static behind final in public final Color BLUE = new Color();, the program runs correctly without throwing StackOverflowError. Why does not it throw the Exception? Is it that when JVM identifies that some static object is referring to itself then it should stop? How does Java handle this?

>Solution :

Without the static:

class Color {
  public final Color BLUE = new Color();
}

To create an instance of Color (via new Color()), you have to create an instance of Color for the BLUE field; to create that instance of Color, you have to create an instance of Color for the BLUE field; to create that instance of Color, you have to create an instance of Color for the BLUE field, etc. See the problem?

If you make it static:

class Color {
  public static final Color BLUE = new Color();
}

You aren’t reinitializing BLUE every time you create a new instance of Color. An instance of Color is created when the class is initialized, and that’s that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading