타입변환

서현서현·2022년 2월 8일
0

JAVA

목록 보기
3/27
post-thumbnail

Q. 데이터타입을 변환할 수 있을까?

(EX) byte ↔ int 데이터 타입 변환 방법에 대해서 알아보자


🐳 자동타입변환 (promotion)

: 값의 범위가 작은타입이 타입으로 저장될 경우

byte < short < int < long < float <double

큰타입은 작은타입을 얼마든지 수용할 수 있으므로 변환에 큰 문제가 없다.
문제는 반대의 경우에 나타나는데, 작은타입이 큰타입으로 변환될경우이다.

char = 2byte = short인데, short는 음수가 포함되지만 char는 양수만 포함한다.
같은 2byte지만 변환이 불가능 한 것이다!


🐳 강제타입변환 (casting)

큰타입을 작은타입으로 변환할 경우엔 강제타입변환, 즉 casting을 해야 한다.
(데이터의 손상를 감수해야한다.)

* casting 예제

package chapter02;

public class PromotionExample {
	public static void main(String[] args){
		byte b= 65;
		char c = b;
}

(오류) byte는 음수가 가능하므로 양수만 가능한 char형으로 변환이 불가능하다.

package chapter02;

public class PromotionExample {
	public static void main(String[] args){
		byte b= 65;
		char c = (char) b; //char로 캐스팅하면 오류해결
}

EX 1

package chapter02;

public class CastingExample {
	public static void main (String[] args) {
		int intValue = 44032;
		char charValue = (char) intValue;
		System.out.println(charValue);
		
		long longValue = 500;
		intValue = (int) longValue;
		System.out.println(intValue);
		
		double doubleValue = 3.14;
		intValue = (int) doubleValue;
		System.out.println(intValue);
	}
}

정수타입변수가 산술연산에서 피연산자로 사용되면 int보다 작은 byte나 short 경우 int로 변환되어 사용된다.

package chapter02;

public class ByteOperationExample {
	public static void main (String[] args) {
		byte result1 = 10+20;
		System.out.println(result1);
		
		byte x = 10;
		byte y = 20;
		byte result2 = x + y;
		System.out.println(result2);
	}
}

(오류)

		byte x = 10;
		byte y = 20;
		int result2 = x + y;

주의 : byte 로 선언된게 ‘변수’일때만 int로 변환

package chapter02;

public class OperationsPromotionExample {
	public static void main(String[] args) {
		byte byteValue1 = 10;
		byte byteValue2 = 20;
		// byte byteValue3 = byteValue1+byteValue2;
		int intValue1 = byteValue1 + byteValue2;
		System.out.println(intValue1);
		
		char charValue1 = 'A';
		char charValue2 =1;
		// char charValue3 = charValue1+charValue2;
		int intValue2 = charValue1+charValue2;
		System.out.println("유니코드: "+intValue2);
		System.out.println("출력문자: "+(char)intValue2);
		
		int intValue3 = 10;
		int intValue4 = intValue3/4;
		System.out.println(intValue4);
		
		int intValue5 =10;
		// int intValue6 = 10/4.0;
		double doubleValue =intValue5 /4.0;
		System.out.println(doubleValue);
		
		int x =1;
		int y =2;
		double result = (double) x/y;
		System.out.println(result);
		
	}
}

작은타입을 큰타입으로 바꿔서 계산해준다

String result2 = "10"+10이 1010이 아닌 20이 나오게 하고 싶을때
int result3 = Byte.parseByte("10")+10;
int result4 = Integer.parseInt("10")+200;

(주의) 캐스팅은 기본형끼리만 가능 (참조형 불가)

char var = (char) strValue;


🐳 문자열을 기본타입으로 강제 변환

반대로 기본타입을 문자열로 강제변환 하는 방법은

String str = String Value of()

🚨 char는 문자열로 캐스팅 불가

0개의 댓글