#.equals vs ==
20 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @golden dome! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 720 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Bcs String isn't a primitive datatype, whereas int is
char, float, double, short, byte, boolean, long are also primitive
I'd advice you to have a look a the basics of object oriented programming to understand what references are in this context. Then you'll also see, that (and why) something like:
int i = 33;
System.out.println(i.equals(78));
Is actually impossible^^
A single equal sign is used for assignments. int value = 5;. For comparing primitves you use two equal signs if (value == 5) and for Objects .equals() if (string.equals(otherString).
some comment here too
Pfffff😂
ez
In the statement
String s = "foo";`
sis a variable of type 'String reference', not a String object."foo"is a String literal whose type is a 'String reference'.
In Java, the values of parameters, variables, fields and values returned from methods always either primitive values or references.
Since == compares the values, it actually behaves exactly the same for all types.
When you say a.equals(b), the . operator follows the reference in a and invokes the equals method on that object.
When the value in a is null (not referring to an object) then you get an error trying to follow that reference.
It doesn't hold solely for strings but it's a bit worse with Strings compared to other objects
primitives don't have an equalss method, conparing those with == is fine
For other objects: == compares references and equals allows the class to define a different mechanism for comparison (typically a logical comparison taking account the data) so if you want to use that, you should use equals
With Strings, there is no good reason to use ==, especially because of interning.
to avoid the NPE of a.equals(b), Objects.equals(a,b) is an option
oh lol language differences
in js, string is also primitive
oka it clears up
thank you everyone
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.