I have a question about comparing a string with the empty string in Java. Is there a difference, if I compare a string with the empty string with == or eq
Given two strings:
String s1 = "abc";
String s2 = "abc";
-or -
String s1 = new String("abc");
String s2 = new String("abc");
The == operator performed on two Objects checks for object identity (it returns true if the two operators return to the same object instance.) The actual behavior of == applied to java.lang.Strings does not always appear to be consistent because of String interning.
In Java, Strings are interned (at least partly at the discretion of the JVM.) At any point in time, s1 and s2 may or may not have been interned to be the same object reference (supposing they have the same value.) Thus s1 == s2 may or may not return true, based solely on whether s1 and s2 have both been interned.
Making s1 and s2 equal to empty Strings has no effect on this - they still may or may not have been interned.
In short, == may or may not return true if s1 and s2 have the same contents. s1.equals(s2) is guaranteed to return true if s1 and s2 have the same contents.