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
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
+ 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.
+ 1
Thanks swim
- 1
Of course, why wouldn't it? You assign b to a, "Java" is equal "Java". What answer do you expect?