See the following code:
public static void main(final String[] args) { Integer a = new Integer(100); Integer b = 100; System.out.println(a == b); }
What is the output of this code? I believe many people will easily guess: false, because the addresses of objects A and B are different, it is false to compare them with "=. Congratulations! You are correct.
Let's look at the following code:
public static void main(final String[] args) { Integer a = 100; Integer b = 100; System.out.println(a == b); }
You may answer, this is nothing different, so it is still false. Unfortunately, if you execute the above Code, the result is true.
The above code may surprise you. Well, let's look at the following code:
Is the result true? Unfortunately, if you execute the above Code, the result is false.
public static void main(final String[] args) { Integer a = 156; Integer b = 156; System.out.println(a == b); }
Are you surprised? Then let's look at the following code:
public static void main(final String[] args) { Integer a = Integer.valueOf(100); Integer b = 100; System.out.println(a == b); }
The final result, as you may have guessed, is true.
The first code: = compare the address. If the addresses of the two objects are different, it must be false!
Code 2: JDK uses the metadata mode when data is between-128-127. That is, the same address corresponding to multiple references.
In this way, the third code is easy to understand. When it is greater than this range, it is different objects. The effect of the fourth code is the same as that of the second code.