Search code examples
javareturnstatic-constructorclass-constructors

Returning in a static initializer


This isn't valid code:

public class MyClass
{
    private static boolean yesNo = false;

    static
    {
        if (yesNo)
        {
            System.out.println("Yes");
            return; // The return statement is the problem
        }
        System.exit(0);
    }
}

This is a stupid example, but in a static class constructor we can't return;. Why? Are there good reasons for this? Does someone know something more about this?

So the reason why I should do return is to end constructing there.

Thanks


Solution

  • I think the reason is that initializers are carried together with field initializations (and with constructors, in the case of instance initializers). In other words, the JVM only recognizes one place to initialize static fields, and thus all initializations - whether in blocks or not - must be done there.

    So, for example, when you write a class:

    class A {
        static int x = 3;
        static {
            y = x * x;
        }
        static int z = x * x;
    }
    

    Then it's actually as if you've written:

    class A {
        static int x, y, z;
        static {
            x = 3;
            y = x * x;
            z = x * x;
        }
    }
    

    This is confirmed if you look at the disassembly:

    static {};
      Code:
       0:   iconst_3
       1:   putstatic       #5; //Field x:I
       4:   getstatic       #5; //Field x:I
       7:   getstatic       #5; //Field x:I
       10:  imul
       11:  putstatic       #3; //Field y:I
       14:  getstatic       #5; //Field x:I
       17:  getstatic       #5; //Field x:I
       20:  imul
       21:  putstatic       #6; //Field z:I
       24:  return
    

    So if you would have added a "return" somewhere in the middle of your static initializer it would also have prevented z from being calculated.