Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In most situations, you should use String literals to avoid creating unnecessary objects. This is actually <strong>Item 5: Avoid creating unnecessary objects</strong> of Effective Java:</p> <blockquote> <h3>Item 5: Avoid creating unnecessary objects</h3> <p>It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both faster and more stylish. An object can always be reused if it is immutable (Item 15). As an extreme example of what not to do, consider this statement:</p> <pre><code>String s = new String("stringette"); // DON'T DO THIS! </code></pre> <p>The statement creates a new <code>String</code> instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor (<code>"stringette"</code>) is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:</p> <pre><code>String s = "stringette"; </code></pre> <p>This version uses a single <code>String</code> instance, rather than creating a new one each time it is executed. Furthermore, it is guaranteed that the object will be reused by any other code running in the same virtual machine that happens to con- tain the same string literal [JLS, 3.10.5]</p> </blockquote> <p>There is however one situation where you want to use the <code>new String(String)</code> constructor: when you want to force a substring to copy to a new underlying character array like in:</p> <pre><code>String tiny = new String(huge.substring(0, 10)); </code></pre> <p>This will allow the big underlying <code>char[]</code> from the original <code>huge</code> String to be recycled by the GC.</p>
    singulars
    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. 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