Boxing and Unboxing in Java

    Data types in Java include basic data types and reference data types. Basic data types have corresponding wrapper classes. The following are the number of bytes, default values, and corresponding wrapper types corresponding to basic data types.

byte 1 byte 0 Byte
char 2 bytes Unicode Char
short 2 bytes 0 Short
int 4 bytes 0 Integer
long 8 bytes 0 Long
float 4 bytes 0.0f Float
double 8 bytes 0.0d Douoble
boolean   false Boolean

What is boxing and unboxing?

Integer i=10;//valueOf() boxing
Integer i2=(Integer)10;//Display boxing
Integer i3=new Integer(20);// new heap allocation
int  i4=i;//intValue()
int i5=(int)i;//Display unboxing

Boxing is to convert a primitive data type to a wrapper type, and unboxing is to convert a wrapper type to a primitive data type. The valueOf method is called when boxing, and the basic data type +Of method is called when unboxing.

Take int and Integer as an example

public class TestDemo {
    public static void main(String[] args) {
         
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 129;
        Integer i4 = 129;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

The output is: true 

                   false

This shows that i1 and i2 are the same object, and i3 and i4 refer to different objects. Next, take a look at the source code of Integer's valueOf().

public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

    This indicates that a number between -128 and 127 will return a reference to an existing object, or a new object if it is not in this range. The above i3 and i4 are greater than 127, so the output result is false.



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326770141&siteId=291194637