반응형
형변환에는 두 가지가 있다.
자동 형변환 : 작은 타입 -> 큰 타입 (ex. int -> long, int -> double)
강제 형변환 : 큰 타입 -> 작은 타입 (ex int -> byte)
자동형변환은 데이터 손실이 일어날 일이 없다.
하지만 강제 형변환은 큰 크기의 타입이 작은 크기의 타입으로 변환되는 것이기에 데이터 손실이 일어날 수 있다.
byte 타입은 1byte 크기로 -2^7 ~ 2^7 -1 (-128 ~ 127) 까지의 수를 표현할 수 있다
만약 int 타입의 128을 byte로 형변환한다면 데이터 손실이 발생한다.
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int v1 = 128;
byte test = (byte)v1;
System.out.println(test);
}
}
출력
캐스팅 과정에서 데이터 손실이 일어나면, 데이터 손실이 발생함을 알리는 프로그램을 만들어 보았다.
main.class
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import java.util.Scanner;
public class Casting {
public static void main(String[] args) {
// TODO Auto-generated method stub
int type = 0;
double input = 0;
Scanner scan = new Scanner(System.in);
System.out.print("실수를 입력해주세요. : ");
input = scan.nextDouble(); //데이터 타입이 가장 큰 실수로 입력받기
while(true) {
System.out.println();
System.out.print("어떤 타입으로 변환할 것인가요? ( 1.byte 2. short"
+ "3. int 4. long 5. float. 6.double ) : "); // 원하는 캐스팅 타입 정하기
type = scan.nextInt();
if(type > 6 || type < 1) {
System.out.print("다시 입력해주세요. "); continue;
}
else break;
}
CastingLose cl = new CastingLose(type,input); // 캐스팅 시 데이터 손실이 발생하는지 판단하는 객체생성
// 캐스팅 완료시 출력 swich
switch(type) {
case 1 : if(cl.CastingLoseResult()==1) { byte btmp = (byte)input; System.out.println("캐스팅 완료 :"+ btmp);} break;
case 2 : if(cl.CastingLoseResult()==1) { short stmp = (short)input; System.out.println("캐스팅 완료 :"+ stmp); }break;
case 3 : if(cl.CastingLoseResult()==1) { int itmp = (int)input; System.out.println("캐스팅 완료 :"+ itmp); }break;
case 4 : if(cl.CastingLoseResult()==1) { long ltmp = (long)input; System.out.println("캐스팅 완료 :"+ ltmp); }break;
case 5 : if(cl.CastingLoseResult()==1) { float ftmp = (float)input; System.out.println("캐스팅 완료 :"+ ftmp); }break;
case 6 : if(cl.CastingLoseResult()==1) { double dtmp = input; System.out.println("캐스팅 완료 :"+ dtmp); }break;
default : break;
}
}
}
|
cs |
CastingLose.class
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
public class CastingLose {
private int type;
private double input;
public CastingLose(int type, double input) {
this.type = type;
this.input = input;
}
// 캐스팅 데이터 손실여부 전달 메소드
public int CastingLoseResult() {
switch(type) {
case 1 : if(isByteLose()==0) printLose(); else return 1; break;
case 2 : if(isShortLose()==0) printLose(); else return 1; break;
case 3 : if(isIntLose()==0) printLose(); else return 1; break;
case 4 : if(isLongLose()==0) printLose(); else return 1; break;
case 5 : if(isFloatLose()==0) printLose(); else return 1; break;
case 6 : if(isDoubleLose()==0) printLose(); else return 1; break;
default : return 0;
}
return 0;
}
// 타입별 캐스팅 손실 판단 메소드
public int isByteLose() {
if(input > Byte.MAX_VALUE || input < Byte.MIN_VALUE) return 0;
else return 1;
}
public int isShortLose() {
if(input > Short.MAX_VALUE || input < Short.MIN_VALUE) return 0;
else return 1;
}
public int isIntLose() {
if(input > Integer.MAX_VALUE || input < Integer.MIN_VALUE) return 0;
else return 1;
}
public int isLongLose() {
if(input > Long.MAX_VALUE || input < Long.MIN_VALUE) return 0;
else return 1;
}
public int isFloatLose() {
if(input > Float.MAX_VALUE || input < Float.MIN_VALUE) return 0;
else return 1;
}
public int isDoubleLose() {
if(input > Byte.MAX_VALUE || input < Byte.MIN_VALUE) return 0;
else return 1;
}
// 데이터 손실 발생시 메세지 출력 메소드
public void printLose() {
System.out.println("캐스팅 되기에 값이 크거나 너무 작아 데이터 손실이 발생합니다.");
}
}
|
cs |
출력 결과
이외에도
float와 double은 부동 소수점 방식을 채택함으로 가수부가 정수와 소수점 자리의 모든 숫자를 나타낼수 있어야한다.
int는 32bit이고 float의 경우, 가수부가 23bit이므로 int에서 float로 형변환시 데이터손실이 일어날수 있다.
하지만 double은 가수부가 52bit이므로 데이터 손실이 발생하지 않다.
반응형
'JAVA > JAVA Basic' 카테고리의 다른 글
[Java] 조건문과 반복문 심화 (0) | 2020.11.22 |
---|---|
[Java] 연산자 정리하기 (0) | 2020.11.21 |
' * ' 로 도형 만들기 (0) | 2020.09.10 |
10진수를 2진수, 8진수, 16진수로 변환 프로그램 (With Java) 2 (0) | 2020.09.09 |
10진수를 2진수, 8진수, 16진수로 변환 프로그램 (With Java) 1 (0) | 2020.09.04 |