Skip to content

Instantly share code, notes, and snippets.

@singun
Last active January 24, 2024 00:18
Show Gist options
  • Save singun/ad10e770a68ea54f9067 to your computer and use it in GitHub Desktop.
Save singun/ad10e770a68ea54f9067 to your computer and use it in GitHub Desktop.
Long 자료형 나눗셈

다음 소스코드의 실행 결과는 뭐가 나올까?

public class HelloWorld{
     public static void main(String []args){
        final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
        final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
        System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
     }
}

결과는 바로 5가 출력된다. 1000이 출력되지 않는다.

이런 문제는 MICROS_PER_DAY가 오버플로 되기 때문에 발생한다. 계산 결과를 long 타입에 넣는 것은 문제가 되지 않지만 곱셈 연산이 int 자료형 끼리 이루어 지며 이때 오버플로가 발생한다. int*int의 결과는 int이다. 자바는 타겟 타이핑(targer typing)을 지원하지 않기 때문에 결과가 long이라 해도 피연산자들의 자료형이 long이 아니라면 long 연산을 하지 않는다.

target typing - 결과 자료형이 long이니까 연산을 할때 long 연산을 합시다!

문제 해결은 아래와 같이, 곱셈에 사용되는 첫번째 int를 long로 변경해주면 된다.

public class HelloWorld{
     public static void main(String []args){
        final long MICROS_PER_DAY = 24l * 60 * 60 * 1000 * 1000;
        final long MILLIS_PER_DAY = 24l * 60 * 60 * 1000;
        System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
     }
}
@hyunolike
Copy link

이해가 안됐는데 좋은 자료 감사합니다! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment