difference between .equals() and ==

49 Views Asked by At

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?

2

There are 2 best solutions below

2
Louis Wasserman On

But other strings can be compared with ==.

They can't, actually. Not reliably.

Why is that and what are the cases when we need == or equals?

The cases when you need == do not exist. The cases when you use .equals are 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 ==.)

0
Leafxe 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.