Acordding to my knowledge in java I know, that there is no operator overloading in the Java language.
So, why this code prints ‘true’ twice ?
String s1 = "abc";
String s2 = "abc";
System.out.println(s1==s2);
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1==i2);
==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 twotruein the given case. Another code snippet you might want to try out:As you must have already tried out; it prints out
falseand thentrue. The reason for this is that using thenewkeyword 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,s1now points to an interned string with the contents “abc” (or to a string in the string pool) whereass2now points to a completely new string object (again with the content “abc”). Hence thefalsein 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” theequalsmethod of theObjectclass to provide a logical comparison. Unless the class you write doesn’t provide a logical implementation of theequalsmethod, it doesn’t matter whether you callequalsor 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.