logo

Java의 유형 캐스팅

자바에서는 타입 캐스팅 수동 및 자동으로 데이터 유형을 다른 데이터 유형으로 변환하는 방법 또는 프로세스입니다. 자동 변환은 컴파일러가 수행하고 수동 변환은 프로그래머가 수행합니다. 이 섹션에서는 다음 내용을 논의하겠습니다. 타입 캐스팅 그리고 그 유형 적절한 예를 들어요.

Java의 유형 캐스팅

타입 캐스팅

한 데이터 유형의 값을 다른 데이터 유형으로 변환하는 것을 다음과 같이 말합니다. 타입 캐스팅 .

유형 캐스팅의 유형

유형 캐스팅에는 두 가지 유형이 있습니다.

  • 확폭형 주조
  • 협소형 주조

확폭형 주조

낮은 데이터 유형을 높은 데이터 유형으로 변환하는 것을 호출합니다. 확대 유형 캐스팅. 그것은 또한로 알려져 있습니다 암시적 변환 또는 캐스팅 다운 . 자동으로 수행됩니다. 데이터가 손실될 위험이 없으므로 안전합니다. 다음과 같은 경우에 발생합니다.

  • 두 데이터 유형은 서로 호환되어야 합니다.
  • 대상 유형은 소스 유형보다 커야 합니다.
 byte -> short -> char -> int -> long -> float -> double 

예를 들어, 숫자 데이터 유형을 char 또는 Boolean으로 변환하는 작업은 자동으로 수행되지 않습니다. 또한 char 및 Boolean 데이터 유형은 서로 호환되지 않습니다. 예를 살펴보겠습니다.

WideningTypeCastingExample.java

 public class WideningTypeCastingExample { public static void main(String[] args) { int x = 7; //automatically converts the integer type into long type long y = x; //automatically converts the long type into float type float z = y; System.out.println('Before conversion, int value '+x); System.out.println('After conversion, long value '+y); System.out.println('After conversion, float value '+z); } } 

산출

 Before conversion, the value is: 7 After conversion, the long value is: 7 After conversion, the float value is: 7.0 

위의 예에서는 변수 x를 가져와서 long 유형으로 변환했습니다. 그 후, long 유형이 float 유형으로 변환됩니다.

저녁 식사 대 저녁 식사

협소형 주조

상위 데이터 유형을 하위 데이터 유형으로 변환하는 것을 호출합니다. 좁아짐 유형 캐스팅. 그것은 또한로 알려져 있습니다 명시적 변환 또는 캐스팅하다 . 프로그래머가 수동으로 수행합니다. 캐스팅을 수행하지 않으면 컴파일러는 컴파일 타임 오류를 보고합니다.

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

축소형 캐스팅의 예를 살펴보겠습니다.

다음 예에서는 축소형 캐스팅을 두 번 수행했습니다. 먼저, long 데이터 유형을 int 유형으로 변환한 후 double 유형을 long 데이터 유형으로 변환했습니다.

NarrowingTypeCastingExample.java

 public class NarrowingTypeCastingExample { public static void main(String args[]) { double d = 166.66; //converting double data type into long data type long l = (long)d; //converting long data type into int data type int i = (int)l; System.out.println('Before conversion: '+d); //fractional part lost System.out.println('After conversion into long type: '+l); //fractional part lost System.out.println('After conversion into int type: '+i); } } 

산출

 Before conversion: 166.66 After conversion into long type: 166 After conversion into int type: 166