12

I came across this little quine program, written without main method:

enum f {
  f;
  System z;
  String s="enum f{f;System z;String s=%c%s%1$c;{z.out.printf(s,34,s);z.exit(0);}}";
  {z.out.printf(s,34,s);
  z.exit(0);}
}

Can somebody explain how does this work? Thanks.

Uros K
  • 3,274
  • 4
  • 31
  • 45
  • Interesting, but how do you let it run? EDIT: The file has to be named `f.java`, so you compile it with `javac f.java` – mtsz Feb 02 '12 at 22:27
  • 1
    Yes. You compile it with `javac f.java` and run it with `java f`. It works with jdk6, but not with 7. – Uros K Feb 02 '12 at 22:34
  • After I've read the description you posted, I got it running, thanks nevertheless :) – mtsz Feb 02 '12 at 22:37
  • 3
    @mtsz Up to at least Java 6 you could run classes without a `main` method, but with a static initializer; the JVM would complain about the missing method, but after loading the class, which would execute the static initializer. I just tried it out with Java 7 and it complains immediately, before running the static initializer. Looks like this is a change in Java 7. – Jesper Feb 02 '12 at 22:40
  • Thanks @Jesper, I didn't know it was even possible to run code with only a static initializer. It's always great to learn something new :) – mtsz Feb 02 '12 at 22:44
  • 1
    Fun fact: Java WebStart also loads the main class without initialising it, so wont run the static initialiser if the main method is not present. – Tom Hawtin - tackline Feb 03 '12 at 00:29

1 Answers1

9

Lines 5 and 6 are an instance initializer. It is called when the class is instantiated. Since this is an enum with one constant named f, it is going to be instantiated once and the instance initializer block is executed.

Note that z is null, but out is a static member of class System, so you can call z.out.printf() anyway. The printf statement takes the string s as a format string with two arguments, 34 and s itself.

34 is the ASCII code for double quote ". It is filled in for the %c and %1$c in the format string. The %s in the format string is replaced by the format string s itself.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Jesper
  • 202,709
  • 46
  • 318
  • 350