Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - can we return from within an initializer? [duplicate]

Tags:

java

jls

Why there cannot be multiple exit points from a static initializer? Does Java Language specification state so?

When trying to compile code as:

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

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

Compiler prints out an error: return outside method

Java disassembly with javap shows that static is a void method, so would it be possible, theoretically, to create a bytecode that would have multiple 'returns'?

like image 414
Axarydax Avatar asked Aug 25 '26 04:08

Axarydax


1 Answers

The JLS states that a return statement within a static initializer is illegal here.

like image 183
Sotirios Delimanolis Avatar answered Aug 27 '26 16:08

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!