Reputation: 31
I come up with the scenario & can't understand the logic behind it ? I understood the first one only, rest two unable to understand ? Please explain how internally it work?
public class Test {
public static void main(String[] args) {
String s = "Karan";
Object o = "Karan";
System.out.println(s.equals(o)); // True
System.out.println(o.equals(s)); // True
System.out.println(s == o); // True
}
}
Upvotes: 0
Views: 576
Reputation: 20195
There is a difference between the static type of an object and the dynamic type of a variable.
The static type is the type known at compile time. For Object o = "Karan";
, the static type is the one at the left of o
, i.e. Object
. Now, one could ask why that is the case since at compile-time, it can be inferred that o
is a String
. Well if we consider something like
Object o;
if (someCondition) {
o = "Karam";
} else {
o = new StringBuffer();
}
then we cannot know whether o
is a String
or a StringBuffer
, thus its static type is Object
(since o
is defined as Object
).
The dynamic type is the type at runtime. In the example above, after the if
-statement has been executed, o
is either a String
or a StringBuffer
, but not both and nothing else. In your example, the dynamic type of Object o = "Karan";
is String
.
When variables are compared through equals(...)
, they must have the same dynamic type in order for the comparison to return true
(notice that this property is necessary, but not sufficient). Since o
in your example is, in fact, a String
AND the content is equal to s
, s.equals(o) == o.equals(s) == true
.
As to why s == o
returns true
: the question is answered in this post.
Upvotes: 1
Reputation: 2178
String s = "Karan"
this is a String object referred by a String reference.
Object o = "Karan"
this is a String object referred by an Object reference. Super class can refer to object of sub-class.
For both s.equals(o)
and o.equals(s)
the underlying objects equal()
is called, since the objects are of type String (even if reference 'o' is of type Object) String's equals is called which compares the value of the string which are equal. That is what you got true
as result.
s == o
compares the object reference of s and o. They were created using double quote which uses the String pool, creates the object once and refers it again. So both s and o are exactly same String object. This makes ==
return true.
Upvotes: 1