Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's go through it line by line.</p> <p><strong>Line 11</strong></p> <p>An easy start, no strings created here.</p> <p><strong>Line 12</strong></p> <p>We're assigning the String <code>"Fred"</code> to <code>s</code>. Although it looks like a String is created here, this string will live in the constant pool. The <a href="http://docs.oracle.com/javase/specs/jvms/se5.0/html/VMSpecTOC.doc.html" rel="nofollow">JVMS</a> section <a href="http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#19124" rel="nofollow">2.17.6 Creation of New Class Instances</a> guarantees that the objects for string literals will <em>at latest</em> be created when the surrounding class is loaded, which by definition is <em>before the method is invoked</em>. So no new string objects are created on this line.</p> <p><strong>Line 13</strong></p> <p>The literal string <code>"47"</code> is referenced, which again will have been created statically (as above). However there's also the invocation of the <code>+</code> operator, which <em>will</em> create a new String in order to hold the result of the concatenation. So that's the first string created.</p> <p><strong>Line 14</strong></p> <p>The <code>substring</code> method does indeed create a new String. It shares the underlying character array with its parent - and so takes up hardly any extra memory - but since Strings are immutable, each different string representation requires a different <code>String</code> object. (This is probably a gotcha - my first instinctive response was "ah, string created by substring are special" but of course it still has to create a new object).</p> <p><strong>Line 15</strong></p> <p>As above - the uppercase representation is different, so a new String must be created to hold the result.</p> <p><strong>Line 16</strong></p> <p><code>Strings</code> override the <code>toString()</code> method to simply <code>return this</code> - hence no additional String is created.</p> <p><strong>The scores on the doors</strong></p> <p>By my count that's three String objects created during this method (with two of those objects sharing the same underlying character array, and with two pre-existing objects referenced for the string literals).</p>
 

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