programing

숫자 리터럴의 Java 7 밑줄

randomtip 2021. 1. 14. 08:13
반응형

숫자 리터럴의 Java 7 밑줄


_숫자에서 숫자를 구분 하기 위해 a 사용해야 할 때 사용할 수없는 다음 경우를 이해하지 못합니다.

숫자 문자열이 예상되는 위치

( 여기 JDK7 가이드에 설명 된대로 )

몇 가지 예?


당신은하지 않습니다 당신이 "_"를 사용 할 수 있습니다 . 제안서에 제시된 예는 신용 카드 번호, 전화 번호 또는 코드에 구분 기호를 사용하는 것이 합당한 단순한 숫자입니다.

"자릿수 문자열이 예상되는 위치"의 경우 단순히 숫자로 시작 (또는 끝)해야하는 위치에 있습니다. 여기 예시들이 있습니다.

이 제안에 따르면 밑줄은 숫자 사이에만 배치 할 수 있습니다. 일반적으로 숫자 문자열이 예상되는 위치에는 자체적으로 배치 할 수 없습니다.

int x1 = _52; // 이것은 숫자 리터럴이 아니라 식별자입니다.

int x2 = 5_2; // 확인. (10 진수 리터럴)

int x2 = 52_; // 불법. (밑줄은 항상 숫자 사이 여야합니다.)

int x3 = 5_______2; // 확인. (10 진수 리터럴.)

int x4 = 0_x52; // 불법. "0x"기수 접두사에 밑줄을 넣을 수 없습니다.

int x5 = 0x_52; // 불법. (밑줄은 항상 숫자 사이 여야합니다.)

int x6 = 0x5_2; // 확인. (16 진수 리터럴)

정수 x6 = 0x52_; // 불법. (밑줄은 항상 숫자 사이 여야합니다.)

int x6 = 0x_; // 불법. (밑줄을 제거한 상태에서는 유효하지 않음)

int x7 = 0_52; // 확인. (8 진 리터럴)

int x7 = 05_2; // 확인. (8 진 리터럴)

int x8 = 052_; // 불법. (밑줄은 항상 숫자 사이 여야합니다.)


자원:


Javadoc에 작성된대로 :

Java SE 7 이상에서는 숫자 리터럴의 숫자 사이에 원하는 수의 밑줄 문자 (_)가 나타날 수 있습니다. 예를 들어이 기능을 사용하면 숫자 리터럴에서 숫자 그룹을 구분하여 코드의 가독성을 높일 수 있습니다.

예를 들어 코드에 자릿수가 많은 숫자가 포함 된 경우 쉼표 나 공백과 같은 구두점을 구분 기호로 사용하는 방법과 유사하게 밑줄 문자를 사용하여 숫자를 세 그룹으로 구분할 수 있습니다.

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;

누군가가 원래 게시물 (OP)에서 URL을 죽인 것 같습니다. 다음은 일부 서식 기능으로 인해 다시 죽일 경우를 대비 한 전체 불쾌한 URL입니다.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

당신이 말하는 페이지의 구체적인 인용문은 다음과 같습니다.

숫자 사이에만 밑줄을 넣을 수 있습니다. 다음 위치에는 밑줄을 넣을 수 없습니다.

  • 숫자의 시작 또는 끝

  • 부동 소수점 리터럴에서 소수점에 인접

  • F 또는 L 접미사 앞

  • 숫자 문자열이 예상되는 위치

그건 그렇고, 가능한 한 까다로워지기 위해 다음 예제와 같이 세 번째 지점에서 D 접미사 앞에 밑줄을 사용할 수 없다는 것을 언급해야합니다.

double trouble = 123.456_D;  //fail
float myBoat = 321.123_F;  //fail
long winded = 90210_L;  //fail

나도 세 번째 요점이 다소 궁금하다는 것을 알았다. 내 말은, 대부분의 경우 모든 시나리오가 처음 세 가지 요점으로 다루어집니다. 그렇다면 그들이 말하는이 신비한 '문자열'은 무엇입니까? 이 신비한 네 번째 항목을 추가하도록 강제하는 처음 세 가지 요점으로 실제로 해결되지 않은 시나리오는 무엇입니까?

처음에는 작동하지 않는 다음 예제와 같이 b 또는 x 뒤에 숫자가 예상되는 16 진수 표기법 또는 이진 표기법에 대해 이야기하고 있다고 생각했습니다.

byte size = 0_b111101;  //fail
byte me = 0b_111101;  //fail
int hexed = 0_x_BABE;  //fail

Still, I think that might technically be the same as the first point, which says an underscore can't be at the beginning of the number; but certainly, a 'string of numbers' is expected after a 'b' or an 'x' when using binary or hex, right? So if I was a betting man, I might put some money behind the binary/hexadecimal scenario. But I have another plausible scenario on which I might hedge my bet. Here it goes.

Personally, I wish there was a rule in Java that said you can only use the word 'string' when talking about a java.lang.String. Allowing the term 'string' to retain it's pedestrian meaning causes confusion, and this is a perfect example.

이제 네 번째 요점이 "자릿수 java.lang.String이 예상되는 위치에서"라고 말하면 구문 분석해야하는 숫자를 나타내는 실제 java.lang.String 객체에 대해 이야기하고 있다는 결론에 도달 할 수 있습니다. 따라서 다음 코드를 사용하십시오.

int i = Integer.parseInt("123_456");

그게 컴파일 될까요? 실행 될까요? 잘 컴파일되지만 물론 parseInt 메서드는 숫자의 java.lang.String을 예상하고 해당 숫자 java.lang.String의 유효성 검사 또는 구문 분석은 런타임에 다음 오류를 트리거합니다.

스레드 "main"의 예외 java.lang.NumberFormatException : 입력 문자열의 경우 : "123_456"at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) at java.lang.Integer.parseInt (Integer.java:492) at Tester.main (Tester.java:7)의 java.lang.Integer.parseInt (Integer.java:527)

물론 이것은 런타임 오류이며 Oracle 문서는 실제로 컴파일 시간에 플래그가 지정되는 오류에 대해 말하는 것으로 보입니다. 그러나 이것은 확실히 '문자열'이 예상되는 시나리오입니다.

이제 Oracle 문서 만 Wiki 형식으로되어 있다면. 다음과 같은 내용을 추가하고 싶을 수도 있습니다.

숫자 사이에만 밑줄을 넣을 수 있습니다. 다음 위치에는 밑줄을 넣을 수 없습니다.

  • 숫자의 시작 또는 끝

  • 부동 소수점 리터럴에서 소수점에 인접

  • 'F', 'L'또는 'D'접미사 앞 ( 'D'추가)

  • 16 진 및 2 진 마커 'x'및 'b'앞 또는 뒤

  • 그리고 숫자 만 기대하는 메소드에 java.lang.String을 제공하면 백그라운드에서 사용되는 구문 분석 알고리즘에 의해 런타임 예외가 발생할 것으로 예상됩니다.

그건 그렇고, 나는 TheServerSide에서 주제에 대한 작은 기사를 썼습니다. 자유롭게 살펴보십시오. 이 기사는 Oracle Certified Professional, Java 7 Programmer 인증 목표를 달성하도록 설계되었지만 밑줄 사용과 관련된 규칙을 일반적으로 설명하는 매우 포괄적이고 읽기 쉬운 기사입니다.

OCPJP 인증 : 밑줄이있는 숫자 리터럴에 대해 알아야 할 사항

도움이되기를 바랍니다.


모르겠지만 여기에 문법이 있습니다. (어디서나 "문자열"이 보이지 않음)

http://download.oracle.com/otndocs/jcp/enhancements-0.875-pr-oth-JSpec/

IntegerLiteral:
    DecimalIntegerLiteral 
    HexIntegerLiteral 
    OctalIntegerLiteral 
    BinaryIntegerLiteral 

BinaryIntegerLiteral:
    BinaryNumeral IntegerTypeSuffixopt 

BinaryNumeral:
    0 b BinaryDigits 
    0 B BinaryDigits 

DecimalNumeral:
    0 
    NonZeroDigit Digitsopt 
    NonZeroDigit Underscores Digits 

Underscores:
    _ 
    Underscores _ 

Digits:
    Digit
    Digit DigitsAndUnderscoresopt Digit

DigitsAndUnderscores:
    DigitOrUnderscore
    DigitsAndUnderscores DigitOrUnderscore

DigitOrUnderscore:
    Digit
    _

HexDigits:
    HexDigit 
    HexDigit HexDigitsAndUnderscoresopt HexDigit 

HexDigitsAndUnderscores:
    HexDigitOrUnderscore 
    HexDigitsAndUnderscores HexDigitOrUnderscore 

HexDigitOrUnderscore:
    HexDigit 
    _ 

OctalNumeral:
    0 OctalDigits 
    0 Underscores OctalDigits 

OctalDigits:
    OctalDigit 
    OctalDigit OctalDigitsAndUnderscoresopt OctalDigit 

OctalDigitsAndUnderscores:
    OctalDigitOrUnderscore 
    OctalDigitsAndUnderscores OctalDigitOrUnderscore 

OctalDigitOrUnderscore:
    OctalDigit 
    _ 

BinaryDigits:
    BinaryDigit 
    BinaryDigit BinaryDigitsAndUnderscoresopt BinaryDigit 

BinaryDigitsAndUnderscores:
    BinaryDigitOrUnderscore 
    BinaryDigitsAndUnderscores BinaryDigitOrUnderscore 

BinaryDigitOrUnderscore:
    BinaryDigit
    _ 

BinaryDigit: one of
    0 1

My interpretation of this is that underscores cannot be placed by themselves in positions where a string of digits would normally be expected:

int x1= _; // Illegal.

"In positions where a string of digits is expected" means where a variable of type String which contains digits is expected, then using an underscore will make the underscore part of the number. For example look at the code below:

int num = 999_333;    
String anum = "999_333";
System.out.println(num);   //Outputs 999333
System.out.println(anum);  //Outputs 999_333

So if you have a method expecting a String of digits as one of the arguments, DO NOT use underscore to separate the digits because it will be treated as any other String.


TL;TR;

You do not have to use it anywhere, but if you want, you can use it everywhere between every digits.

This is especially useful to improving readability:

10_000_000_000 // Is equal to 10000000000
7_687_316_418_138_483.345_938 // Is equal to 7687316418138483.345938

I believe the In positions where a string of digits is expected covers things like escape sequences in string literals. For example, you can't say \u00_11.

ReferenceURL : https://stackoverflow.com/questions/6212558/java-7-underscore-in-numeric-literals

반응형