2013年12月21日 星期六

Underscores in Numeric Literals
許裕永 譯 (原文內容取自 Oracle 官網)
Underscores in Numeric Literals - Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
數值字面值中的下底線 - 任意數量的下底線字元( _ )可以出現在任何數值字面值的任何位置. 這個特色可以讓你如同範例一般, 把數值字面值中的數字分割成數個群組, 這樣可以增加你的程式碼的可讀性.

For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
在實務上, 如果你的程式碼中包含有許多位數的數值, 你可以使用下底線字元將數字切割成三個部份, 如同你使用像是逗點或空格之類的標點符號來區分數字.

The following example shows other ways you can use the underscore in numeric literals:
下列範例秀出了其他你可以使用下底線在數值字面值之中的方式.

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;

You can place underscores only between digits; you cannot place underscores in the following places:
你只可以在數字之中置放下底線; 你不可以在下列地方置放下底線:
  • At the beginning or end of a number
    數字的起頭或結尾Adjacent to a decimal point in a floating point literal
    緊臨浮點數字面值中的小數點
  • Prior to an F or L suffix
    在 F 或 L 的符號之前
  • In positions where a string of digits is expected
    在形勢上被預期為數字的 String.
The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:
下列範例示範了在數值字面值中合法及不合法的下底線置放位置(這些為最突出的):

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

沒有留言:

張貼留言