java basic data type automatic boxing and unboxing

java basic data type automatic boxing and unboxing

 

 

1. Definition:

public class test {
    public static void main(String[] args) {
        Integer a = 3;//boxing
        int b = a; //unboxing
    }
}

 Looking at the source code of Integer , we can see:

The wrapper class of the basic type, boxing, actually calls the valueof method of the wrapper class;

Unboxing, the wrapper class is called: xxxValue method;

For example, for Integer , boxing: Integer.valueOf(int i) ; unboxing: Integer.intValue() .

 

2. Application examples and pits:

 

1. Use the example code:

public class TestAutoBoxing {

	/**
	 * Test class demonstrates autoboxing and unboxing of basic types, and comparison rules
	 * @author cdzhujun
	 */
	public static void main(String[] args) {
		/**
		 * The number within -128~127, if it already exists, it will be cached, and it supports multiplexing of similar types: Short/Character/Long/Byte
		 * Value range: Integer, Byte, Short, Long: [-128, 127] Character: [0, 127]
		 * Float, Double: no cache, a new Boolean every time: there are only two fixed values, as long as the values ​​are the same, they are equal
		 */
		System.out.println("############################");
		// numbers outside -128~127
		Integer ii1 = 200;
		Integer ii2 = 200;
		System.out.println("ii1==ii2: " + (ii1 == ii2));// false
		// A number within -128~127
		Integer ii3 = 100;
		Integer ii4 = 100;
		System.out.println("i3==i4: " + (ii3 == ii4));// true
		System.out.println("—————————");

		Double d1 = 100.0;
		Double d2 = 100.0;
		Double d3 = 200.0;
		Double d4 = 200.0;
		System.out.println(d1 == d2); // false
		System.out.println(d3 == d4); // false
		System.out.println("—————————");

		Boolean b1 = false;
		Boolean b2 = false;
		Boolean b3 = true;
		Boolean b4 = true;
		System.out.println(b1 == b2);// true
		System.out.println (b3 == b4); // true
		System.out.println("—————————");
		
		/**
		 *== Compare:
		 * When both are basic types, the value is compared; when both are wrapper classes, they are compared according to the caching rules; when the base class is compared with the wrapper class, the wrapper class will be automatically unboxed
		 * Not to mention new, every time new, a new object is created in the heap memory
		 */
		System.out.println("############################");
		// Example 1: When both are primitive types, the value is compared
        int i1 = 1;
        int i2 = 1;
        System.out.println("i1==i2 : " + (i1 == i2)); // true
        // Example 2: When both are wrapper classes, compare by cache rules
        Integer obj1 = 1;
        Integer obj2 = 1;
        System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true
        // Example 3: Base class and wrapper class comparison, wrapper class is automatically unboxed
        Integer num1 = 1;
        int num2 = 1;
        System.out.println("num1 == num2 : " + (num1 == num2)); // true
        // Example 4: Let's not talk about new, every time new, a new object is created in the heap memory
        Integer one = new Integer(1);
        Integer anotherOne = new Integer(1);
        System.out.println("one == anotherOne : " + (one == anotherOne)); // false
        // Example 5: One is a wrapper class, the other is new, which is equivalent to two new
        System.out.println(num1 == one); // false
        
        /**
         *== Special scenario:
         * 1. If one of the == comparisons is an expression (operated with +, -, *, /, >, < operators, the wrapper class will be unpacked to participate in the operation first.
         * 2. When the two operands of the == operator are references of the wrapper type, the comparison points to the same object;
         * And if one of the operands is an expression (that is, contains an arithmetic operation), the comparison is a numeric value (that is, an automatic unboxing process is triggered).
         */
        System.out.println("############################");
        Integer num111 = 100;  
        int num222 = 100;  
        Long num333 = 200L;
        long numm3 = 100L;
        Integer numm1 = 200;
        //num111 is first unboxed to participate in the operation, num111+num222 is of int type after operation, and then becomes Integer after boxing
        //Because the operation on the right side contains expressions, the final results of num333 and (num111 + num222) calculations will be automatically unboxed and become long and int types
        //The basic type of long/int can be compared by ==, and the comparison is only the value, so the final result returns true
        System.out.println(num333 == (num111 + num222)); //true
        System.out.println(num222 == numm3); //true
        //System.out.println(num333 == numm1);//This is not acceptable, it should be a type mismatch
        
        /**
         * equals() of the wrapper class: the type is the same, and the values ​​of the variables are equal, will finally return true
         * Note: The equals() method of the wrapper class overrides the same method of the Object class;
         * The String and Date classes also rewrite the Object class equals(), but the implementation is different (not discussed here)
         */
        System.out.println("############################");
        Integer num11 = 100;  
        int num22 = 100;
        Long num4 = 200L;
        System.out.println(num11.equals(num22));  //true
        System.out.println(num4.equals(num11 + num22)); //false, because equals is not unboxed, because Long and Integer types do not match
        System.out.println(num4 == (num11 + num22)); // true, there is an operator, the + calculation result will be unboxed
	}

}

 2. Pit : Integer type can be null , int type cannot be null .

Integer i1=null;
int i2=i1;

 These two lines of code are completely legal and can be compiled completely, but at runtime, a null pointer exception will be thrown because the int type cannot be null .

So: during automatic unboxing, make sure that the value of the wrapper class cannot be null .

 

Third, the advantages and disadvantages of automatic packing and unpacking:

1. Advantages:

Save trouble and simplify your code . Automatically convert the base type and the wrapper class to each other.

Save memory . As in the example above, objects of reusable classes ( [-128,127] ) can be used when the range of numbers is small.

 

2. Disadvantages: In the case of automatic boxing operation in a loop, such as the following example, redundant objects will be created, which will affect the performance of the program.

Integer sum = 0;
 for(int i=1000; i<5000; i++){
   sum+=i;
}

 Inside is actually:

sum = sum.intValue() + i;
Integer sum = new Integer(result);

 Many new objects are created, but they are of no practical use, so external memory overhead will be increased and performance will be affected.

 

Fourth, the similarities and differences between basic types and packaging types

 

1. In Java , everything is an object, but the eight basic types (char, byte, int, double, float, short, long, boolean) are not objects .

       2. Depending on the way of declaration , the basic type does not need to be created by the new keyword, while the encapsulated type needs the new keyword.

       3. The storage method and location are different . The basic type is to directly store the value of the variable and save it in the stack for efficient access. The encapsulated type needs to point to the instance by reference, and the specific instance is stored in the heap.

       4. Different initial values , the initial value of the encapsulated type is null , the initial value of the basic type depends on the specific type, such as the initial value of the int type is 0 ( integer: including int, short, byte, long, the initial value is 0) , the boolean type is false , the float type: float, double, the initial value is 0.0 , the character: char, the initial value is a space, that is, '' " , if it is output, it will not see the effect on the Console .

       5. The usage is different , for example, only the packaging type can be used in cooperation with the collection class.

 

 

Guess you like

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