Unexpected int/Integer behavior when number starts by 0

别说谁变了你拦得住时间么 提交于 2020-01-02 14:31:50

问题


I can't understand why this is not printing the expected value (400300) when I put extra zeros in front of the number:

System.out.println(new Integer(0400300)); // prints 131264
System.out.println(0400300); // prints 131264

If I put one or more zeros in front of the number, the expected value is not printed.

// JUnit test does not pass:
assertTrue(0400300 == 400300);  // returns false!?

回答1:


Adding 0 to the front made the number an Octal literal. So:

0400300 = 3 * 8 ^ 2 + 4 * 8 ^ 5 = 131264

See JLS for the relevant sections. Quote:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.



来源:https://stackoverflow.com/questions/16611185/unexpected-int-integer-behavior-when-number-starts-by-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!