Why 2 objects of class Integer 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 ));
  }
}

Conclusion: -

z == h -> false

why is the conclusion false when the values ​​of both objects are equal?

Is there any other way in which we can make objects equal?

+5
source share
7 answers

You are trying to compare two different objects, not their values. z and h point to two different Integer objects that have the same value.

z == h 

Checks if two objects are equal. Therefore, he will return the lie.

If you want to compare the values ​​stored by the Integer object, use the method equals.


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 objects, i.e. object1 and object2 with a value of 44. Now

z = h

, , z h, . .. object1 == object2 .

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.

z == h  

true.

http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

+1

. h.equals(z) h == z, .

+6

h == z , (i.e Integer a = 43), -128 127 ( ), i.e:

 Integer a = 44;
 Integer b = 44;

 System.out.println("a == b -> " + (a == b));

:

a == b -> true

[-128, 127], false

 Integer a = 1000;
 Integer b = 1000;

 System.out.println("a == b -> " + (a == b));

:

a == b -> false

Integer.equals().

+3

Integer (int) equals.

z == h, int, Integer (z h), .

-

, Integer, int, .

System.out.println("z == h -> " + h.equals( z));

true.

+2

- , . z h , == . == ; , .

, z.equals(h); h.equals(z); true.

+1
source

Read this: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html

An integer is an object by which you compare the addresses / links / pointers of objects, not values.

Integer a = Integer(1);
Integer b = Integer(1);

a == b; // false
a.compareTo(b); // true
+1
source

check that you can use z ++ in an Integer object.

0
source

All Articles