java - 为什么 Java SE 1.7 中数字文字中的下划线规则在八进制和十六进制中不同?八进制文字不是违反规则吗?

标签 java literals

根据 oracle doc下划线不能放在数字的开头,这很好。但是当涉及到八进制数时,我们可以在开头加上下划线。是不是很奇怪?

int x1 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int x2 = 0_52;             // OK (octal literal)

最佳答案

规则是:

Underscores are allowed as separators between digits that denote the integer.

当涉及带有基数前缀的文字时,表示整数的数字的构成有所不同,对于十六进制/二进制:

... the integer is only denoted by the digits after the 0x or 0b characters and before any type suffix. Therefore, underscores may not appear immediately after 0x or 0b, or after the last digit in the numeral.

但是对于八进制,规则是不同的:

In a decimal or octal literal, the integer is denoted by all the digits in the literal before any type suffix. Therefore, underscores may not appear before the first digit or after the last digit in the numeral. Underscores may appear after the initial 0 in an octal numeral (since 0 is a digit that denotes part of the integer) and after the initial non-zero digit in a non-zero decimal literal.

引用:https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1

关于java - 为什么 Java SE 1.7 中数字文字中的下划线规则在八进制和十六进制中不同?八进制文字不是违反规则吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52780165/

相关文章:

javascript - 如何使用循环将 key 对添加到对象文字中——而不覆盖现有条目?

scala 通用双括号文字

ruby - 当我在正则表达式的范围量词中放置一个空格时,它有什么意义?

java - 在屏幕上绘图 - Java

java - 在 eclipse 中为 postgres db 获取正确的驱动程序时遇到问题

java - 如何在 java 中编写十六进制浮点文字?

Java:如何从泛型类型获取类文字?

java - Hibernate:更新对象的最佳方式

javac 找不到包

java - 如何在 JFrame 组件之间添加延迟