Detailed explanation of Integer in Java

Detailed explanation of Integer in Java

There are two types of int and integer in Java. Simply put, Integer is a reference type of int, but the type of reference is quite special. Let’s look at some demos below:

Integer a1 = 140;
Integer a2 = 140;
System.out.println(a1 == a2);

Integer b1 = 120;
Integer b2 = 120;
System.out.println(b1 == b2);

The result of the operation is:

false
true

Reason: Java will cache the number between -128 and 127. When Integer i = 127, 127 will be cached. Next time you write Integer j = 127, it will be taken directly from the cache. Will recreate the object again .

So when the address is 120, the address is the same, and the operation is true. When it is greater than 127, open a new address space, the address is inconsistent, it is false .

Of course we can also force a new variable to be reopened:

Integer c1 = new Integer(120);
Integer c2 = new Integer(120);
System.out.println(c1 == c2);


Integer d1 = new Integer(120);
Integer d2 = 120;
System.out.println(d1 == d2);

The result of the operation is:

false
false

This better validates our above ideas.

What happens if you compare the value of Integer and int?

Integer e1 = new Integer(120);
int e2 = 120;
System.out.println(e1 == e2);



Integer f1 = new Integer(140);
int f2 = 140;
System.out.println(f1 == f2);

Integer g1 = 120;
int g2 = 120;
System.out.println(g1 == g2);

The result of the operation is:

true
true
true

Reason: When Integer and int are compared, Integer will be automatically unboxed and become int for comparison .

From the above conclusions we draw:

  1. Integer can appear to be a value type when it is less than -128 to 127. When it exceeds this range, it will become a reference type.
  2. When Integer is compared with int, it will be automatically unboxed into int, and then compared

Based on the above, I started to have a question:

Integer i1 = 140;
Integer i2 = i1;
i1++;
System.out.println(i2);
System.out.println(i2 == i1);

The result of the operation is:

140
false

Why doesn't i2 change with the value of i1?

Reason: Integer automatically calls the internal function intValue() when performing operations.

The above code can be disassembled into:

Integer i1 = 140;
Integer i2 = i1;
i1=Integer.valueOf(i1.intValue()+1);
System.out.println(i2);
System.out.println(i2 == i1);

According to all the above situations, we can write an ultimate value type and reference type conversion:

Integer i1 = 120;
Integer i2 = i1;
Integer i3=i1+1;
Integer i4=i3-1;
System.out.println(i2);
System.out.println(i2 == i4);

operation result:

120
true

When i1=140, i2 == i4 will become false.

Reference: https://cloud.tencent.com/developer/article/1579123 Detailed explanation of Integer in Java-Cloud + Community-Tencent Cloud