Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>==</code> for reference types compares the references; <code>==</code> for primitive types compares values. In case of your first example, the two object references turn out to be the same due to a concept known as string pool. Hence two <code>true</code> in the given case. Another code snippet you might want to try out:</p> <pre><code>String s1 = "abc"; String s2 = new String("abc"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); </code></pre> <p>As you must have already tried out; it prints out <code>false</code> and then <code>true</code>. The reason for this is that using the <code>new</code> keyword results in the creation of a completely new string even though a string object with the exact same contents already exists in the string pool. In this case, <code>s1</code> now points to an interned string with the contents "abc" (or to a string in the string pool) whereas <code>s2</code> now points to a completely new string object (again with the content "abc"). Hence the <code>false</code> in the first print statement.</p> <p>In the second print statement, what we are doing is comparing the contents of the String object rather than its reference, which as it should prints <code>true</code>.</p> <p>This is one of the most common mistakes made by beginners of the Java language; they use <code>==</code> for logical comparison when it actually results in a reference comparison. Read the link posted in one of the answers here for more details about string pooling. On a related note, String class "overrides" the <code>equals</code> method of the <code>Object</code> class to provide a logical comparison. Unless the class you write doesn't provide a logical implementation of the <code>equals</code> method, it doesn't matter whether you call <code>equals</code> or use the <code>==</code> operator; the result would be the same i.e. reference comparison.</p> <p>For a more in-depth view on equality, <a href="http://www.ibm.com/developerworks/java/library/j-jtp05273.html" rel="noreferrer">read Brian's article; an excellent read</a>.</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