Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"" is an actual string, albeit an empty one.</p> <p>null, however, means that the String variable points to nothing.</p> <p><code>a==b</code> returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.</p> <p><code>a.equals(b)</code> returns false because "" does not equal null, obviously.</p> <p>The difference is though that since "" is an actual string, you can still invoke methods or functions on it like</p> <p><code>a.length()</code></p> <p><code>a.substring(0, 1)</code></p> <p>and so on.</p> <p>If the String equals null, like b, Java would throw a <code>NullPointerException</code> if you tried invoking, say:</p> <p><code>b.length()</code></p> <hr> <p>If the difference you are wondering about is == versus equals, it's this: </p> <p>== compares references, like if I went</p> <pre><code>String a = new String(""); String b = new String(""); System.out.println(a==b); </code></pre> <p>That would output false because I allocated two different objects, and a and b point to different objects.</p> <p>However, <code>a.equals(b)</code> in this case would return true, because <code>equals</code> for Strings will return true <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)">if and only if the argument String is not null and represents the same sequence of characters.</a></p> <p>Be warned, though, that Java does have a special case for Strings.</p> <pre><code>String a = "abc"; String b = "abc"; System.out.println(a==b); </code></pre> <p>You would think that the output would be <code>false</code>, since it should allocate two different Strings. Actually, Java will <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()">intern</a> literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.</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