java boxing and unboxing
There are three types of data types in Java: Boolean, Character and Numeric. Among them, the numerical type is divided into integer and floating point type.
byte b=18;//1 byte char ch='a';//2 bytes 16 bits so the default value is '\u0000' a 0 four bits char ch1='male';//2 bytes float f=12.5f;//4 bytes default value 0.0f short sh=20;//2 bytes default value 0 long o=34L;//L is a long type flag, it can also be lowercase 8 bytes, the default value is 0 double d=12.45D;//8 bytes default value 0,0d boolean b1=true;//Not sure how many bytes the default value is false
Java's wrapper class is to represent a simple type of variable as a class. Java has six wrapper classes, namely Boolean, Character, Integer, Long, Float and Double.
Let's use Int and Integer as an example
public class haha { public static void main(String[] args){ Integer integer=10;//valueOf() boxing } }
View the class .class file information
When this code is executed, this method is called. This is the automatic boxing of java.
It is to turn the int type into an object of the Integer class through this method.
Integer integer2=(Integer)10;//Display boxing Integer integer3=new Integer(10);//Allocating memory on the heap integer3 stores an object memory address
The boxing process is implemented by calling the valueOf method of the wrapper, and the unboxing process is implemented by calling the xxxValue method of the wrapper. (xxx represents the corresponding basic data type).
public class haha { public static void main(String[] args){ Integer integer=10;//valueOf() boxing int i=integer;//Unboxing intValue() method int i1=(int)integer;//Display unboxing } }
View the class .class file information
When this code is executed, the intValue() method is called, which implements automatic unboxing.
Why do these two pieces of code have different execution results? Next, let's analyze the original code
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }It can be seen from this original code that when i is between the maximum value of 127 and the minimum value of -128, the program will store the reference of this value in the buffer area, and then when there is a value of i between 127 and -128, it will Will look in the buffer and return the address and value in the buffer. If it is outside this range, an object will be recreated.