In Java, it is important to note, ==
always means "return true if these two things refer to the same instance of an object in memory"
When you declare a string using the constructor:
String s1 = new String("Foo");
String s2 = new String("Foo");
A new string instance is always created. This means that even though they have the same value, s1
and s2
are never going to be the same object and as such ==
returns false.
There is a special case for constant strings however. When you declare a string thus:
String s3 = "Foo";
String s4 = "Foo";
then a single constant string is created in the string pool, and both variables s3 and s4 point to it as a memory optimization. This should be treated as an implementation detail however. Comparison should still always be done using the Equals method.