0

String a=new String("Java"); String b=new String("Java"); a=b; System.out.println(a==b); the answer is true. Why?

Equal operator

23rd Jul 2019, 8:09 AM
Rohit Ahuja
Rohit Ahuja - avatar
5 Answers
+ 16
equals() method == tests for reference equality, (whether they are the same object) .equals( ) tests for value equality, (whether they are logically "equal") equals() is a method used to compare two objects for equality. The default implementation of the equals() method in the Object class returns true if and only if both references are pointing to the same instance. It therefore behaves the same as comparison by == . https://code.sololearn.com/clfOay4iwY7p/?ref=app
23rd Jul 2019, 11:28 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 1
Think of it like this. A = a dog B = a cat A(dog) = B(cat) Now (A is a cat) and (B is a cat) So when you compare these objects refs in the println method your doing this. A(cat) == B(cat); I would say it's TRUE that the cat is the same cat 😁 (==) compares refrences to objects so dont use this when comparing string values as strings are objects and objects have refreneces that are stored inside the variable, its perfectly ok to use this == operator when comparing primitive type data as they are not objects therefore there variables store the actual value. use .equals() method to compare strings.
23rd Jul 2019, 10:29 AM
D_Stark
D_Stark - avatar
+ 1
Thanks swim
23rd Jul 2019, 11:35 AM
Rohit Ahuja
Rohit Ahuja - avatar
- 1
Of course, why wouldn't it? You assign b to a, "Java" is equal "Java". What answer do you expect?
23rd Jul 2019, 8:29 AM
Agent_I
Agent_I - avatar