Questions about the Java integer size comparison

Source: Internet
Author: User

Reference:

Http://www.blogjava.net/zhangyuan/archive/2010/07/24/327011.html

Http://www.wenhq.com/article/view_392.html

Run it, and the results from the console are like this.

A==b:true
A.equals (b): True


When we change the value

Running, the console results are

A==b:false
A.equals (b): True


Source code--
In fact, when we use integer a = number, to assign the value of the integer This class is called public static integer valueOf (int i) this method.

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 comparison of data values. 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.

Summarize

128 to 127 of the two Integer objects, how to compare the same, beyond this range of only equals () is equal.

Java Auto-Boxing is the information value from 128 to 127, which is reused in memory after being boxed as object data, that is, for the same value, the same object is returned (this, like the String Class).
When compared directly to the numerical value (i.e., a==300000 ), it is probably the same as the comparison of int, so it is equal or equal.

Questions about the Java integer size comparison

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.