8 Basic types of Java (Byte, short, Integer, Long, Character, Boolean, float, double), except for Float and double, all six of them implement a constant pool. However, they use constant pools only when they are greater than or equal to 128 and are less than or equal to 127.
As can be seen from the following example:
[Java] View plain copy
public static void Main (string[] args) {
Integer a = 127;
Integer B = 127;
System.out.println ("Equal to 127:");
System.out.println (A = = B);
System.out.println ("*******");
A = 128;
b = 128;
System.out.println ("equal to 128:");
System.out.println (A = = B);
System.out.println ("*****************");
A = -128;
b = -128;
System.out.println ("Equal to -128:");
System.out.println (A = = B);
System.out.println ("*****************");
A = -129;
b = -129;
System.out.println ("Equal to -129:");
System.out.println (A = = B);
System.out.println ("*****************");
Test Boolean
System.out.println ("Test Boolean");
Boolean C = true;
Boolean d = true;
System.out.println (c = d);
D = new Boolean (true);
System.out.println (c = d);
}
The results are as follows:
Equals 127:
True
equals 128:
False
Equals-128:
True
Equals-129:
False
Test Boolean
True
False
When we assign a value to an integer, we actually call the integer.valueof (int) method to see the source code, which is implemented as follows:
[Java] View plain copy
public static Integer valueof (int i) {
if (i >= -128 && i <= integercache.high)
Return integercache.cache[i + 128];
Else
return new Integer (i);
}
And the Integercache implementation is as follows:
[Java] View plain copy
private Static Class Integercache {
static final int high;
Static final Integer cache[];
static {final int low =-128;
High value May is configured by property int h = 127; if (integercachehighpropvalue!= null) {//Use Long.decode this to avoid invoking methods that//req
Uire Integer ' s autoboxing cache to be initialized int i = Long.decode (integercachehighpropvalue). Intvalue ();
i = Math.max (i, 127);
Maximum array size is integer.max_value h = math.min (i, Integer.max_value--low);
High = h;
cache = new Integer[(high-low) + 1];
int j = Low;
for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +); Private Integercache () {}