why 2 objects of Integer class in Java cannot be e

2019-06-20 20:44发布

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?

7条回答
手持菜刀,她持情操
2楼-- · 2019-06-20 21:10

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.

查看更多
登录 后发表回答