0

Can anyone tell me when to use equals() and "==" operator? I know that equals() method is used to compare the values of Strings. Also I know that "==" is used to check the references. What it exactly means?

Harika
  • 23
  • 2
  • 8

1 Answers1

2

Imagine two cars, for a moment. Let's say they're a green Toyota Corolla and an orange Ferrari. You want to compare them--are they similar? Yes; they're both cars. But, they have different properties. Their values (literally and figuratively) are not equal, and when I talk about the Corolla, I'm definitely not talking about the Ferrari. When I refer to one, I'm not referring to the other.

Now, imagine that I'm talking with you about a red Corolla. You also have a red Corolla. Neat! We have the same car! Except, they aren't exactly the same car, because they're two different cars. They just happen to have the same value. I can have mine painted and it won't change yours, or I could crash mine, and they won't have the same value. Comparing our two cars would be like using the equals() method. We could say they have the same value (until I crash mine, or change it some other way).

But, if we're each talking about a red Corolla, and it turns out I bought the Corolla from someone you sold yours to--hey, we're talking about the same Corolla! We're actually referring to the same exact thing. If I crash my Corolla, I've also crashed your (former) Corolla. If I paint it, it's still the same car. Checking whether we're talking about the exact same thing is reference equality.

Eric Hughes
  • 831
  • 6
  • 19