[Java]타입 변환

Devlog·2024년 2월 14일

Java

목록 보기
3/41

타입 변환
byte a = 10; //byte 타입 변수 a에 10을 저장
int b = a; //byte 타입 변수 a에 저장된 10을 int 타입 변수 b에 복사해서 저장

자동 타입 변환
큰 허용 범위 타입 = 작은 허용 범위 타입

기본 타입을 허용 범위 크기순으로 정리
byte < short < int < long < float < double

1.int-byte
byte byteValue = 10;
int intValue = byteValue;

  1. 실수(float, double) - long
    long longValue = 5000000000L;
    float floatValue = longValue; //5.0E9f로 저장됨
    double doubleValue = longValue; //5.0E9로 저장됨

  2. int-char
    char charValue = 'A';
    int intValue = charValue; //65가 저장됨

예외)
char 타입보다 허용 범위가 작은 byte 타입은 char타입으로 자동 타입 변환될 수 없음
→ char타입의 허용 범위는 음수를 포함하지 않는데, byte타입은 음수를 포함하기 때문
byte byteValue = 65;
char charValue = byteValue; ← 컴파일 에러

public class PromotionExample {
	public static void main(String[] args) {
		//자동 타입 변환
		byte byteValue = 10;
		int intValue = byteValue;
		System.out.println("intValue: "+intValue);
		
		char charValue = '가';
		intValue = charValue;
		System.out.println("가의 유니코드: "+intValue);
		
		intValue = 50;
		long longValue = intValue;
		System.out.println("longValue: "+longValue);
		
		longValue = 100;
		float floatValue = longValue;
		System.out.println("floatValue: "+floatValue);
		
		floatValue = 100.5F;
		double doubleValue = floatValue;
		System.out.println("doubleValue: "+doubleValue);
	}
}

-출력-
intValue: 10
가의 유니코드: 44032
longValue: 50
floatValue: 100.0
doubleValue: 100.5

강제 타입 변환(캐스팅:casting)
: 큰 허용 범위 타입을 작은 허용 범위 타입으로 강제로 나눠서 저장하는 것

작은 허용 범위 타입 = (작은 허용 범위 타입)큰 허용 범위 타입
1.byte-int
int intValue = 10;
byte byteValue = (byte) intValue; //강제 타입 변환

2.int-char
int intValue = 65;
char charValue = (char)intValue;
System.out.println(charValue); // 'A'가 출력

3.int-double
소수점 이하 부분은 버려지고, 정수 부분만 저장됨
double doubleValue = 3.14;
int intValue = (int)doubleValue; //3만 저장됨

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);
	}

}

-출력-

500
3

정수 연산에서의 자동 타입 변환

1.byte타입 변수가 피연산자로 사용된 경우
byte x = 10;
byte y = 20;
byte result = x+y; //컴파일에러
int result = x+y;

2.int타입 변수가 피연산자로 사용된 경우
int x = 10;
int y = 20;
int result = x+y;

public class ByteOperationExample {

	public static void main(String[] args) {
		//자바 컴파일러는 컴파일 단계에서 10+20을 미리 연산해서 30을 만들고, result 변수에 30을 저장하도록 바이트 코드를 생성
		//이 경우에는 피연산자가 변수가 아니므로 int 타입으로 변환을 하지 않음
		byte result1 = 10+20;
		System.out.println(result1);
		
		byte x = 10;
		byte y = 20;
		int result2 = x+y;
		System.out.println(result2);
	}

}

-출력-
30
30

정수 연산식에서 모든 변수가 int타입으로 변환되는 것은 아님
두 피연산자 중 허용 범위가 큰 타입으로 변환되어 연산을 수행함

public class LongOperationExample {

	public static void main(String[] args) {
		byte value1 = 10;
		int value2 = 100;
		long value3 = 1000L;
		long result = value1+value2+value3;
		
		System.out.println(result);

	}
}

-출력-
1110

실수 연산에서의 자동 타입 변환

double타입으로 연산
int intValue = 10;
double doubleValue = 5.5;
doubel result = intValue + doubleValue;

int타입으로 연산
int intValue = 10;
double doubleValue = 5.5;
int result = intValue + (int)doubleValue; //15가 저장됨

-f or F가 없는 실수 리터럴을 double타입으로 해석함
double result = 1.5+2.3;
float result = 1.5+2.3; //컴파일에러
float result = 1.5F+2.3F;

int x = 1;
int y = 2;
double result = x/y;
→ 코드 실행 시, 0.5가 아닌 0.0이 출력됨
이유는 자바에서 정수 연산의 결과는 정수가 되기 때문
x/y의 연산 결과는 0.5가 아니라 0이 되고, 0을 double타입 변수 result에 저장하므로 0.0이 됨

위 코드의 결과가 0.5가 되기 위해서는 다른 방법으로 바꿔야함
[방법 1]
int x = 1;
int y = 2;
double result = (double) x/y;
System.out.println(result);

[방법 2]
int x = 1;
int y = 2;
double result = x / (double)y;
System.out.println(result);

[방법 3]
int x = 1;
int y = 2;
double result = (double)x / (double)y;
System.out.println(result);

만약 (double)(x/y)로 잘못 수정하면 0.5가 아닌 0.0을 얻음
이유는 (x/y)가 먼저 연산되어 0이 되고, 여기에 (double)0을 적용했기 때문임

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);
	}

}

-출력-
30
유니코드=66
출력문자=B
2
2.5
0.5


+연산에서의 문자열 자동 타입 변환

public class StringConcatExample {

	public static void main(String[] args) {
		
		//숫자 연산
		int value = 10 + 2 + 8;
		System.out.println("value: "+ value);
		
		//문자열 결합 연산
		String str1 = 10 + 2 + "8";
		System.out.println("str1: " + str1);
		
		String str2 = 10 + "2" + 8;
		System.out.println("str2: " + str2);
		
		String str3 = "10" + 2 + 8;
		System.out.println("str3: " + str3);
		
		String str4 = "10" + (2+8);
		System.out.println("str4: " + str4);

	}

}

-출력-
value: 20
str1: 128
str2: 1028
str3: 1028
str4: 1010


문자열을 기본 타입으로 강제 타입 변환
String → (byte, short, int, long, float, double, boolean)
Byte.parseByte();
Short.parseShort();
Integer.parseInt();
Long.parseLong();
Float.parseFloat();
Double.parseDouble();
Boolean.parseBoolean();

문자열이 숫자가 아닌 알파벳이나 특수 문자, 한글 등을 포함하고 있을 경우
숫자 타입으로 변환을 시도하면 숫자 형식 예외(NumberFormatException)가 발생함

(byte, short, int, long, float, double, boolean) → String
String.valueOf(기본타입값);
ex) Sting.value(3) → 문자열 "3"을 얻음

public class PrimitiveAndStringConversionExample {

	public static void main(String[] args) {
		int value1 = Integer.parseInt("10");
		double value2 = Double.parseDouble("3.14");
		boolean value3 = Boolean.parseBoolean("true");
		
		System.out.println("value1: " + value1);
		System.out.println("value3: " + value2);
		System.out.println("value3: " + value3);
		
		String str1 = String.valueOf(10);
		String str2 = String.valueOf(3.14);
		String str3 = String.valueOf(true);
		
		System.out.println("str1: " + str1);
		System.out.println("str2: " + str2);
		System.out.println("str3: " + str3);
	}

}

-출력-
value1: 10
value3: 3.14
value3: true
str1: 10
str2: 3.14
str3: true

0개의 댓글