Skip to content

thmuch/java-quine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java quines

A quine is a computer program that outputs its own source code.

In 1998, we set out a challenge for some students that we were teaching Java: They were to create the shortest Java code that outputs itself. In the end, it became a challenge for us tutors. I found a solution that needed merely 208 bytes. More recent Java versions need even fewer bytes:

The actual quines are linked above. But as they are one-liners (for briefness), they are pretty hard to read. So here is my Java 1.0 quine, formatted slightly better:

class S {
    public static void main(String[] a) {
        System.out.print((s += (char) 34) + s + ';' + '}');
    }

    static String s = "class S{public static void main(String[]a){System.out.print((s+=(char)34)+s+';'+'}');}static String s=";
}

And, for comparison, the Java 10 quine with better formatting:

class V {
    public static void main(String[] a) {
        var f = "class V{public static void main(String[]a){var f=%c%s%1$c;System.out.printf(f,34,f);}}";
        System.out.printf(f, 34, f);
    }
}

Using Java 21 preview features, it gets even shorter (again, formatted for readability):

void main() {
    var f="void main(){var f=%c%s%1$c;System.out.printf(f,34,f);}";
    System.out.printf(f,34,f);
}

Remember, these formatted code examples are no quines – but they are easier to read to get the idea how quines work.

Disclaimer

Do not use in production 😉

Credits

While the Java 1.0 quine is completely my own work, the Java 1.5 version is based on this example IIRC. I then used the Java 1.5 code to write the even shorter version for Java 10+.

About

Quines (programs that output their own source code) for different Java versions

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages