Java - can we return from an initializer?

Why can't there be multiple exit points from a static initializer? Does the Java language spec indicate?

When trying to compile the code like:

class HelloWorldApp {
    static {
        if(1 > 2)
          return;
        System.out.println("static"); 
    }

    public static void main(String[] args) {
        System.out.println("Hello World!"); 
    }
}

      

The compiler gives an error message: return outside method

Disassembling Java with the help javap

shows what static

is a void method, so in theory it is possible to create a bytecode that has multiple "returns"?

+3


source to share


1 answer


The JLS states that the operator return

in the initializer static

is illegal here .



+5


source







All Articles