I know this has been covered but I\'ve seen inconsistent arguments here on SO.
So if I have:
String a = \"apple2e\";
String b = \"apple2e\";
System.
If you change to the following:
System.out.println("a==b? " + (a == b));
You get
a==b? true
Whats happening here is that a and b both point to an internal cache of Strings that is maintained by the String class.
Here is the implementation of String.equals()
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
anObject must be a String in order to return true, if it is a reference to the same Object, then it returns true immediately.
Otherwise as you can see, is is doing a character by character comparison.