Two different Integer objects are actually equal

Let's look at a simple code first:

public static void main(String[] args) {
    int a = 127;
    int b = 127;
    System.out.println(a == b);    //true

    Integer c = 127;
    Integer d = 127;
    System.out.println(c == d);    //true

    int e = 128;
    int f = 128;
    System.out.println(e == f);    //true

    Integer g = 128;
    Integer h = 128;
    System.out.println(g == h);    //false
  }

==Operators in Java are to determine whether they are equal:

  • For basic data types, it is judged whether the values ​​of the two are equal;
  • For reference types, it is judged whether the two are the same object, that is, the addresses pointed to by the two reference variables are the same.

The above results are easy to understand except for the c == dresults true. So c == dwhy is the trueresult?

This is because integers with values ​​in the range of [-128 ~ 127] are used frequently, so the integers in this range are specially treated, and the Integerobjects are placed in the constant object pool. When we declare Integer c = 127, we will create one IntegerObject, and place this object in the object pool. When declaring Integer d = 127, it is found that the object pool already has an object with a value 127, and the Integerobject is reused Integer; therefore, although we declare two Integerreference variables, they point to the same An Integerobject.

-------------------------------- END -------------------------------

For more exciting articles in time, please pay attention to the public account "Java Essentials".

Guess you like

Origin blog.51cto.com/xtayfjpk/2678170