Java에서 형변환(Casting)의 모든 것: 기본형부터 참조형까지
1. 형변환(Casting)이란?
형변환은 데이터 타입을 다른 데이터 타입으로 변경하는 작업을 말합니다.
Java는 정적 타입 언어로, 변수의 타입이 고정되므로 형변환이 필요할 때 명시적으로 처리해야 합니다.
형변환은 크게 기본형 형변환(Primitive Type Casting)과 참조형 형변환(Reference Type Casting)으로 나뉩니다.
2. 형변환의 주요 유형
2.1 기본형 형변환 (Primitive Type Casting)
기본형 형변환은 숫자, 문자, 논리형 데이터 타입 간의 변환을 의미합니다.
- 예:
int
에서double
로 변환
2.2 참조형 형변환 (Reference Type Casting)
참조형 형변환은 클래스와 객체 간의 형변환을 의미하며, 상속 관계에서 자주 사용됩니다.
- 예:
Animal
타입에서Dog
타입으로 변환
3. 기본형 형변환의 상세 설명
기본형 형변환은 데이터 타입의 크기와 호환성에 따라 자동 형변환 또는 강제 형변환이 이루어집니다.
3.1 자동 형변환(Widening Casting)
자동 형변환은 작은 크기의 타입이 더 큰 크기의 타입으로 변환될 때 자동으로 이루어집니다.
자동 형변환의 규칙
- 데이터 손실이 없을 경우 자동 변환이 가능.
- 크기 순서:
byte
→short
→int
→long
→float
→double
예제
public class AutoCasting {
public static void main(String[] args) {
int intValue = 10;
double doubleValue = intValue; // 자동 형변환
System.out.println("정수: " + intValue);
System.out.println("실수: " + doubleValue);
}
}
결과
정수: 10
실수: 10.0
3.2 강제 형변환(Narrowing Casting)
강제 형변환은 큰 크기의 타입을 작은 크기의 타입으로 변환할 때 사용하며, 데이터 손실이 발생할 수 있습니다.
강제 형변환의 문법
타겟타입 변수명 = (타겟타입) 값;
예제
public class ForcedCasting {
public static void main(String[] args) {
double doubleValue = 10.5;
int intValue = (int) doubleValue; // 강제 형변환
System.out.println("실수: " + doubleValue);
System.out.println("정수: " + intValue);
}
}
결과
실수: 10.5
정수: 10
3.3 숫자 형변환에서의 주의점
데이터 손실 사례
public class DataLoss {
public static void main(String[] args) {
int largeValue = 130;
byte byteValue = (byte) largeValue; // 데이터 손실
System.out.println("정수: " + largeValue);
System.out.println("바이트: " + byteValue);
}
}
결과
정수: 130
바이트: -126
이유:
byte
는 -128에서 127까지만 표현할 수 있으므로 데이터가 손실됩니다.
3.4 문자와 숫자의 변환
문자를 숫자로 변환
public class CharToNumber {
public static void main(String[] args) {
char ch = 'A';
int asciiValue = ch; // 자동 형변환
System.out.println("문자: " + ch);
System.out.println("ASCII 값: " + asciiValue);
}
}
숫자를 문자로 변환
public class NumberToChar {
public static void main(String[] args) {
int asciiValue = 65;
char ch = (char) asciiValue; // 강제 형변환
System.out.println("ASCII 값: " + asciiValue);
System.out.println("문자: " + ch);
}
}
4. 참조형 형변환의 상세 설명
참조형 형변환은 클래스 간 상속 관계에서 사용됩니다.
4.1 업캐스팅(Upcasting)
정의
- 자식 클래스 객체를 부모 클래스 타입으로 변환.
- 자동 형변환이 이루어짐.
예제
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
public class UpcastingExample {
public static void main(String[] args) {
Animal animal = new Dog(); // 업캐스팅
animal.eat(); // 부모 클래스 메서드 호출 가능
// animal.bark(); // 오류: 자식 클래스 메서드는 호출 불가능
}
}
4.2 다운캐스팅(Downcasting)
정의
- 부모 클래스 객체를 자식 클래스 타입으로 변환.
- 반드시 명시적으로 강제 형변환을 수행해야 함.
예제
public class DowncastingExample {
public static void main(String[] args) {
Animal animal = new Dog(); // 업캐스팅
Dog dog = (Dog) animal; // 다운캐스팅
dog.eat();
dog.bark();
}
}
주의점
- 잘못된 다운캐스팅은
ClassCastException
을 발생시킴.
4.3 instanceof
연산자 활용
다운캐스팅 전에 객체의 타입을 확인하기 위해 instanceof
연산자를 사용합니다.
예제
public class InstanceofExample {
public static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal; // 안전한 다운캐스팅
dog.bark();
} else {
System.out.println("Casting is not possible.");
}
}
}
5. 형변환 관련 주요 예외
ClassCastException
잘못된 형변환 시 발생하는 예외.Animal animal = new Animal(); Dog dog = (Dog) animal; // ClassCastException 발생
NumberFormatException
문자열을 숫자로 변환할 때 형식이 맞지 않으면 발생.int num = Integer.parseInt("ABC"); // NumberFormatException 발생
6. 형변환의 실제 활용 사례
컬렉션 프레임워크에서의 형변환
List<String> list = new ArrayList<>(); list.add("Hello"); String value = (String) list.get(0); // 형변환 필요
다형성과 메서드 오버라이딩
Animal animal = new Dog(); animal.eat(); // 부모 클래스의 메서드 호출
Wrapper 클래스 변환
int num = Integer.parseInt("123"); // 문자열 → 정수 변환
7. 결론
Java에서 형변환은 기본형과 참조형 모두 다양한 상황에서 활용됩니다. 자동 형변환은 편리하지만, 강제 형변환과 다운캐스팅에서는 데이터 손실과 예외 발생 가능성을 주의해야 합니다. 형변환의 원리를 잘 이해하고 instanceof
와 같은 안전장치를 활용하면, 보다 안정적이고 유연한 코드를 작성할 수 있습니다.