在代码中写一长串数字是一件很难读的东西。在JDK 7引入的新功能中,现在允许我们使用下划线字符来写数字文字,以打断数字以使其更易于阅读。
在以下示例中,您可以看到如何在数字文字中使用下划线。您会发现,它确实使数字更易于阅读。
package org.nhooo.example.basic; public class UnderscoreNumericExample { public static void main(String[] args) { // 使用下划线写数字文字是一种更简单的方法 // 阅读长号。 int maxInt = 2_147_483_647; int minInt = -2_147_483_648; if (maxInt == Integer.MAX_VALUE) { System.out.println("maxInt = " + maxInt); } if (minInt == Integer.MIN_VALUE) { System.out.println("minInt = " + minInt); } // 使用数字以二进制或十六进制文字形式写数字 // 下划线。 int maxIntBinary = 0B111_1111_1111_1111_1111_1111_1111_1111; int maxIntHex = 0X7____F____F____F____F____F____F____F; System.out.println("maxIntBinary = " + maxIntBinary); System.out.println("maxIntHex = " + maxIntHex); } }
代码段的结果:
maxInt = 2147483647 minInt = -2147483648 maxIntBinary = 2147483647 maxIntHex = 2147483647