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?
Now when you compare two Integer objects using a == operator, Java doesn't compare them by value, but it does reference comparison. When means even if the two integers have the same value, == can return false because they are two different objects in the heap.
To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.
In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1.
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.
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