형변환(Type Cast)

이상해씨·2023년 4월 25일
0

JAVA

목록 보기
5/40

캐스팅이란?

  • 다른 데이터 유형에 한 데이터 유형 값을 할당

1) 묵시적 형 변환 Widening Casting(자동)

  • 자동 형변환
  • 작은 타입에서 큰 타입으로 변환
  • 컴파일러가 자동적으로 변환
    byte -> short -> char-> int ->long-> float->double
public class Main {
  public static void main(String[] args) {
    int IntData = 9;
    double DoubleData = IntData; // Automatic casting: int to double

  }
}

2) 명시적 형 변환 Narrowing Casting(수동)

  • 강제 형변환
  • 큰 타입 -> 작은 타입
  • 묵시적 형변환시, 컴파일러가 오류를 발생.
  • 프로그래머가 직접 변환
  • (타입)을 명시하여 형을 변환 (강제 형변환)
    예) (int) FloatData

double -> float -> long -> int -> char -> short -> byte

public class Main {
  public static void main(String[] args) {
    double DoubleData = 9.78d;
    int IntData = (int) DoubleData; // Manual casting: double to int


  }
}
public class Ex02_TypeChange1
{
    public static void main(String[] args)
    {
    	int num1 = 1;
        byte num2 = 1;
        byte num3 = 127;
        byte num4 = 130;
        
        short num5 = 1;

        num2 = num5; // 오류 발생 :  error: incompatible types: possible lossy conversion from short to byte
        num2 = (byte) num5;
    }
}

참고

profile
공부에는 끝이 없다

0개의 댓글