Integer auto-packing unpacking bug, creating objects in 128 to 127

Source: Internet
Author: User

1

public class Demo3 {public static void main (string[] args) {Integer a = 1;integer b = 2;integer c = 128;integer D = 128;in Teger E = 321;integer f = 321; Long g = 3L; System.out.println (System.identityhashcode (c));//366712642system.out.println (System.identityhashcode (d));// 1829164700//actually, when we use an integer a = number, to assign a value, the class is called the public static integer//valueOf (int i) method. public static Integer valueOf (int i) {//if (I >= -128 && i <= integercache.high)//Return integercache.ca Che[i + 128];//else//return new Integer (i);//}//Let's take a look at the code of valueof (int//i) and find out that he made an if judgment on the incoming parameter I. In the case of -128<=i<=127, the int primitive data type is used directly, but beyond this range is a new object. we//know that the "= =" symbol is a comparative memory address when comparing objects, whereas for raw data types it is a direct alignment data value. Then the problem is solved. As for why the value of the int type will be in the -128<=i<=127 range? We know that the eight-bit binary representation is exactly the range of 128 to 127. It's probably because of it. System.out.println (c = = d);//falseSystem.out.println (E = = f);//falseSystem.out.println (c = = (A + b));//Falsesystem.out . println (C.equals (A + b));//falseSystem.out.println (g = = (A + b));//TrueSystem.out.println (G.eqUals (A + b));//False type}} 

  

Integer auto-packing unpacking bug, creating objects in 128 to 127

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.