Java 中以0开头的int变量的真实值

  "Java 中以0开头的int变量的真实值"

Posted by     "华恒" on Tuesday, March 10, 2015

TOC

今天在leetcode上做题的时候无意中发现下面这个问题:

请问下面的Java语句输出的是什么值?

System.out.println(00123);
System.out.println(0_123);

答案是:

83
83

为什么??

当时也不解,后来在Java语言规范里面找到答案,请看Java 7 语言规范,规范里头明确规定: > 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.

也就是说,以0开始的int类型,Java会将它转换成八进制表示,对于00123来说,代表的八进制值为:1×8×8+2×8+3 = 83。