public class Comparison {
public static void main(String[] args) {
String s = "prova";
String s2 = "prova";
System.out.println(s == s2);
System.out.println(s.equals(s2));
}
}
outputs:
true
true
on my machine. Why? Shouldn't be == compare object references equality?
Because String
instances are immutable, the Java language is able to make some optimizations whereby String
literals (or more generally, String
whose values are compile time constants) are interned and actually refer to the same (i.e. ==
) object.
JLS 3.10.5 String Literals
Each string literal is a reference to an instance of
class String
.String
objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions -are "interned" so as to share unique instances, using the methodString.intern
.
This is why you get the following:
System.out.println("yes" == "yes"); // true
System.out.println(99 + "bottles" == "99bottles"); // true
System.out.println("7" + "11" == "" + '7' + '1' + (char) (50-1)); // true
System.out.println("trueLove" == (true + "Love")); // true
System.out.println("MGD64" == "MGD" + Long.SIZE);
That said it needs to be said that you should NOT rely on ==
for String
comparison in general, and should use equals
for non-null
instanceof String
. In particular, do not be tempted to intern()
all your String
just so you can use ==
without knowing how string interning works.
new String(...)
If for some peculiar reason you need to create two String
objects (which are thus not ==
by definition), and yet be equals
, then you can, among other things, use this constructor:
public String(String original)
: Initializes a newly createdString
object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary sinceStrings
are immutable.
Thus, you can have:
System.out.println("x" == new String("x")); // false
The new
operator always create a new object, thus the above is guaranteed to print false
. That said, this is not generally something that you actually need to do. Whenever possible, you should just use string literals instead of explicitly creating a new String
for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With