在数字文字中引入下划线 。 从Java 7开始,您可以在Java源代码中向可读性更高的10_000_000_000写一个长数字,例如10000000000。 在数字文字中使用下划线的最重要原因之一是避免了细微的错误,而这些细微的错误很难通过查看代码来找出。 很难注意到在10000000000和1000000000之间缺少的零或多余的零,而不是10_000_000_000和1_000_000_000。 因此,如果您正在使用Java源代码处理大量数字,请在数字中使用下划线以提高可读性


如何在Java中实现数字下划线

就像我说的那样,它是一种语法糖,就像在切换情况下如何实现String一样,这也是在编译器的帮助下实现的。 在编译时,编译器会删除这些下划线并将实际数字放入变量中。 例如10_000_000将在编译时转换为10000000。 由于CPU处理长数字串没有问题,这对他很有趣,所以我们不必理会,就是我们这个贫穷的人遇到了处理长数字的问题。 此功能对于银行和金融领域应用程序特别有用,该应用程序处理大笔钱,信用卡号,银行帐号和其他处理较长ID的域。 尽管强烈建议不要在Java文件中写入敏感数据,并且绝对不要在生产代码中这样做,但带下划线的数字比以前容易得多。

Java中在数字中使用下划线的规则

jackson java 下划线 java中如何给文字加下划线_jackson java 下划线

Java编程语言对于在数字文字中使用下划线具有严格的规则集。 如前所述,您只能在数字之间使用它们。 您不能以下划线开头或以下划线结尾。 这是更多地方,您不能在数字文字中使用下划线:

  1. 在数字的开头或结尾
  2. 与浮点文字中的小数点相邻
  3. 在F或L后缀之前
  4. 在需要一串数字的位置

这是几个示例,显示了数字文字中下划线的一些有效和无效用法

float pi1 = 3_.1415F;      // Invalid; cannot put underscores adjacent (before) to a decimal point
float pi2 = 3._1415F;      // Invalid; cannot put underscores adjacent (after) to a decimal point
long socialSecurityNumber1  = 999_99_9999_L;  // Invalid; cannot put underscores prior to an L suffix

int a1 = _52;              // This is an identifier, not a numeric literal, starts with underscore
int a2 = 5_2;              // OK (decimal literal)
int a3 = 52_;              // Invalid; cannot put underscores at the end of a literal
int a4 = 5_______2;        // OK (decimal literal)

int a5 = 0_x52;            // Invalid; cannot put underscores in the 0x radix prefix
int a6 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int a7 = 0x5_2;            // OK (hexadecimal literal)
int a8 = 0x52_;            // Invalid; cannot put underscores at the end of a number

int a9 = 0_52;             // OK (octal literal)
int a10 = 05_2;            // OK (octal literal)
int a11 = 052_;            // Invalid; cannot put underscores at the end of a number

这是在数字文字中使用下划线的更多示例

long creditCardNumber = 6684_5678_9012_3456L;  // Never do it on production code
long socialSecurityNumber = 333_99_9999L;      // Never, Ever do it on production code
float pi =              3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

您可以看到,与不使用数字下划线相比,代码更具可读性。 顺便说一句,在Java中始终使用L表示长文字。 尽管使用小写字母l是合法的,但您永远不要将其与数字一起使用,因为它看起来与数字1完全相似。请告诉我您是否能找出12l和121之间的差异,我想不是很多。 12L和121怎么样?

始终在数字中使用下划线 ,尤其是使用长数字时,应使其更具可读性。 我知道此功能仅在Java 1.7中可用,并且尚未广泛使用,但是考虑到Java 8配置文件,我希望Java 8将比Java 7更快,更广泛地被社区采用。


https://www.javacodegeeks.com/2014/03/why-use-underscore-in-numbers-from-java-se-7-underscore-in-numeric-literals.html