Consider the following Java code:
Object a = new Integer(2);
Object b = new Integer(2);
System.out.println(a.equals(b));
Object x = new Object();
Object y = new Object();
System.out.println(x.equals(y));
The first print statement prints true and the second false.
If this is an intentional behavior, how this helps programming in Java?
If this is not an intentional behavior, is this a defect in Java?
I’m going to answer your question with reservations, but you should know that you are hurting yourself if the intent of the question was to get you to learn and your solution was to ask StackOverflow. That aside…
This behavior is intentional.
The default
equals()method onjava.lang.Objectcompares memory addresses, which means that all objects are different from each other (only two references to the same object will returntrue).java.lang.Integeroverrides this to compare the value of theIntegers, so two differentIntegers both representing the number two compare equal. If you used==instead, you would getfalsefor both cases.Standard practice in Java is to override the
equalsmethod to returntruefor objects which have the same logical value, even if they were created at different times (or even with different parameters). It’s not very useful to have objects representing numbers if you don’t have a way to ask, “do these two things represent the same value?”.Incidentally, and this is a tangent here, Java actually keeps a cache of
Integerobjects for small values. So sometimes you may get twoIntegerobjects where even the==operator will returntrue, despite you getting them from two different sources. You can even get code that behaves differently for larger integers than it does for smaller, without having it look at the integral values!