728x90
반응형
Error Message
error: incompatible types: possible lossy conversion from long to int
번역 : 호환되지 않는 유형 : long에서 int로 손실 변환 가능
Cause
int는 정수형 변수로 실수형을 int로 변환하면 소수점에 있는 수가 손실돼요..
long을 int로 저장하는 것은 손실되는 값이 존재하기 때문에 Java에서는 허용하지 않습니다..!
Solution
1. solution
우선, long값을 int로 변환하기 전에 값이 int 범위 내에 있는지 검사하는 방법이 있습니다.
이렇게 하면 값이 손실되지 않게할 수 있습니다.
long longVal = 123456789L;
if (longVal >= Integer.MIN_VALUE && longVal <= Integer.MAX_VALUE) {
int intVal = (int) longVal;
} else {
...
}
2. solution
다음 해결 방법으로는 명시적인 형변환을 사용하여 강제로 형변환을 해주면 됩니다.
대신 이 방법은 정보 손실이 발생할 수 있기 때문에 주의가 필요합니다.
long longVal = 123456789L;
int intVal = (int) longVal;
상황에 따라서 어떤 방법을 선택할지는 다르지만, 정보 손실을 피하거나 제어할 수 없는 경우에는 예외 처리를 사용해서 오류를 처리하는 것이 가장 좋습니다.
728x90
반응형
'🖥 백엔드 개발 > 에러 및 예외처리' 카테고리의 다른 글
[Error] error: incompatible types: String[] cannot be converted to char[] (1) | 2023.11.25 |
---|---|
[Error] error: no suitable method found for split(no arguments) (1) | 2023.11.25 |
[Exception] java.lang.ArrayIndexOutOfBoundsException: Index xout of bounds for length x (0) | 2023.11.21 |
[Error] error: unreachable statement (0) | 2023.11.19 |
[Error] error: missing return statement (0) | 2023.11.17 |