Introduction to Automatic unboxing of Java

Source: Internet
Author: User

In the interview process, often there will be the interviewer asked the basic question when the Java Disassembly box, about the problem is not very difficult, but if you do not pay attention to self-study, it may be a face confused, so I do some summary of this issue, and jointly promote!

First, the concept of unboxing

The so-called disassembly box is the conversion between Java's basic type and reference type since JDK1.5.

1.1 Unpacking

Unpacking is the action of converting the corresponding reference type, such as Long,integer,double,float, to the base data type, to the basic data type, called unpacking.

1.2 Boxing

Boxing is a byte, int, short, long, double,float,boolean,char these basic data types of Java are not declared as corresponding reference types when defining data types, and actions that are automatically converted to reference types under the compiler's processing are called boxing.

Second, the relevant application of unboxing

After JDK1.5, it is convenient for us to convert the basic type and reference type:

Package Com.hzp.CZX;/** * Test unpacking * @author Night solitary Cold * @version 1.1.1*/ Public classTestdemo {/** * After unboxing JDK1.5*/     Public Static voidFirst () {Integer I=7;//Basic Types--reference types        intJ=i;//reference Type--Basic typeSystem. out. println (j); }    /** * Unboxing JDK1.4*/     Public Static voidsecond () {Integer I=NewInteger ( +); intj=I.intvalue (); System. out. println (j); }    /** * Test method * @param args*/     Public Static voidMain (string[] args) {first ();    Second (); }}

The above describes some of the basic points of the disassembly box and how to use, but to use unboxing, there are some points to note, the following are some summary of these points of attention.

Third, the attention point

First put a piece of code as follows:

Package Com.ygh.CZX;/** * About Java's unboxing range anatomy * @author night solitary Cold * @version 1.1.1*/ Public classTest {/** * Take the integer type as an example*/     Public Static voidFirst () {Integer I=NewInteger (124); Integer J=NewInteger (124); System. out. println (i==j);//false Integer A1=- -; Integer A2=- -; System. out. println (a1==A2);//true Integer B1=-129; Integer B2=-129; System. out. println (b1==B2);//false Integer C1=127; Integer C2=127; System. out. println (c1==C2);//true Integer D1= -; Integer D2= -; System. out. println (d1==D2);//false} Public Static voidMain (string[] args) {first (); }}

Simply explain:

The first result is false because different objects are created, so they are not the same;

But why is the second and third result different?

The following is posted on the integer class of source code, from the perspective of the source to analyze the problem:

    /** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally being used in preference to * the C Onstructor {@link #Integer (int)}, as this method was likely * to yield significantly better space and time performance     by * caching frequently requested values.  * This method would always have the cache values in the range-128 to 127, * inclusive, and may caches other values outside     of this range.     * * @param i an {@code int} value.     * @return an {@code Integer} instance representing {@code i}. * @since 1.5*/     Public StaticInteger ValueOf (inti) {if(I >= integercache.low && i <=Integercache.high)returnIntegercache.cache[i + (-Integercache.low)]; return NewInteger (i); }

The above code is that when the automatic disassembly box, there is a scope, once out of this range, then the point is not the same object, but to return a newly created object, this range in the integer class of an internal private class Integercache can be reflected, the source code is as follows:

 Private Static classIntegercache {StaticFinalintLow =- -; StaticFinalintHigh ; Staticfinal Integer cache[]; Static {            //High value is configured by property            inth =127; String Integercachehighpropvalue=Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if(Integercachehighpropvalue! =NULL) {                Try {                    inti =parseint (Integercachehighpropvalue); I= Math.max (I,127); //Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value-(-low)-1); } Catch(NumberFormatException nfe) {//If The property cannot is parsed into an int, ignore it.}} High=h; Cache=Newinteger[(high-low) +1]; intj =Low ;  for(intK =0; K < Cache.length; k++) Cache[k]=NewInteger (j + +); //range [ -128, 127] must be interned (JLS7 5.1.7)Assert Integercache.high >=127; }        PrivateIntegercache () {}}

From here we can see that the range value is between [-128,127].

note that the implementations of the valueof methods of the classes Integer, short, Byte, Character, long are similar.
The implementation of the valueof method of Double and float is similar.

Summary: The scope of these basic types of automatic disassembly boxes is as follows:

1. Boolean-Type value

2. The value of all byte

3. The value of the short type in -128~127

4. Value of type int in -128~127

5. Value of char type between \ u0000~\ u00ff

Where double and float are different, we'll use double as an example to post code discussions:

Package Com.ygh.CZX;/** * about the Java unboxing range anatomy * * @author night solitary Cold * @version 1.1.1*/ Public classTest {/** * Double*/     Public Static voidFirst () {Double I1=100.0; Double I2=100.0; Double i3=200.0; Double I4=200.0; System. out. println (I1 = =i2);//false System. out. println (i3 = =i4);//false}/** * Test method*/     Public Static voidMain (string[] args) {first (); }}

Notice why the output of the above code is false? The same we still in the double class in the ValueOf method to discuss, paste out the source code is at a glance:

 /*  * * Returns a {@code Double} instance re     Presenting the specified * {@code double} value. * If a new {@code Double} instance is not required, this method * should generally being used in preference to the CONSTR Uctor * {@link #Double (Double)}, as this method was likely to yield * significantly better space and time Performan     Ce by caching * frequently requested values.     * * @param d a double value.     * @return a {@code Double} instance representing {@code D}. * @since 1.5  */ public  static  Double valueOf (double   D) {return  new      Double (d); }

That is, no matter what range of values your double is, he is returning a new object to you. Float with double, not too much to repeat.

The above is the author of the disassembly box of some finishing, if the reader has a different view can be put forward in the comment area, the author to modify!

Introduction to Automatic unboxing of Java

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.