#.equals vs ==

20 messages · Page 1 of 1 (latest)

golden dome
#

Ok so far i read that, == doesnt work because it may compare differences "references", not the actual value. So we use .equals

Alright this is clear but... why does this hold only for Strings? why not integers?

dull saffronBOT
#

This post has been reserved for your question.

Hey @golden dome! 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 720 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

raw geyser
#

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^^

dull saffronBOT
#

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).

long cargo
#

some comment here too

raw geyser
long cargo
#

ez

bronze mango
#

In the statement

String s = "foo";`
  • s is 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.

final barn
#

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.

final barn
golden dome
#

oka it clears up

#

thank you everyone

dull saffronBOT
# golden dome 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.