Integer Auto-boxing analysis

Source: Internet
Author: User

First look at what the following code will output:

public static void Main (string[] args) {

Integer i = 127;

Integer j = 128;

Integer II = 127;

Integer JJ = 128;

System.out.println (I==II);

System.out.println (J==JJ);

}

The answer is: true,false

What is this for? The reason is that the boxing action is achieved through the valueof method,

The object pool is used in the ValueOf method. If the parameter is between -128~127, the

The object is obtained directly from the object pool, not within that range, and the wrapper object is generated through new.

Let's take a look at the source code:

public static Integer valueOf (int i) {

Assert Integercache.high >= 127;

if (i >= integercache.low && i <= integercache.high)

low=-128,high=127

return integercache.cache[i + (-integercache.low)];

return new Integer (i);

}

So why can't you see the boxing action? How do you know it must be called the valueof function?

Automatic Boxing is the compilation of its behavior. We can compile the code and decompile it to see what the JVM directive is.

Here is the partially deserialized code in the above example:

Compiled from "Integertest.java"

public class Test.integertest {

public Test.integertest ();

Code:

0:aload_0

1:invokespecial #1//Method java/lang/object. " <init> ":() V

4:return

public static void Main (java.lang.string[]);

Code:

0:bipush 127

2:invokestatic #2//Method java/lang/integer.valueof: (I) Ljava/lang/integer;

5:astore_1

6:sipush 128

9:invokestatic #2//Method java/lang/integer.valueof: (I) Ljava/lang/integer;

}

We can see that auto boxing is really called the valueof function.

Integer Auto-boxing analysis

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.