数値リテラル内のアンダースコア

Java SE 7以降では、数値リテラルの桁の間のどこにでも、任意の数のアンダースコア文字(_)を含めることができます。この機能を使用すると、たとえば数値リテラルの桁の集まりを分離することで、コードの可読性を向上させることができます。

たとえば、桁数の多い数値がコードに含まれている場合は、アンダースコア文字を使用して3桁ずつに分離できます。これは、カンマなどの句読点やスペースを区切り文字として使用するのと似ています。

次の例は、数値リテラル内でアンダースコアを使用するほかの方法を示しています。

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
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;

アンダースコアを配置できるのは桁の間のみです。次の場所にアンダースコアを配置することはできません。

次の例は、数値リテラル内でのアンダースコアの有効な配置と無効な配置(強調表示)を示しています。

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

int x1 = _52;              // This is an identifier, not a numeric literal
int x2 = 5_2;              // OK (decimal literal)
int x3 = 52_;              // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;        // OK (decimal literal)

int x5 = 0_x52;            // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;            // OK (hexadecimal literal)
int x8 = 0x52_;            // Invalid; cannot put underscores at the end of a number

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

Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved.