1
\$\begingroup\$

Here's an example of a static initializer in Java.

It is possible to launch a program without a main method in Java using a static initializer and it's way shorter. It doesn't work on ideone.com but in my IDE, my code in static is executed even if I have no main. The JVM throws an exception when you do that (since there's no main method) but it happens after the code is executed and you can escape it using System.exit(0);.

Here's a comparison in length:

class P{public static void main(String[]a){}}
class P{static{System.exit(0);}}

Can I use it for my code golf ? Is it allowed ? Is it allowed to ommit the System.exit statement and ignore the exception ? Thanks

EDIT: I'm not able to reproduce the behavior I had in my IDE in command line. I was able to to this using IntelliJ. I don't know what command line IntelliJ is running. I will come back with a specific java version and a command line. Should of wait before posting, sorry.

\$\endgroup\$
  • \$\begingroup\$ seems legit, but I'm curious how it works. Do you just tell the interpreter to load a single class and then finish? \$\endgroup\$ – John Dvorak Mar 3 '17 at 14:28
  • \$\begingroup\$ What version of Java are you seeing this behavior with? \$\endgroup\$ – Poke Mar 3 '17 at 14:33
  • \$\begingroup\$ @JanDvorak Static blocks are executed once the class is loaded by the JVM, before it knows if there are other classes and if one of them might have a main method. \$\endgroup\$ – Pavel Mar 3 '17 at 14:50
  • 1
    \$\begingroup\$ How do you compile/run this from the command line? \$\endgroup\$ – Dennis Mar 3 '17 at 15:07
5
\$\begingroup\$

Yes with conditions

I believe this is only valid in Java 6 since Java 7 checks for a main method before initialization (I don't know if things changed in Java 8+). You'll get something like this:

Error: Main method not found in class S, please define the main method as:
   public static void main(String[] args)

Because of this you'd need to make sure all of your answers using this method specify Java 6 specifically.

Additionally it's worth noting that an answer using this method cannot take input from program arguments and cannot make use of return statements for output. You'll be restricted to System.out for the most part.

More Information

If you're running the above code as a Java Applet you don't need a main method and can even work in the constructor rather than just a static initializer. This method can be used in Java 7 (example). This can be achieved with an IDE's "Run As Java Applet" or by disabling the security manager and using appletviewer, which comes with the JDK (unless you're still able to view applets in web browsers. I don't think chrome allows this).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .