Wrapper class constant pool
Most Java primitive wrapper class constant pool techniques are implemented, i.e., Byte, Short, Integer, Long, Character, Boolean; four kinds of packaging front created by default values [-128,127] corresponding to the type of cache data , Character created cache data value in the range [0,127], Boolean direct return True Or False. If you exceed the corresponding range will still go to create a new object.
Two kinds of floating-point type of wrapper class Float, Double and did not realize the constant pool technology.
Integer source
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Example:
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
Integer e = new Integer(127);
Integer f = new Integer(127);
System.out.println(a == b); // true
System.out.println(c == d); // false
System.out.println(e == f); // false
Double m = 1.0;
Double n = 1.0;
System.out.println(m == n); // false
Integer a = 127
; The Java code directly encapsulated into at compile time Integer a = Integer.valueOf(127)
, whereby the object using the constant pool. Integer e = new Integer(127)
; Creates a new object in this case
Automatic boxing and unboxing
Integer a = new Integer(50);
Integer b = new Integer(40);
Integer c = new Integer(10);
System.out.println(a == b + c); // true
Since the operator does not apply to + Integer object, b and c first automatic unpacking operation, the numerical sum, i.e. a == 40. Then Integer object can not be directly compared with the value, so a value of 50 auto-unboxing converted to int, this statement into the final 50 == 50 numerical comparison.