Skip to main content
9 of 16
added 291 characters in body
Olivier Grégoire
  • 14.5k
  • 3
  • 33
  • 56

Java, 62 bytes

enum H{H;{System.out.print("Hello, World!");System.exit(0);}} 

This is valid in Java 6. I believe it can work on Java 5 as well, but I haven't tested. This won't work in Java 4 or earlier (because enum didn't exist) and will not work in Java 7 or after (because the bypass[1] was "fixed").

enum H { // An enum is basically a class. H; // Static initialization of the mandatory instance, invoking the default constructor. // Happens before the existence check of "main"-method. // No constructor means default constructor in Java. { // Instance initialization block. // Executed in each constructor call. System.out.print("Hello, World!"); // duh! System.exit(0); // Exit before the JVM complains that no main method is found. // (and before it writes on stderr) } } 

Rough equivalence in Java as usually written

The above code is roughly equivalent to the following one.

class HelloWorld { public final static HelloWorld INSTANCE; static { INSTANCE = new HelloWorld(); } public HelloWorld() { System.out.print("Hello, World!"); System.exit(0); } } 

Proof of correctness

$ java -version java version "1.6.0_45" Java(TM) SE Runtime Environment (build 1.6.0_45-b06) Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode) $ javac H.java $ java H Hello, World! $ 

1: The bypass consists of the static execution of code when the class is being linked. Before Java 7, the main-method-containing class was no exception to the static initialization code. Afterwards, static initialization was delayed until the main method would actually be found.

Olivier Grégoire
  • 14.5k
  • 3
  • 33
  • 56