What is the difference between == and .equals() in Java? Can you give an example where using one ove

String a = new String("monzo"); String b = new String("monzo"); System.out.println(a == b); // false System.out.println(a.equals(b)); // true
5 Replies
JavaBot
JavaBot2w ago
This post has been reserved for your question.
Hey @TurkijanDEV! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Aivruu
Aivruu2w ago
First statement compares both objects' reference in memory, reason why condition returns false, second one compares objects' contents, only if the class overrides the equals() method, as Object#equals makes a reference-check
JavaBot
JavaBot2w ago
Looks like you're having some trouble comparing strings, check out this stackoverflow question for help.
dan1st
dan1st2w ago
For objects, == compares references while equals() is a custom operation defined by the class that often compares the logical content For Strings, you should always use equals()
JavaBot
JavaBot2w ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?