Thursday, August 11, 2011

Quine in Java

I was doing some reading on self replicating code (the bad kind) and stumbled onto this, which is very cool in an old school sort of way.

From Wikipedia:
A quine is a computer program which takes no input and produces a copy of its own source code as its only output. The standard terms for these programs in the computability theory and computer science literature are self-replicating programs, self-reproducing programs, and self-copying programs.

Here is a nice walk through of the thought process of creating a quine in Java:
http://blogs.adobe.com/charles/2011/01/my-adventure-writing-my-first-quine-in-java.html

The finished product of this blog looks like this (This was tested in eclipse. Note that the main function is only two lines.  The wrapping is just so that it is easier to read on this blog):

public class Quine {
    public static void main (String[] args) {
        String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;%3$c%4$c%4$cSystem.out.printf(s, s, 34, 10, 9);%3$c%4$c}%3$c}";
        System.out.printf(s, s, 34, 10, 9);
    }
}