1

While writing a Quine (i.e. a self-replicating program) in Java, I tried to indent output lines using tab characters:

...
char tab = '\t';
char qm = 34;
char comma = ',';
...
System.out.println(tab + tab + tab + qm + listing[i] + qm + comma);
...

This doesn't work because the plus operator in "tab + tab + ..." adds the tab character values rather than generating a string (61 = 9 + 9 + 9 + 34):

...
61    public static void main(String[] args) {",
...

Placing an empty string at the beginning does the job:

...
System.out.println("" + tab + tab + tab + qm + listing[i] + qm + comma);
...

However, I can't use plain quotation marks in the Quine setting as I need to escape them to output the program text itself.

I wonder if it is possible to enforce the interpretation of the plus operator as String concatenation WITHOUT explicitely using quotation marks or additional Java classes?

chwon
  • 71
  • 4

5 Answers5

3

Do you absolutely need to use +-signs? This'll do the trick too, and is designed for it in terms of performance:

String outputString = new StringBuilder()
    .append(tab).append(tab).append(tab).append(qm)
    .append(listing[i]).append(qm).append(comma)
    .toString();
System.out.println(outputString);
Robin Kanters
  • 5,018
  • 2
  • 20
  • 36
1

Use System.out.printf instead of System.out.println

 char tab = '\t';
 char qm = 34;
 char comma = ',';
 System.out.printf("%c%c%c", tab, tab,comma);
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

You can use StringBuilder to concatenate chars to String.

Take a look at this answer

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
0

You can replace empty quotation marks with simple String constructor:

...
System.out.println(new String() + tab + tab + tab + qm + listing[i] + qm + comma);
...
Yurii Shylov
  • 1,219
  • 1
  • 10
  • 19
0

Performance pointy of view StringBuilder appending is better than String concatenation, but StringBuilder doesn't provide thread safety. If you need thread safety use StringBuffer.

varra
  • 164
  • 8