Because Object
is a type by reference, so the comparison is with the addresses of the objects and not with the values that are within them. Since they’re two different objects, they’re different addresses, so it’s always different.
See more in Memory allocation in C# - Value types and reference types. It’s C#, but it’s the same thing, only C# allows you to create your types by value only Java 10 will allow this.
That’s how it works, but it’s not the way you think, it’s not because the value is the same, it’s because it’s the same object.
class Ideone {
public static void main (String[] args) {
Object x = 3044;
Object y = x;
System.out.println(saoIguais(x, y));
}
public static boolean saoIguais(Object obj, Object obj2) {
return obj == obj2;
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
To compare objects use instanceof
– Netinho Santos
@Netinhosantos with instanceof did not work either, actually gave error
– Mateus