Java advanced automatic unboxing and automatic boxing __java

Source: Internet
Author: User
Tags static class wrapper
Introduction to Java Basic Types

In Java, there are 8 basic data types, the details of which are as follows:

byte - 32768-32768 /tr>
type size range default value
8 -128-127 0
short 0
int -2147483648-2147483648 0
long -9233372036854477808-9233372036854477808 0
float -3.40292347e+38-3.40292347e+38 0.0f
double -1.79769313486231570e+308-1.79769313486231570e+308 0.0d
char \u0000-u\ffff \u0000
boolean true/false false


The Java language is an object-oriented language, but the basic data types in Java are not object-oriented, which is a lot of inconvenience in practical use, in order to solve this problem, the designer encapsulates each basic data type into a single class. The eight classes corresponding to the basic data type are collectively referred to as wrapper classes (wrapper class). 1. What is automatic unpacking and automatic boxing

Automatic Boxing: The base type is packaged with their corresponding packing class so that they have the object's characteristics and can invoke the method defined by the corresponding wrapper class, such as ToString ().

As an example:

   Integer i0 = new Integer (0);
   Integer i1 = 2;
   Integer i1_ = integer.valueof (2);

The first line of the top three lines of code is the most basic way to create an integer object. The second line of code is the automatic boxing we're going to talk about here. The third line of code is the nature of the second line of code, which means that when you use automatic boxing to get a reference data type, the JVM actually calls the valueof () method, and later we'll look at the Java source.

Automatic unboxing: In contrast to the direction of automatic boxing, the object of a wrapper class such as Integer and double is simplified to the base type of data.

As an example:

        1.system.out.println (i1+2);

This code uses an automatic unboxing. I1 is an integer object that we get by automatically boxing, and this object cannot be arithmetic directly, but we give it +2, so we have to convert the integer object to the basic data type (int), which is the process of automatic unpacking.

P.S. The so-called automatic, that is, this process does not require the programmer to complete, but the JVM is automatically completed, the JVM will be based on the syntax to determine whether the boxing and unboxing action.
In addition, automatic unboxing and automatic boxing jdk1.5 introduced new features, so if your JDK version is less than 1.5, it is not allowed to write. 2. Why is there automatic unpacking and automatic boxing

Why does Java provide such a feature? My understanding is this:
1. Because of laziness. If there is no automatic unpacking and automatic boxing, then our code is this:

    Integer i = new Integer (2);//If you need an integer object I, the value is 2
    int b=i.intvalue (), and//You need an int value, the size is equal to I

However, with automatic unpacking and boxing, we can write this:

        Integer i = 2;
        int b = i;

Does it save a lot of money, and it looks like the code is more concise.

2. The automatic boxing process can actually play the role of saving memory. Let's take a look at an example:

        Integer a = 1;
        Integer B = 1;
        Integer C = 144;
        Integer d = 144;
        Integer a1 = new integer (1);
        Integer B1 = new integer (1);
        System.out.println (A = = B);         True
        System.out.println (a.equals (b));    True
        System.out.println (a1 = = B1);       False
        System.out.println (A1.equals (B1));  True
        System.out.println (c = = d);         False
        System.out.println (C.equals (d));    True

Is it strange why the 7th Act is true and the 12th Act false? This is because, in case of automatic boxing, when the value from –128 to 127 is boxed as an integer object, there is a reuse in memory and there is always only one object. If you exceed the value from –128 to 127, the boxed integer object is not reused, which is equivalent to creating a new integer object each time it is boxed.

So, why do you have to design it? In general, the use of small numbers is very high, the small number of save, so that it always has only one object can save memory, improve efficiency.

This actually uses a kind of design pattern which is called the element pattern, the interest can study this design pattern. 3. How to use the automatic unpacking and automatic boxing

How to use the above example you should also be clear, automatic unpacking and boxing is actually the JVM to help us to call some functions, so that we can save a lot of things, the code will look more concise, but here is another point to emphasize, first look at the code:

Integer a = null;
int b = A;

This writing is entirely in accordance with the Java Syntax specification, compilation can also be passed normally, but it is obvious that the runtime throws a null pointer exception. So here's a reminder that when you use an automatic unboxing, make sure that the wrapper class reference is not empty. 4. SOURCE Analysis

The above mentioned several methods of packing class, we an integer class as an example, to see what the Java source is like. The first is the valueof () method:

public static Integer valueof (int i) {
        if (i >= integercache.low && i <= integercache.high)
        //Not set Words, ingegercache.high default is 127 return
            Integercache.cache[i + (-integercache.low)];
        return new Integer (i);
}

As mentioned above, in the case of automatic boxing, the value from –128 to 127, which is boxed as an integer object, is reused in memory. Now understand why, when you call the ValueOf () method, you will judge whether the number you give is in Integercache.low and I <= Integercache.high, if it is, then he generates a unique object in memory, and when you want to generate it for the second time, he will give you the address of the first generated object and will not regenerate it. Instead of the number in this range, the objects you generate each time are different.

What is the size of the automatic packing pool defined, there is an inner class in the Integer.java

private static class Integercache {static final int low =-128;
        static final int high;

        Static final Integer cache[];
            static {//high value May is configured by property int h = 127;
            String Integercachehighpropvalue = Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if (integercachehighpropvalue!= null) {try {int i = parseint (Integercach
                    Ehighpropvalue);
                    i = Math.max (i, 127);
                Maximum array size is integer.max_value h = math.min (i, Integer.max_value-(-low)-1);
                The catch (NumberFormatException NFE) {//If The property cannot is parsed into an int, ignore it.

            } high = h;
            cache = new Integer[(high-low) + 1];
            int j = Low;
               for (int k = 0; k < cache.length; k++) CACHE[K] = new Integer (j + +);
        range [ -128, 127] must be interned (JLS7 5.1.7) assert Integercache.high >= 127; Private Integercache () {}}

The Integercache class (this is the jdk1.8 source) defines the size of an integer automatic boxing pool. From the source we can see that the lower bound is written dead, is-128, but the upper bound is by the parameter Integercachehighpropvalue decoding, which indicates that In fact, we can customize the size of the automatic packing pool by changing the size of the Integercachehighpropvalue value, of course, no one will change it.

The range of an integer automatic packing pool is -128~127
Byte,short,long Range is -128~127
Character Range is 0~127
float and double no automatic boxing pool 5. Summary

Through the mechanism of automatic boxing and unboxing, Java saves some memory overhead and creates object overhead, improves efficiency and simplifies code. When using this mechanism, the following points need to be noted:
1. In the case of the comparison of = =, the reference of the data within the scope of the automatic packing pool is the same, and the range is different.
2. When unpacking automatically, make sure that the reference to the wrapper class is not empty.
Reference:
Http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Related Article

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.