Maybe I've been working too long on Java without really understanding some of its basics.
I do understand that ==
is for object reference equality and .equals()
is for object value equality.
Comparing Integers
:
Integer x = 1, y = 1;
System.out.println(x == y); // true
Why? Since object reference equality is used, it should be false since they are both different objects.
Comparing getClass()
return values:
String s1 = "a", s2 = "b";
System.out.println(s1.getClass() == s2.getClass()); // true
Why? Again as per above, object reference is used. Both using getClass
will return separate Class objects.
Did I miss something or is my mind is too tired of coding in Java?
Integer x = 1, y = 1;
System.out.println(x==y); // true, why?
This happens because for values in the byte
range (-128 to +127), java uses cached Integer objects, stored in Integer's inner class, IntegerCache. Every time an Integer object is created with value between -128 and +127, the same object will be returned (instead of creating the new object).
Conversely, for values outside the byte
range, the comparison is false
:
Integer x = 999, y = 999;
System.out.println(x==y); // false
String s1 = "a", s2 = "b";
System.out.println(s1.getClass() == s2.getClass()); // true. Why?
This is true because the class of both objects is String
, and there is only one copy of each class object per JVM (it's like a singleton). The class object returned from getClass()
of each String is the same class object (String.class
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With