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.
z == h
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.
Integer z = new Integer(43); // Object1 is created with value as 43.
z++; // Now object1 holds 44.
Integer h = new Integer(44); // Object2 is created with value as 44.
So at the end we have two different Integer object ie object1 and object2 with value as 44.
Now
z = h
This will check if objects pointed by z and h is same. ie object1 == object2
which is false.
If you do
Integer z = new Integer(43); // Object1 is created with value as 43.
z++; // Now object1 holds 44. Z pointing to Object1
Integer h = z; // Now h is pointing to same object as z.
Now
z == h
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 of h == z
to get the equality behavior you expect.
h == z
would work only if you assign the value via auto-boxing (i.e Integer a = 43
) and the value is in between -128 and 127 (cached values), i.e:
Integer a = 44;
Integer b = 44;
System.out.println("a == b -> " + (a == b));
OUTPUT:
a == b -> true
If the value is out of the range [-128, 127]
, then it returns false
Integer a = 1000;
Integer b = 1000;
System.out.println("a == b -> " + (a == b));
OUTPUT:
a == b -> false
However, the right way to compare two objects is to use Integer.equals()
method.
Integer
is Object not primitive (int) And Object equality compare with equals
method.
When you do z == h
it will not unbox into int
value unless it checks both Integer
reference(z & h) are referring same reference or not.
As it is derived in documentation -
The result is true if and only if the argument is not null and is an
Integer object that contains the same int value as this object.
System.out.println("z == h -> " + h.equals( z));
It will print true
.
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);
or h.equals(z);
These should return true.
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.
Integer a = Integer(1);
Integer b = Integer(1);
a == b; // false
a.compareTo(b); // true
check to make sure you can use z++ on the Integer object.