수색…


통사론

  • TargetType target = (SourceType) source;

숫자가 아닌 프리미티브 주조

boolean 형은 다른 원시 형과 캐스팅 될 수 없습니다.

유니 코드로 지정된 코드 포인트 매핑을 사용하여 char 을 모든 숫자 유형으로 /에서 변환 할 수 있습니다. char 는 부호없는 16 비트 정수 값 (2 바이트)으로 메모리에 표시되므로 byte (1 바이트)로 캐스팅하면 해당 비트가 8 개 삭제됩니다 (ASCII 문자는 안전합니다). Character 클래스의 유틸리티 메소드는 int (4 바이트)를 사용하여 코드 포인트 값으로 /에서 전송하지만 short 코드 (2 바이트)로 유니 코드 코드 포인트를 저장하는 데 충분합니다.

int badInt   = (int)  true; // Compiler error: incompatible types

char char1   = (char)   65; // A
byte byte1   = (byte)  'A'; // 65
short short1 = (short) 'A'; // 65
int int1     = (int)   'A'; // 65

char char2   = (char) 8253; // ‽
byte byte2   = (byte)  '‽'; // 61 (truncated code-point into the ASCII range)
short short2 = (short) '‽'; // 8253
int int2     = (int)   '‽'; // 8253

숫자 원시적 인 주조

숫자 형 프리미티브는 두 가지 방식으로 캐스팅 될 수 있습니다. 암시 적 형변환은 소스 유형이 대상 유형보다 작은 범위를 가질 때 발생합니다.

//Implicit casting
byte byteVar = 42;
short shortVar = byteVar;
int intVar = shortVar;
long longVar = intvar;
float floatVar = longVar;
double doubleVar = floatVar;

명시 적 형변환은 소스 유형이 대상 유형보다 큰 범위를 가질 때 수행되어야합니다.

//Explicit casting
double doubleVar = 42.0d;
float floatVar = (float) doubleVar;
long longVar = (long) floatVar;
int intVar = (int) longVar;
short shortVar = (short) intVar;
byte byteVar = (byte) shortVar;

부동 소수점 프리미티브 ( float , double )를 정수 프리미티브에 캐스팅 할 때이 숫자는 버림합니다 .

객체 주조

프리미티브와 마찬가지로 객체는 명시 적으로나 묵시적으로 캐스트 될 수 있습니다.

소스 유형이 목표 유형 (수퍼 클래스 또는 인터페이스로 3 스)을 확장 또는 구현할 때 암시 적 3 스팅이 발생합니다.

명시 적 형변환은 소스 유형이 대상 유형 (하위 유형으로 형변환)에 의해 확장되거나 구현 될 때 수행되어야합니다. 이것은 캐스트되는 오브젝트가 목표 유형 (또는 목표 부속 유형)이 아닌 경우 런타임 예외 ( ClassCastException )를 생성 할 수 있습니다.

Float floatVar = new Float(42.0f);
Number n = floatVar;                //Implicit (Float implements Number)
Float floatVar2 = (Float) n;        //Explicit
Double doubleVar = (Double) n;      //Throws exception (the object is not Double)

기본 숫자 승격

 static void testNumericPromotion() {

    char char1 = 1, char2 = 2;
    short short1 = 1, short2 = 2;
    int int1 = 1, int2 = 2;
    float float1 = 1.0f, float2 = 2.0f;

    // char1 = char1 + char2;      // Error: Cannot convert from int to char;
    // short1 = short1 + short2;   // Error: Cannot convert from int to short;
    int1 = char1 + char2;          // char is promoted to int.
    int1 = short1 + short2;        // short is promoted to int.
    int1 = char1 + short2;         // both char and short promoted to int.
    float1 = short1 + float2;      // short is promoted to float.
    int1 = int1 + int2;            // int is unchanged.
}

instanceof를 사용하여 객체를 형 변환 할 수 있는지 테스트

Java는 instanceof 연산자를 사용하여 객체가 특정 유형인지 또는 해당 유형의 하위 클래스인지 테스트합니다. 그런 다음 프로그램은 해당 오브젝트를 캐스트하거나 캐스트하지 않을 것을 선택할 수 있습니다.

Object obj = Calendar.getInstance();
long time = 0;

if(obj instanceof Calendar)
{
    time = ((Calendar)obj).getTime();
}
if(obj instanceof Date)
{
    time = ((Date)obj).getTime(); // This line will never be reached, obj is not a Date type.
}


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow