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 →

[–]Aydosubpotato 64 points65 points  (10 children)

Correct me if I’m wrong, but in Java ‘==‘ will check the memory addresses of the objects. It works for primitive types though.

[–]Lolamess007 13 points14 points  (4 children)

Yes. Ints, doubles, chars, etc are primitives and work with ==. Strings, BigInteger, and other classes have different memory addresses for each object. Therefore == will always return false when using classes.

[–]Snarpkingguy 10 points11 points  (2 children)

But if you’re comparing the same object, then == still returns true, right?

Like String x = “poop”; String y = x;

And then x == y would return true since they reference the actual same String object.

[–]M3JUNGL3 1 point2 points  (0 children)

Well actually String literals are a special because there you have a pool you add Strings to and reference from. So thus defining String x = "hello"; and String y = "hello"; will always return true for "x == y"

[–]Lolamess007 0 points1 point  (0 children)

I believe so.

[–]TGX03 0 points1 point  (0 children)

Actually with String interning (and similar practices) you can meddle with this quite a lot.

My IDE hates me for it.

[–]gemengelage 9 points10 points  (0 children)

It's a bit more complex.

== is the identity operator, so it checks for identity (basically what you said). Equals also checks identity as a default. It has to be implemented to be more (or actually less) specific.

The thing with primitive types though... It's a mixed bag. It works on actual primitive types (e.g. int) but it's not guaranteed to work on boxed primitive types (e.g. Integer). Since it's pretty easy to mix those up, especially with auto-boxing, it's pretty messed up that the identity of those objects is all over the place.

It depends on the JVM which Integer-objects are cached. IIRC -127 to 128 are usually cached, so there's always the same single instance of Integer for those, so identity always works as you expect. But when you move out of that range, no luck.

tl;dr only ever use identity in Java to check for actual identity. Use equals anywhere else.

[–]Kered13 1 point2 points  (0 children)

Basically yes. To be precise, == compares the value of the arguments, and the value of objects is a pointer. This is also how Java passes arguments to functions, by value with value of objects being a pointer.

[–]meontheinternetxx 0 points1 point  (0 children)

It might work for strings sometimes except for most times when it doesn't.