Java is a nearly pure object-oriented programming language, but for programming convenience or to introduce basic data types that are not objects, but in order to be able to use these basic data types as Object operations, Java introduces the corresponding wrapper type (wrapper class) for each basic data type. The wrapper class for int is integer,
The automatic boxing/unpacking mechanism has been introduced from JDK 1.5 (5.0), allowing the two to be converted to each other.
Java provides the wrapper type for each primitive type:
Primitive Type: Boolean, char, Byte,short,int, long,float,double
Package Type: boolean,character,byte,short,integer,long,float,double
1 PackageCom.lovo; 2 3 Public classAutounboxingtest {4 5 Public Static voidMain (string[] args) {6Integer A =NewInteger (3); 7Integer B = 3;//automatically boxing 3 into an integer type8 intc = 3; 9System.out.println (A = = B);//false Two references do not reference the same objectTenSystem.out.println (A = = c);//true a automatically unboxing into int type and C comparison One } A}
Add: Recently also encountered a more classic face test, is also automatic packing and unpacking related
1 public class Test03 { 2 3 public static void Main (string[] args) { 4 Integer f1 = 1 XX, F2 = f3, F4 = 150 5 System.out.println (F1 == F2); The result is true 6 System.out.println (F3 == F4) ; The result is false 7 } 8 }
If unknown, it is easy to assume that both outputs are either true or false. The first thing to note is that the F1, F2, F3, and F4 Four variables are all integer objects, so the following = = Operation compares values instead of references.
What is the nature of boxing?
When we assign an int value to an integer object, we call the static method of the integer class valueof, and if we look at ValueOf's source code, we know what's going on.
1 Public Static Integer valueOf (int i) { 2 if (i >= integercache.low && i <=< c9> integercache.high) 3 return integercache.cache[i + (- Integercache.low)]; 4 return New Integer (i); 5 }
Simply put, if the value of the literal is between 128 and 127, then the new integer object is not added, but the integer object in the constant pool is referenced directly,
So the result of F1==F2 in the above interview question is true, and the result of F3==F4 is false.
Differences between int and Integer in Java and related examples