int带前导0的行为奇怪

4

请问这里发生了什么?当我用前导零初始化整数时,程序不会忽略零,而是执行了其他我不知道的操作。

可能重复:
整数带有前导零

int num = 0200;

System.out.println(num); // 128

System.out.println(033); // 27

@aaaa bbbb:你点击了“关闭”链接并实际投票关闭了吗?还是你只是说你认为应该投票关闭? - S.Lott
我不是注册用户,所以我无法真正关闭。 - aaaa bbbb
2个回答

11

当然 - 根据Java语言规范第3.10.1节,它将其视为一个八进制字面量:

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

OctalNumeral:
        0 OctalDigits

OctalDigits:
        OctalDigit
        OctalDigit OctalDigits

OctalDigit: one of
        0 1 2 3 4 5 6 7

Note that octal numerals always consist of two or more digits; 0 is always considered to be a decimal numeral-not that it matters much in practice, for the numerals 0, 00, and 0x0 all represent exactly the same integer value.


当然我不知道为什么我没想到那个。当我在那里放了一个9时,它报错了!感谢您的快速回复,Jon! - Andrew
好的,我正在删除我的答案。Java规范应该足够清晰明了。 - Tom

6

这是一个八进制(基数为8)字面量。

同样地,0x27 是一个十六进制(基数为16)字面量,它的十进制值为39。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接