Home » Uncategorized » Java quine

Java quine

I’ve been reading again today some articles that mentioned quines, and decided that I should try to write a quine myself – right away, without looking up any techniques for quine writing.

In around half an hour or so it was done. Checking Wikipedia subsequently revealed that I’ve used same approach as everyone else – put source code contents into string array, and take care to output it properly twice.

Here’s the code of my quine in case anyone’s interested.

public class Quine {
	private static final String TAB = "\t";

	public static void main(String[] args) {
		for (int i = 0; i < LINES.length; i++) {
			System.out.println(LINES[i]);
			if (i == 19) {
				for (int k = 0; k < LINES.length - 1; k++) {
					System.out.println(TAB + TAB + "\"" + esl(LINES[k]) + "\",");
				}
				System.out.println(TAB + TAB + "\"\"");
			}
		}
	}

	private static String esl(String txt) {
		return txt.replaceAll("([\"\\\\])", "\\\\$1");
	}

	private static final String[] LINES = {
		"public class Quine {",
		"	private static final String TAB = \"\\t\";",
		"",
		"	public static void main(String[] args) {",
		"		for (int i = 0; i < LINES.length; i++) {",
		"			System.out.println(LINES[i]);",
		"			if (i == 19) {",
		"				for (int k = 0; k < LINES.length - 1; k++) {",
		"					System.out.println(TAB + TAB + \"\\\"\" + esl(LINES[k]) + \"\\\",\");",
		"				}",
		"				System.out.println(TAB + TAB + \"\\\"\\\"\");",
		"			}",
		"		}",
		"	}",
		"",
		"	private static String esl(String txt) {",
		"		return txt.replaceAll(\"([\\\"\\\\\\\\])\", \"\\\\\\\\$1\");",
		"	}",
		"",
		"	private static final String[] LINES = {",
		"	};",
		"}",
		""
	};
}
Advertisements

One thought on “Java quine

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s