3

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'?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Axarydax
  • 16,353
  • 21
  • 92
  • 151
  • 3
    The JLS states that a `return` statement within a `static` initializer is illegal [here](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7). – Sotirios Delimanolis Sep 24 '14 at 16:14
  • This looks like a JVM question, not a JLS one. The too specs do differ at times, and this may be one of them. – Chris K Sep 24 '14 at 16:15
  • see at : http://stackoverflow.com/questions/11118226/how-to-return-from-a-static-initialization-block-in-java – Nicola Avancini Sep 24 '14 at 16:17
  • @SotiriosDelimanolis turn that into an answer, so I can accept it – Axarydax Sep 24 '14 at 16:18
  • @Axarydax I do not recall anything in the JVM spec that prohibits that (obviously there is in the JLS spec). Probably the best way to find out would be to try it. You could use a jvm assembler tool like http://jasmin.sourceforge.net/ – Chris K Sep 24 '14 at 16:18
  • @ChrisK How isn't it a JLS question? The JVM supports stuff not in Java. – Dave Newton Sep 24 '14 at 16:18
  • @DaveNewton from the question 'so would it be possible, theoretically, to create a bytecode'... the JVM is capable of doing some things that the JLS does not allow, such as having return type as part of the method signature. Perhaps the OP could clarify. – Chris K Sep 24 '14 at 16:19
  • 1
    @ChrisK I was able to create the .class file with Jasmin, thanks, so it runs in JVM without problems. That makes me wondering why would the return statement be forbidden in the JLS. – Axarydax Sep 24 '14 at 16:24
  • @ChrisK That's my point; the JVM supports functionality not available at the Java level. – Dave Newton Sep 24 '14 at 17:11
  • @ChrisK "there is no caller to return to" Depends whether you think this is a question about the language or, about the implementation. (nobody on this thread seems to know). There _is_ a caller, but like you said, it's not any method in the program's source code. – Solomon Slow Sep 24 '14 at 17:12

1 Answers1

5

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724