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?
h == z
would work only if you assign the value via auto-boxing (i.eInteger a = 43
) and the value is in between -128 and 127 (cached values), i.e:OUTPUT:
If the value is out of the range
[-128, 127]
, then it returnsfalse
OUTPUT:
However, the right way to compare two objects is to use
Integer.equals()
method.