본문 바로가기

코딩/Java

자바 - 변수에 숫자 값 할당 시 가독성 높이는 법 (int a = 1,000,000 가능?)

반응형

자바에서 숫자(integer, float 등등) 타입의 변수에 값을 할당 시, 값의 길이가 길면 가독성이 떨어진다.

public class Example {
    public static void main(String[] args) {
        int num = 100000000; // 얼마??
    }
}

 

 

 

public class Example {
    public static void main(String[] args) {
        int num = 100,000,000; // error: <identifier> expected
    }
}

천 단위로 콤마를 넣으면 에러가 발생.

 

 

 

public class Example {
    public static void main(String[] args) {
        int num = 100_000_000;

        System.out.println(num); // 100000000
    }
}

콤마 대신 _ (언더스코어)는 숫자 값에 삽입할 수 있다.

 

 

 

public class Example {
    public static void main(String[] args) {
        int numOne = 100_000_000;
        int numTwo = 1__000;
        int numThree = 1_0_0;

        System.out.println(numOne);     // 100000000
        System.out.println(numTwo);     // 1000
        System.out.println(numThree);   // 100
    }
}

_ (언더스코어)를 숫자 어디에든 넣을 수 있다.

 

 

 

_ (언더스코어) 사용 시 주의점

public class Example {
    public static void main(String[] args) {
        // 1. 숫자의 시작과 끝에 _ 불가
        // int numOne = _100;
        // int numTwo = 100_;

        // 2. 소수점 옆에 _ 불가
        // float floatOne = 0_.1f;
        // float floatTwo = 0._1f;

        // 3. 숫자의 접미사(Suffix) 옆에 _ 불가
        // float floatThree = 0.1_f;
        // long longOne = 1000_L;

        // 4. 숫자의 접두사(Prefix) 문자 사이 혹은 옆에 _ 불가
        // int binary = 0b_100;
        // int hex = 0_x100;
    }
}

 

 

자바 숫자 표현 공식 문서: https://docs.oracle.com/javase/8/docs/technotes/guides/language/underscores-literals.html

반응형