Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why 2 objects of Integer class in Java cannot be equal

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?

like image 309
Himanshu Aggarwal Avatar asked Feb 09 '13 07:02

Himanshu Aggarwal


People also ask

Does == work for integer in Java?

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.

How do you compare two integers equal in Java?

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.

Can you compare integer and int?

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.

What is long int in Java?

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.


2 Answers

No. Use h.equals(z) instead of h == z to get the equality behavior you expect.

like image 175
Louis Wasserman Avatar answered Nov 14 '22 22:11

Louis Wasserman


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.

like image 21
Eng.Fouad Avatar answered Nov 14 '22 23:11

Eng.Fouad