且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 08 在 Java 中不是有效的整数文字?

更新时间:2023-09-29 10:38:40

在 Java 和其他几种语言中,以 0 开头的整数文字被解释为八进制(基数为 8)的量.

In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity.

>

对于个位数(除了不允许的0809),结果是一样的,所以你可能没有注意到它们被解释为八进制.但是,如果您编写的数字超过一位有效数字,您可能会对结果感到困惑.

For single-digit numbers (other than 08 and 09, which are not allowed), the result is the same, so you might not notice that they are being interpreted as octal. However, if you write numbers with more than one significant digit you might be confused by the result.

例如:

010 ==  8
024 == 20

因为八进制文字通常不是您想要的,所以您应该始终注意不要以 0 开始整数文字,除非您实际上试图自己写零.

Since octal literals are usually not what you want, you should always take care to never begin an integer literal with 0, unless of course you are actually trying to write zero by itself.