Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using <code>String</code> concatenation is translated into <code>StringBuilder</code> operations by the compiler.</p> <p>To see how the compiler is doing I'll take a sample class, compile it and decompile it with jad to see what's the generated bytecode.</p> <p>Original class:</p> <pre><code>public void method1() { System.out.println("The answer is: " + 42); } public void method2(int value) { System.out.println("The answer is: " + value); } public void method3(int value) { String a = "The answer is: " + value; System.out.println(a + " what is the question ?"); } </code></pre> <p>The decompiled class:</p> <pre><code>public void method1() { System.out.println("The answer is: 42"); } public void method2(int value) { System.out.println((new StringBuilder("The answer is: ")).append(value).toString()); } public void method3(int value) { String a = (new StringBuilder("The answer is: ")).append(value).toString(); System.out.println((new StringBuilder(String.valueOf(a))).append(" what is the question ?").toString()); } </code></pre> <ul> <li>On <code>method1</code> the compiler performed the operation at compile time.</li> <li>On <code>method2</code> the <code>String</code> concatenation is equivalent to manually use <code>StringBuilder</code>.</li> <li>On <code>method3</code> the <code>String</code> concatenation is definitely bad as the compiler is creating a second <code>StringBuilder</code> rather than reusing the previous one.</li> </ul> <p>So my simple rule is that concatenations are good unless you need to concatenate the result again: for instance in loops or when you need to store an intermediate result.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload