Java-based automatic packing and unpacking

Source: Internet
Author: User

Java-based automatic packing and unpacking
Definition

In java, data types can be divided into two categories: Basic Data Type and reference data type. The basic data type is not an object, therefore, java provides a corresponding packaging class for using data types as objects. (For more information about the packaging class, see the common classes in the blog Java basics)

This blog mainly describes the automatic packing and splitting mechanisms of packaging classes.

The so-called packing is to wrap the basic data types with their corresponding reference types so that they can have the characteristics of objects. For example, we can wrap the int type into Integer type objects, or double the Double Packing Scale, and so on.

The so-called unpacking is in the opposite direction of packing. It simplifies the reference type objects such as Integer and Double into basic data types.

The automatic packing and unpacking introduced by java JDK are the compiler to decide whether to perform packing and unpacking Based on the code we write. You do not need to use methods such as valueOf () and intValue. (If you are not familiar with this, please refer to the common class details of blog Java basics)

Precautions for the automatic packing and unpacking Mechanism

This is the focus of this blog

Let's take a look at a small example:

public class WrapperText {    public static void main(String[] args) {        Integer a = 100;        Integer b = 100;        Integer c = 200;        Integer d = 200;        System.out.println(a == b);//1        System.out.println(a == 100);//2        System.out.println(c == d);//3        System.out.println(c == 200);//4    }}

If we do not know much about the automatic packing and unpacking operations in Java, we will definitely think this way: After automatic packing, abcd is different references of Integer objects, the "=" operator is used to compare object references, so both 1 and 3 should output false. For 2 and 4, because both a and c are automatically split, the comparison is a comparison of basic data types. The "=" operator compares their values, SO 2 and 4 are true because of this output. That is, the final result output:
False
True
False
True
But the correct result is:

We can see that the result of 1 is true, and the result of 3 is false. Why. In fact, the automatic packing process actually calls the valueOf () method, while the source code of the valueOf () method is:

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);    }
private static class IntegerCache {        static final int low = -128;        static final int high;        static final Integer cache[];        static {            // high value may be configured by property            int h = 127;            String integerCacheHighPropValue =                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");            if (integerCacheHighPropValue != null) {                int i = parseInt(integerCacheHighPropValue);                i = Math.max(i, 127);                // Maximum array size is Integer.MAX_VALUE                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);            }            high = h;            cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);        }        private IntegerCache() {}    }

By reading the source code, we can find that, to save memory in java, an array in the IntegerCache class caches Integer objects whose values range from-128 to 127. When we call Integer. when valueOf (int I) is used, if the I value is between-128 and 127, an object is directly returned from the cache; otherwise, a new Integer object is returned. Therefore, 1 is true, and 3 is false.

Finally, I will share an interesting question related to it:

Please provide a Statement on I to convert the following cycle into an infinite loop:

while(j <= i && i <= j && i != j){    }

I believe that if I read this blog carefully, this question will be easily solved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.