It should be noted that ==
compares whether two references point to the same object, while the equals()
method (for String
) checks whether two objects have the same value. What do I mean by this? What's really the difference?
When you use ==
to compare Strings, it's checking to see if the two Strings you're comparing point to the exact same location in memory. Note that I could have String a = "abc"
and String b = "abc"
, but a
and b
don't reference the same memory (they might represent two different memory locations, and those memory locations both happen to hold the same value, "abc"). This is exactly what is happening in your example, except the value of your Strings is "Eddie". equals()
, on the other hand, compares any two Strings to see if they have the same characters.
Crummy analogy:
Image the JVM is a waiter. Say you see your friend Bob with a bacon cheeseburger with crispy onions, and it looks appetizing. Further assume you want to ask the JVM if you can have what Bob is having. If you use ==
, the JVM will rip the burger Bob is eating right out from under his nose, and hand you that burger. That exact burger. If you use equals()
, the JVM will get you another bacon cheeseburger with crispy onions from the kitchen. You almost always want equals()
with String comparisons. Don't steal Bob's burger!!!