반응형
- 타입 변환
- 자동 타입 변환
public class PromotionExample {
public static void main(String[] args) {
byte byteValue = 10; // 2byte 정수
int intValue = byteValue; // 자동타입변환 byte -> int
System.out.println(intValue);
char charValue = '가'; // 2byte
intValue = charValue; // 재할당 44032
System.out.println(intValue);
intValue = 500; // 4byte
long longValue = intValue; // 8byte int -> long
System.out.println(longValue);
}
}
값
10
44032
500
- 강제 타입 변환
public class CastingExample {
public static void main(String[] args) {
// 정수타입 : int(4byte) -> char(2byte)
int intValue = 44032;
char charValue = (char) intValue;
System.out.println(charValue);
// 정수타입 : long(8byte) -> int(4byte)
long longValue = 5000000000L;
intValue = (int) longValue; // 데이터 손실
System.out.println(intValue);
double doubleValue = 3.14;
intValue = (int) doubleValue;
System.out.println(intValue);
}
}
값
가
705032704
3
- 강제 타입 변환 전 데이터 손실 여부 체크
public class CheckValueBeforeCasting {
public static void main(String[] args) {
int i = 128;
// Byte.MIN_VALUE -128
// Byte.MAX_VALUE 127
// 조건식 : i < -128 또는 i > 127
// i가 -128보다 작거나 127보다 크다면
if(i < Byte.MIN_VALUE || i > Byte.MAX_VALUE) {
System.out.println("byte타입으로 변환할 수 없다");
} else {
byte b = (byte) i;
System.out.println(b);
}
}
}
- 연산식에서 자동 타입 변환
public class OperationPromotionExam {
public static void main(String[] args) {
byte bv1 = 10;
byte bv2 = 20;
int result = bv1 + bv2;
char charValue1 = 'A'; // 65
char charValue2 = 1;
int result2 = charValue1 + charValue2;
int intValue3 = 10;
int intValue4 = 4;
int result3 = intValue3 / intValue4; // 2.5
System.out.println(result3); // 2
double result4 = intValue3 / intValue4;
System.out.println(result4); // 2.0
double result5 = (double)intValue3 / intValue4;
System.out.println(result5); // 2.5
}
}
result4 가 2.5 가 아니라 2.0인 이유는 이미 int로 연산이 이뤄졌기때문
2.5로 바꾸기 위해서 변수 둘중 하나를 변환해야함 (result5 참고)
반응형
댓글