Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>As I understand it, it's because a and b are two different references to the same object (apple2e).</p> </blockquote> <p>Because of string interning, and <strong>only</strong> because of string interning <code>a</code> and <code>b</code> are different references to the same <code>String</code> object.</p> <hr> <p>Unfortunately, your code does not do what you think it does. Try this:</p> <pre><code>String a = "apple2e"; String b = "apple2e"; System.out.println("a==b? " + a == b); // "false" System.out.println("a==b? " + (a == b)); // "a==b? true" </code></pre> <p>Java automatically interns all string literals. <strong>That</strong> is why the second sysout prints what it does. The first sysout prints only <code>"false"</code> because string concatenation (<code>+</code>) has higher precedence than <code>==</code>, so it's equivalent to this:</p> <pre><code>System.out.println("a==b? apple2e" == "apple2e"); </code></pre> <p>I don't think that's what you meant to test!</p> <p>This, on the other hand, will give you two separate <code>String</code> instances:</p> <pre><code>String a = new String("apple2e"); String b = new String("apple2e"); System.out.println("a==b? " + (a == b)); // "a==b? false" </code></pre> <p>Which would schematically look like</p> <pre><code>a (reference_id 123) --------------- "apple2e" b (reference_id 456) --------------- "apple2e" </code></pre> <p>and can be reduced to the original situation using <code>String#intern()</code>:</p> <pre><code>String a = new String("apple2e").intern(); String b = new String("apple2e").intern(); System.out.println("a==b? " + (a == b)); // "a==b? true" </code></pre> <p>e.g.</p> <pre><code>a (reference_id 123) ------+ +--------- "apple2e" b (reference_id 456) ------+ </code></pre>
 

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