Operator overloading in Java
It's not entirely true that there is no operator-overloading in Java. There just isn't any custom operator overloading. For example there's some operator-overloading with +
which adds as both addition and as String
-concatenation. This is defined by the language and can't be modified by the developer.
Your example, however doesn't use operator overloading anywhere. ==
on reference types always does the same thing: return true
when the left side and the right side refer to the exact same object.
In this case s1
and s2
reference the same object and i1
and i2
reference the same object as well.
s1
ands2
reference the same internedString
, because string literals are guaranteed to be interned.i1
andi2
reference the same cachedInteger
because auto-boxing will re-use a fixed pool ofInteger
objects for common numeric values.
==
for reference types compares the references; ==
for primitive types compares values. In case of your first example, the two object references turn out to be the same due to a concept known as string pool. Hence two true
in the given case. Another code snippet you might want to try out:
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
As you must have already tried out; it prints out false
and then true
. The reason for this is that using the new
keyword results in the creation of a completely new string even though a string object with the exact same contents already exists in the string pool. In this case, s1
now points to an interned string with the contents "abc" (or to a string in the string pool) whereas s2
now points to a completely new string object (again with the content "abc"). Hence the false
in the first print statement.
In the second print statement, what we are doing is comparing the contents of the String object rather than its reference, which as it should prints true
.
This is one of the most common mistakes made by beginners of the Java language; they use ==
for logical comparison when it actually results in a reference comparison. Read the link posted in one of the answers here for more details about string pooling. On a related note, String class "overrides" the equals
method of the Object
class to provide a logical comparison. Unless the class you write doesn't provide a logical implementation of the equals
method, it doesn't matter whether you call equals
or use the ==
operator; the result would be the same i.e. reference comparison.
For a more in-depth view on equality, read Brian's article; an excellent read.