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
⌛
This post has been reserved for your question.
Hey @TurkijanDEV! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose 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.
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-checkFor objects,
==
compares references while equals()
is a custom operation defined by the class that often compares the logical content
For String
s, you should always use equals()
💤
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.