Questions about automatic packing (New Features of automatic packing/folding in jdk1.5)

Source: Internet
Author: User

I saw such a question in the forum today.

Int K = 100;
Integer int1 = integer. valueof (k );
Integer int2 = integer. valueof (k );
System. Out. println ("A." + (int1 = int2); // true
K = 200;
Integer int3 = K;
Integer int4 = K;
System. Out. println ("B." + (int3 = int4); // false
Char c = 'a ';
Character char1 = C;
Character char2 = C;
System. Out. println ("C." + (char1 = char2); // true
C = 'status ';
Character char3 = C;
Character char4 = C;
System. Out. println ("D." + (char3 = char4); // false

What is the result? I wrote all the answers below.

For integer int1 = integer. valueof (k );

We all know that it is the automatic binning function added by jdk1.5, that is, automatic conversion of the original class and its encapsulation class.

However, the later int1 = int2 returns true, and the same method int3 = int4 returns false, which makes it hard to figure out.

Finally, I understood it only after reading the JDK source code.

Source code of valueof:

Public static integer valueof (int I )...{
Final int offset = 128;
If (I> =-128 & I <= 127)... {// must Cache
Return integercache. cache [I + offset];
}
Return new INTEGER (I );
}

It processes the size of byte (-128-127), which is obtained from the 256 integer cache initialized by integercache.

In this way, only one object is of course true, and the following 200 is out of the range and a new INTEGER (I) is used to generate a new object, and the return value is false.

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.