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 == d
results true
. So c == d
why is the true
result?
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 Integer
objects are placed in the constant object pool. When we declare Integer c = 127
, we will create one Integer
Object, 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 Integer
object is reused Integer
; therefore, although we declare two Integer
reference variables, they point to the same An Integer
object.
-------------------------------- END -------------------------------
For more exciting articles in time, please pay attention to the public account "Java Essentials".