https://lyon69003.tistory.com/14
01_정수타입
- 자바의 정수형 데이터 타입으로는 byte, char, short, int, long이 있다. - 그 중 int를 기본 정수형이라고 한다. 모든 정수형은 연산시 int형으로 변환되어 처리되며 결과도 int형이다. 01. 바이트 타입 : - 바..
lyon69003.tistory.com
01. 데이터 범위
위 포스팅에서 살펴본 것 처럼, 해당 데이터타입이 나타낼 수 있는 범위를 초과하면 변수에 쓰레기값이 들어가게 된다. 그러면 원하는 결과를 얻지 못할 수 있는 것이다.
예를 들어 아래의 연산을 시도했을 때, result변수의 값이 int형으로 나타낼 수 있는 값의 범위를 벗어나기 때문에 -294967296이라는 이상한 값이 출력된다.
1
2
3
4
5
6
7
8
9
|
public class CheckOverflowExample {
public static void main(String[] args) {
int result = 2000000000 + 2000000000;
System.out.println(result);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
이러한 경우 아래와 같이 int 보다 더 큰 범위를 갖는 long형 변수를 사용 할 수도 있다.
그러면 원하는 값인 4000000000이 출력된다.
1
2
3
4
5
6
7
8
9
|
public class CheckOverflowExample {
public static void main(String[] args) {
long result = 2000000000L + 2000000000L;
System.out.println(result);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
하지만 아래처럼 결과값이 커질 경우, 똑같은 문제가 발생하여 -7527149226598858751 라는 이상한 값이 출력된다.
1
2
3
4
5
6
7
8
9
|
public class CheckOverflowExample {
public static void main(String[] args) {
long result = 999999999999999999L * 999999999999999999L;
System.out.println(result);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
02. Overflow 탐지
이러한 것을 막기 위해, 위 포스팅에서 살펴본 것 처럼 결과값이 유효범위를 초과할 경우 연산이 되지 않게 하는 방법이 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class CheckOverflowExample { //산술연산 전 오버플로우를 탐지해준다
public static void main(String[] args) {
try {
int result = safeAdd(2000000000, 2000000000);
System.out.println(result);
} catch(ArithmeticException e) {
System.out.println("오버플로우가 발생하여 정확하게 계산할 수 없음");
}
}
public static int safeAdd(int left, int right) {
if(right > 0) { //즉 덧셈
if(left > (Integer.MAX_VALUE - right)) {
throw new ArithmeticException("오버플로우 발생");
}
}else { //뺄셈
if(left < (Integer.MIN_VALUE - right)) {
throw new ArithmeticException("오버플로우 발생");
}
}
return left + right;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
03. NaN, Infininty
연산을 하다보면 NaN(Not a Number)과 Infinite 값이 발생하기도 한다.
예를 들어 어떤 수를 0으로 나눌 경우 ArithmeticException중 하나인 byZero 예외가 발생하며 프로그램이 종료되어 더이상 연산을 수행할 수 없게 된다.
그런데 같은 수를 실수 타입인 0.0이나 0.0f로 나눌 경우, /연산의 경우에는 infinity, % 연산의 경우에는 NaN의 결과가 나오게 된다. 이 때 프로그램이 종료되지 않기 때문에 다음 코드가 존재할 경우 계속해서 연산을 수행하게 되는데, 어떤 연산을 수행하더라도 infinity 또는 NaN의 결과가 산출되므로 데이터가 엉망이 된다. 즉, 연산을 계속 수행하지 못하도록 막아야 한다는 것이다.
간단하게는 아래와 같이 Double.isInfinite(double), Double.isNaN(double) 메소드를 이용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package ex02_Accuracy;
public class InfinityAndNaNCheckExample {
public static void main(String[] args) {
int x = 5;
double y = 0.0;
double z = x / y;
System.out.println("값 산출 불가");
} else {
System.out.println(z + 2);
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
위 코드의 문제점은, 콘솔상에는 '값 산출 불가'라는 메시지가 떴지만 실제로는 x/y 연산이 수행되어 z에 infinity 값이 들어갔다는 것이다. 이러한 경우 다음에 z의 값을 사용하여 연산하는 코드가 존재한다면 값이 엉망이 되어버린다.
따라서 아래와 같은 코드가 더욱 바람직하다.
>> 참고 : Double.valueOf(String) 메소드 : String 문자열을 double형으로 바꿔준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class InputDataCheckNaNExample2 {
public static void main(String[] args) {
String userInput = "NaN";
double var = Double.valueOf(userInput);
double currentBalance = 100000;
if(Double.isNaN(var)) {
System.out.println("NaN이 입력되어 연산을 수행할 수 없음");
var = 0.0; //currentBalance의 값을 유지시켜 줌
}
currentBalance += var;
System.out.println(currentBalance);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
9번째 줄의 코드를 통해 NaN이 입력되었을 경우에는 currentBalance의 현재값을 유지하도록 조치해준다.
'IT > Java' 카테고리의 다른 글
06_참조형 데이터 타입 (0) | 2019.12.01 |
---|---|
05_중복 없이 로또 번호 추출(조건문, Math.random()) (0) | 2019.11.30 |
04_String 연산자 (0) | 2019.11.29 |
02_실수형 데이터 (0) | 2019.11.29 |
01_정수타입 (0) | 2019.11.29 |