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:
- Java 1.0 quine (208 bytes)
- Java 1.5 quine (172 bytes): Uses
printf
instead ofprint
- Java 10 quine (166 bytes): Uses
var
instead ofString
type declaration - Java 21 quine (102 bytes): Uses an unnamed class and an instance main method (preview feature)
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.
Do not use in production 😉
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+.