I don't know why after using .toString() and having our new String, we need only to use .equals instead of == when we want to compare. But other strings can be compared with ==. Why is that and what are the cases when we need == or equals?
difference between .equals() and ==
49 views Asked by Gargouri Nourallah At
2
There are 2 answers
0
On
In Java, == compares addresses and .equals() compares contents. Objects, like strings are reference types so even if they contain the same content, using == while comparing two strings may not always return the same outcome.
.equals() is a method that accepts the type Object and casts the value to the class and gets the instance's private members and compare the values.
They can't, actually. Not reliably.
The cases when you need
==do not exist. The cases when you use.equalsare 100% of the time.(There are some cases where people may say that with string interning or other use cases,
==suffices. This is not actually a good reason, and you should never use==.)