#Use of ==
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
You’ve got the core idea right!
- For primitives,
==compares the actual values (e.g.,int a = 5; int b = 5; a == bistrue). - For reference types like objects,
==checks if two references point to the exact same memory location (same object), not if their internal data is equal.
That’s why for objects, you generally use .equals() to check logical equivalence (like two different String objects containing the same characters).
This distinction is key in Java’s memory model and object handling. Using == for objects often leads to subtle bugs if you meant to compare their contents rather than identities.
Useful links:
yeah exactly
reference type variables just store the "value of the reference", not the object itself
thus == still compares the value even for reference types
just that the value isnt the object itself
.equals is essentially just a normal java method. no magic involved
normally ud compare properties in it
example:
class Person {
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Person)) { return false; }
Person other = (Person) o;
return name.equals(other.name) && age == other.age;
}
}
but its totally up to u what u want to compare
maybe persons are identified only by their name, then age plays no role
return name.equals(other.name);
totally up to u what logic makes the most sense in order to compare objects with each other
java wont do any guessing for u in terms of "oh, lemme compare property by property"
u define the logic in ur equals method urself
== in contrast doesnt do any of that. its built-in "magic" that simply compares the object identity
people often say "its the objects memory address". that isnt really true but it might help understand what identity means
another example are twins
Person first = new Person("John");
Person second = new Person("John");
first == second nope, false
two different object identities
but sure, they look alike so first.equals(second) would probably be true (provided thats how u implemented the equals method)
By default equals works like == for references right
Unless you implement your own override for the class
yeah, as u know, u inherit equals from the all-parent class Object
and in there, the code looks like this:
class Object {
...
public boolean equals(Object o) {
return this == o;
}
}
so thats the default behavior u get
so again, "no magic". just normal java inheritance with normal java code
👍