Reputation: 233
I know that Object.equals()
compares the value of object in heap memory. and == compares the references.
But when I am running my code I am getting both as equal.
public class test3 {
public static void main(String args[]){
test2 ts = new test2();
test2 tss = new test2();
if(ts.a == tss.a){
System.out.println("they are equal");
}else
System.out.println("they are unequal..");
if(ts.a.equals(tss.a)){
System.out.println("equal");
}else
System.out.println("not equal..");
}
}
public class test2 { String a= "soumya"; }
Upvotes: 0
Views: 182
Reputation: 15755
Most of the case, ==
(defaults to the Object#equals(Object o)
) returns the same as equals()
Please check the equals(Object obj)
of Object
in the source code:
public boolean equals(Object obj) {
return (this == obj);
}
They return true if and only if their references are one and the same.
But sometimes, they may not be the same, if the equals() has been overrided.The most common case is that String
has overrided the equals()
to make it s1.equals(s2) return true as long as s1 and s2 have the same literal value.
Please check the below output:
public static void main(String[] args) {
String s1=new String("123");
String s2=new String("123");
Object o1=new Object();
Object o2=new Object();
System.out.println(s1.equals(s2));//true, since String override the equals() method
System.out.println(s1==s2);//false
System.out.println(o1.equals(o2));//false
System.out.println(o1==o2);//false
}
Upvotes: 0
Reputation: 11949
Since your updated your question with the definition of class test2
, the answer is now clear: String's constant are stored into an internal cache, using intern().
And this part:
All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification
That's why reference and equality (using equals
) returns both true
.
Upvotes: 1
Reputation: 34900
Looks like a rebus, but nothing suprising. In java
there are several reference types which have cache (pool) of their values in some intervals. Such types are e.g.: String
, Integer
(for values -128...127).
So, I suppose, your test2
class looks like:
class test2 {
String a = "x" ;
}
or
class test2 {
Integer a = 1;
}
or something similar.
About these caches you can read:
Integer
: Integers caching in Java
String
: What is the Java string pool and how is "s" different from new String("s")?
Upvotes: 3