Boxing and unpacking in Java

Source: Internet
Author: User

I. Basic data type Object type

1, first think of a question, after having the basic type why should there be a wrapper type?

Core: Let the basic type have the characteristics of the object, to achieve more functions.

Java is the programming language of a Face object, the basic type does not have the nature of the object, in order to let the basic type also has the characteristics of the object, there is a wrapper type.

When we use the collection type map, the list must use the wrapper type instead of the base type, it is equivalent to "wrapper" the base type, so that it has the nature of the object, and adds properties and methods to it to enrich the operation of the basic type.

int i = 1new// the system automatically packs I into an integer type object and then into the collection

2. Before Java SE5, if you want to generate an integer object with a value of 10, you must do this:

  Integer i = newInteger(10);

The auto-boxing feature is provided at the beginning of Java SE5, if you want to generate an integer object with a numeric value of 10, this is all you need:

  Integer i = 10;

This process automatically creates the corresponding integer object based on the value, which is the boxing.

So what is unpacking? As the name implies, it corresponds to boxing, which is to automatically convert the wrapper type to the basic data type:

Integer i = ten;  // Packing int n = i;   // Unpacking
Ii. how to carry out the packing and unpacking

Let's take the Interger class as an example and look at the code below:

 Public class Main {    publicstaticvoid  main (string[] args) {                 = ten;         int n = i;    }}

After you decompile the class file, you get the following: Javap-c Main

The content of the bytecode obtained from the decompile can be seen as an integer valueof (int) method that is automatically called when boxing. The Intvalue method of integer is called automatically when unpacking.

Others are similar, such as Double and Character.

Iii. related issues

1. What is the output of the following code?

 Public class Main {    publicstaticvoid  main (string[] args) {                 = +;         = +;         = $;         = $;                 System.out.println (i1= =i2);        SYSTEM.OUT.PRINTLN (i3= =i4);}    }

Maybe some friends will say it will output false, or some friends will say that it will output true. But in fact the output is:

true false
View Code

Why do you have such a result? The output shows that I1 and I2 point to the same object, while i3 and I4 point to different objects. At this point only a look at the source code will know, the following is an integer valueof method of the specific implementation:

 Public Static Integer valueOf (int  i) {        if(i >= -128 && i <= integercache.high)            /c6>return integercache.cache[i + +];         Else            return New Integer (i);    }
View Code

Where the Integercache class is implemented as:

Private Static classIntegercache {Static Final intHigh ; Static FinalInteger cache[]; Static {            Final intLow =-128; //High value is configured by property            intH = 127; if(Integercachehighpropvalue! =NULL) {                //Use Long.decode This avoid invoking methods that//require Integer ' s autoboxing cache to be initialized                inti =Long.decode (Integercachehighpropvalue). Intvalue (); I= Math.max (i, 127); //Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value--Low ); } High=h; Cache=Newinteger[(high-low) + 1]; intj =Low ;  for(intk = 0; K < Cache.length; k++) Cache[k]=NewInteger (j + +); }        PrivateIntegercache () {}}
View Code

As you can see from these 2 pieces of code, when you create an integer object by using the ValueOf method, if the value is between [-128,127], a reference to the object that already exists in Integercache.cache is returned, otherwise a new integer object is created.

The values for I1 and I2 in the above code are 100, so the objects that already exist are taken directly from the cache, so i1 and I2 point to the same object, while i3 and I4 point to different objects respectively.

2. What is the output of the following code?

 Public class Main {    publicstaticvoid  main (string[] args) {                 = 100.0;        = 100.0;         = 200.0;         = 200.0;                 System.out.println (i1= =i2);        SYSTEM.OUT.PRINTLN (i3= =i4);}    }

Some friends may think that the output of the above topic is the same, but in fact it is not. The actual output results are:

false false
View Code

This explains why the valueof method of the double class takes on a different implementation than the ValueOf method of the integer class. It is simple: the number of integer values in a range is limited, but floating-point numbers are not.

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.

3. What is the result of this code output:

 Public class Main {    publicstaticvoid  main (string[] args) {                 false ;         false ;         true ;         true ;                 System.out.println (i1= =i2);        SYSTEM.OUT.PRINTLN (i3= =i4);}    }

The output is:

true true
View Code

As to why this is the result, similarly, the source code of the Boolean class will be seen at a glance. The following is a specific implementation of the Boolean valueof method:

 Public Static Boolean ValueOf (boolean  b) {        return (b?  True:false);    }  Public Static Final New Boolean (true);  Public Static Final New Boolean (false);
View Code

4. Talk about the integer i = new integer (XXX) and integer i =xxx, the difference between the two ways.

Of course, this topic belongs to a relatively broad category. But the main point must be answered, I summed up the following two points are the difference:

1) The first way does not trigger the automatic boxing process, while the second method will trigger;

2) difference in execution efficiency and resource occupancy. The second approach is more efficient and resource-intensive than the first case in general (note that this is not absolute).

5. What are the output results of the following program?

 Public classMain { Public Static voidMain (string[] args) {Integer a= 1; Integer b= 2; Integer C= 3; Integer D= 3; Integer e= 321; Integer F= 321; Long g= 3L; Long h= 2L; System.out.println (c==d); System.out.println (e==f); System.out.println (c= = (A +b)); System.out.println (C.equals (a+b)); System.out.println (g= = (A +b)); System.out.println (G.equals (a+b)); System.out.println (G.equals (a+h)); }}

Don't look at the output, let the reader think about what the output of this code is. It is important to note that when the two operands of the "= =" operator are references to the wrapper type, it is whether the comparison points to the same object, and if one of the operands is an expression (that is, the arithmetic operation is included), the value is compared (that is, the process that triggers the automatic unboxing). Also, for wrapper types, the Equals method does not convert the type. Once you understand these 2 points, the above output will be at a glance:

true false true true true false true
View Code

Original link: http://www.cnblogs.com/dolphin0520/p/3780005.html

Boxing and unpacking in Java

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.