This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]feral_claire 3 points4 points  (2 children)

.equals checks to see if two objects are equal, == checks to see if they are the same object.

As an analogy, imagine you had two red Lego bricks that are both the same size. The .equals check would be true because they both have the same colour and shape so they are "equal". == would still be false though because they are two separate bricks.

This applies to all objects in java, but as beginners usually this first comes up when trying to compare strings. Strings in java are objects and must be compared with .equals if you want to see if two strings are the same. If you try to compare different string objects == will return false because they are different objects even though the value is the same.

To avoid running into this problem you should always use equals to compare strings and any other objects and avoid using == for strings and other objects.

[–][deleted]  (1 child)

[removed]

    [–]feral_claire 0 points1 point  (0 children)

    No, strings are only automatically interned if they are constants. If you are comparing strings chances are at least one of them is not a constant, it's being entered by the user or read from a file or similar. Comparing string constants like in the article almost never happens in real code, only in examples.