my code is:
public class Box
{
public static void main(String[] args)
{
Integer z = new Integer(43);
z++;
Integer h = new Integer(44);
System.out.println("z == h -> " + (h == z ));
}
}
Output:-
z == h -> false
why the output is false when the values of both the objects is equal?
Is there any other way in which we can make the objects equal?
You are trying to compare two different object and not their values. z and h points to two different Integer object which hold same value.
Will check if two objects are equal. So it will return false.
If you want to compare values stored by Integer object use
equals
method.So at the end we have two different Integer object ie object1 and object2 with value as 44. Now
This will check if objects pointed by z and h is same. ie
object1 == object2
which is false. If you doNow
will return true.
This might help http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
No. Use
h.equals(z)
instead ofh == z
to get the equality behavior you expect.Integer is an object, not a primitive. If z & h were primitives, == would work just fine. When dealing with objects, the == operator doesn't check for equality; it checks if the two references point to the same object.
As such, use
z.equals(h);
orh.equals(z);
These should return true.Integer
is Object not primitive (int) And Object equality compare withequals
method.When you do
z == h
it will not unbox intoint
value unless it checks bothInteger
reference(z & h) are referring same reference or not.As it is derived in documentation -
It will print
true
.check to make sure you can use z++ on the Integer object.
Read this: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html
Integer is Object you compare address/references/pointers of objects not values.