Underscore in Numeric Literals
Java 7+ อนุญาตให้ใช้ _ คั่นกลุ่มตัวเลข เพื่ออ่านง่ายขึ้น ไม่ส่งผลต่อค่า
ตัวอย่าง
public class Demo {
public static void main(String[] args) {
// Integer
int million = 1_000_000;
int creditCard = 1234_5678_9012_3456; // ต้องเป็น long จริงๆ
// Long (ต้องมี L)
long phone = 08_1234_5678L;
long big = 9_223_372_036_854_775_807L;
// Float (ต้องมี f/F)
float pi = 3.14159_26535_89793f;
// Double
double e = 2.71828_18284_59045;
// Binary (Java 7+)
int bits = 0b1010_1100_1111_0000;
// Hex
int color = 0xFF_CC_00_99;
// Octal
int perm = 0_755;
System.out.println("Million: " + million);
System.out.println("Pi: " + pi);
System.out.println("Binary: " + Integer.toBinaryString(bits));
System.out.println("Hex color: " + Integer.toHexString(color));
}
}
ผลลัพธ์
Million: 1000000 Pi: 3.1415927 Binary: 1010110011110000 Hex color: ffcc0099
กฎการใช้ Underscore
- วางได้ระหว่าง digits เท่านั้น
- ห้าม วาง:
- ต้นเลข:
_123❌ - ท้ายเลข:
123_❌ - ติด decimal point:
123_.45,123._45❌ - ติด type suffix:
123_L,123_f❌ - ติด prefix:
0_xFF,0_b1010❌
- ต้นเลข:
- หลาย underscore ติดกันได้:
1__000(แต่อ่านยาก ไม่แนะนำ)
ประโยชน์
- อ่านง่าย:
1_000_000vs1000000 - Credit card:
1234_5678_9012_3456 - Bit flags:
0b0001_0010_0100_1000 - Hex colors:
0xFF_00_00(RGB)