반응형

바쁜 분은 이것만

  1. 큰 타입(double)을 작은 타입(int)에 그냥 넣으면 나는 컴파일 에러. 소수점이 잘려도 된다면 (int) avg로 직접 바꾸기
  2. 반올림이 필요하면 (int) Math.round(x). Math.round(double)은 long을 돌려줘서 그냥 int에 넣으면 from long to int 에러
  3. score += 4.7은 자바가 몰래 (int)를 붙여 줘서 에러가 안 남. 대신 값이 조용히 잘림

error: incompatible types: possible lossy conversion from double to int는 "double 값을 int에 넣으면 소수점 같은 정보가 사라질 수 있다"는 뜻입니다. 실행 중에 나는 예외가 아니라 컴파일 단계에서 막히는 에러라, 프로그램이 한 줄도 실행되지 않아요. OpenJDK 27에서 상황별로 직접 재현해 정리했습니다.

1. 에러 메시지 읽는 법

public class L1 {
    public static void main(String[] args) {
        double avg = 87.6;
        int score = avg;
        System.out.println(score);
    }
}
L1.java:4: error: incompatible types: possible lossy conversion from double to int
        int score = avg;
                    ^
1 error
error: compilation failed
  • L1.java:4 — 4번째 줄에서 났다는 뜻
  • from double to int — 오른쪽 값의 타입(double)을 왼쪽 변수의 타입(int)에 넣으려 했다는 뜻
  • ^ — 문제가 된 값의 위치

자바는 int → double처럼 넓어지는 방향은 알아서 바꿔 주지만, double → int처럼 좁아지는 방향은 값이 바뀔 수 있어서 직접 적으라고 요구해요. 참고로 맥에서 언어를 한국어로 바꿔(-J-Duser.language=ko, LANG=ko_KR.UTF-8) 컴파일해도 이 메시지는 영어로 나옵니다. OpenJDK 27의 javac에는 독일어·일본어·중국어 번역만 들어 있어서 검색할 때도 영어 문장 그대로 찾으면 돼요.

2. 고치는 법 ① (int) 캐스팅 — 소수점은 버림

public class L2 {
    public static void main(String[] args) {
        double avg = 87.6;
        int a = (int) avg;
        int b = (int) -87.6;
        int c = (int) Math.round(avg);
        System.out.println("(int) 87.6 = " + a);
        System.out.println("(int) -87.6 = " + b);
        System.out.println("(int) Math.round(87.6) = " + c);
    }
}
(int) 87.6 = 87
(int) -87.6 = -87
(int) Math.round(87.6) = 88

(int)는 반올림이 아니라 소수점 아래를 그냥 버립니다. 음수도 0 쪽으로 잘려서 -87.6은 -88이 아니라 -87이 돼요. 87.6을 88로 만들고 싶다면 아래의 Math.round를 써야 합니다.

3. Math.round를 넣었는데 이번엔 from long to int

public class L3 {
    public static void main(String[] args) {
        double price = 1234.5;
        int won = Math.round(price);
        System.out.println(won);
    }
}
L3.java:4: error: incompatible types: possible lossy conversion from long to int
        int won = Math.round(price);
                            ^
1 error
error: compilation failed

메시지가 double에서 long으로 바뀌었어요. Math.round()는 받는 타입에 따라 돌려주는 타입이 다릅니다.

  • Math.round(double) → long
  • Math.round(float) → int

double은 int 범위보다 훨씬 큰 수도 담을 수 있어서 long으로 돌려주는 거예요. int가 필요하면 바깥에 (int)를 한 번 더 씌웁니다.

public class L4 {
    public static void main(String[] args) {
        double d = 1234.5;
        float f = 1234.5f;
        long r1 = Math.round(d);   // double → long
        int r2 = Math.round(f);    // float → int
        int r3 = (int) Math.round(d);
        int r4 = (int) Math.floor(d);
        int r5 = (int) Math.ceil(d);
        System.out.println("Math.round(double) = " + r1);
        System.out.println("Math.round(float)  = " + r2);
        System.out.println("(int) Math.round   = " + r3);
        System.out.println("(int) Math.floor   = " + r4);
        System.out.println("(int) Math.ceil    = " + r5);
        System.out.println("Math.round(-2.5)   = " + Math.round(-2.5));
        System.out.println("Math.round(2.5)    = " + Math.round(2.5));
    }
}
Math.round(double) = 1235
Math.round(float)  = 1235
(int) Math.round   = 1235
(int) Math.floor   = 1234
(int) Math.ceil    = 1235
Math.round(-2.5)   = -2
Math.round(2.5)    = 3

Math.floor(내림)와 Math.ceil(올림)은 double을 돌려주니 역시 (int)가 필요해요. 그리고 Math.round(-2.5)는 -3이 아니라 -2입니다. 0.5를 더한 뒤 내림하는 방식이라 음수의 .5는 큰 쪽(0 쪽)으로 갑니다.

4. int 나눗셈: 에러가 날 때와 안 날 때

평균을 구하다가 이 에러를 만나는 경우가 많아요. 2.0처럼 소수점 있는 숫자가 하나라도 섞이면 계산값이 double이 됩니다.

public class L10 {
    public static void main(String[] args) {
        int total = 7;
        int half = total / 2.0;
        System.out.println(half);
    }
}
L10.java:4: error: incompatible types: possible lossy conversion from double to int
        int half = total / 2.0;
                         ^
1 error
error: compilation failed

반대로 int끼리 나누면 에러는 없지만 소수점이 먼저 버려진 뒤 double에 들어갑니다. 이쪽이 더 찾기 어려워요.

public class L5 {
    public static void main(String[] args) {
        int total = 7;
        int count = 2;
        double avg1 = total / count;
        double avg2 = (double) total / count;
        double avg3 = (double) (total / count);
        double avg4 = total / 2.0;
        System.out.println("total / count          = " + avg1);
        System.out.println("(double) total / count = " + avg2);
        System.out.println("(double) (total/count) = " + avg3);
        System.out.println("total / 2.0            = " + avg4);
    }
}
total / count          = 3.0
(double) total / count = 3.5
(double) (total/count) = 3.0
total / 2.0            = 3.5

7 / 2는 int 계산이라 3이 되고, 그걸 double에 넣어 3.0이 됐어요. (double) total / count처럼 나누기 전에 한쪽을 double로 바꿔야 3.5가 나옵니다. 괄호로 (double) (total / count)를 감싸면 이미 3이 된 뒤라 소용없어요.

5. 그런데 += 는 왜 에러가 안 날까

public class L6 {
    public static void main(String[] args) {
        int score = 80;
        score += 4.7;
        System.out.println("score += 4.7 → " + score);
        int s2 = 80;
        s2 = s2 + 4.7;
    }
}
L6.java:7: error: incompatible types: possible lossy conversion from double to int
        s2 = s2 + 4.7;
                ^
1 error
error: compilation failed

에러는 7번째 줄 s2 = s2 + 4.7에만 나고, 4번째 줄 score += 4.7은 통과했어요. 자바 언어 명세(JLS 15.26.2)에 따르면 a += b는 a = (a의 타입) (a + b)로 처리됩니다. 즉 캐스팅이 자동으로 들어가 있어요. 7번째 줄을 지우고 돌려 보면:

public class L7 {
    public static void main(String[] args) {
        int score = 80;
        score += 4.7;          // score = (int) (score + 4.7) 와 같음
        System.out.println("score += 4.7 → " + score);
        int s2 = 80;
        s2 = (int) (s2 + 4.7);
        System.out.println("s2 = (int) (s2 + 4.7) → " + s2);
        byte b = 10;
        b += 300;              // byte 범위를 넘어도 에러 없이 잘림
        System.out.println("byte 10 += 300 → " + b);
        int big = 2_000_000_000;
        big *= 1.5;            // double 30억 → int 최대값으로
        System.out.println("int 20억 *= 1.5 → " + big);
    }
}
score += 4.7 → 84
s2 = (int) (s2 + 4.7) → 84
byte 10 += 300 → 54
int 20억 *= 1.5 → 2147483647

84.7이 84로 잘렸고, byte 10에 300을 더한 310은 byte 범위(-128~127)를 넘어 54가 됐어요. 20억에 1.5를 곱한 30억은 int 최대값 2147483647로 바뀌었습니다. 컴파일러가 아무 말도 안 하니 +=, *=에 소수를 섞을 땐 값이 잘린다는 걸 기억해 두세요.

6. double → int 말고도 같은 에러: long·float·byte

public class L8 {
    public static void main(String[] args) {
        long count = 10L;
        int n = count;
        float rate = 0.1;
        byte b = 10;
        b = b + 1;
    }
}
L8.java:4: error: incompatible types: possible lossy conversion from long to int
        int n = count;
                ^
L8.java:5: error: incompatible types: possible lossy conversion from double to float
        float rate = 0.1;
                     ^
L8.java:7: error: incompatible types: possible lossy conversion from int to byte
        b = b + 1;
              ^
3 errors
error: compilation failed
  • 0.1처럼 소수점 있는 숫자는 기본이 double이라 float에 넣으려면 0.1f
  • byte·short끼리 더해도 계산은 int로 되기 때문에 b + 1은 int

반면 byte b = 10;처럼 범위 안의 상수는 컴파일러가 값이 안 넘치는 걸 알아서 그냥 통과시켜 줘요.

public class L9 {
    public static void main(String[] args) {
        byte b = 10;          // 상수 10은 byte 범위라 OK
        final int K = 20;
        byte c = K;           // final 상수도 OK
        char ch = 65;
        float rate = 0.1f;    // f 붙이기
        long count = 10L;
        int n = (int) count;
        b = (byte) (b + 1);
        System.out.println(b + " " + c + " " + ch + " " + rate + " " + n);
    }
}
11 20 A 0.1 10

정리

상황 고치는 법
int x = 87.6; (from double to int) 버림이면 (int), 반올림이면 (int) Math.round()
int x = Math.round(d); (from long to int) Math.round(double)은 long → (int) 추가 또는 long 변수
int x = total / 2.0; double 변수로 받거나 (int)
평균이 3.5가 아니라 3.0 나누기 전에 (double) total / count
x += 4.7 에러 없음 자동 캐스팅으로 조용히 잘림 → 의도한 건지 확인
from double to float / int to byte 0.1f, (byte) (b + 1)

참고: JLS 5.1.3 Narrowing Primitive Conversion, 5.2 Assignment Contexts, 15.17.2 Division Operator, 15.26.2 Compound Assignment Operators / Oracle Java SE API 문서 — Math.round, Math.floor, Math.ceil

반응형

+ Recent posts