JVM Knowledge

checkcast

Raw .md Oracle

Operation

Check whether object is of given type

Format

checkcast
indexbyte1
indexbyte2

Forms

checkcast = 192 (0xc0)

Operand Stack

..., objectref →

..., objectref

Description

The objectref must be of type reference. The unsigned indexbyte1 and indexbyte2 are used to construct an index into the run-time constant pool of the current class (§2.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The run-time constant pool entry at the index must be a symbolic reference to a class, array, or interface type.

If objectref is null, then the operand stack is unchanged.

Otherwise, the named class, array, or interface type is resolved (§5.4.3.1). If objectref is a value of the type given by the resolved class, array, or interface type, the operand stack is unchanged.

The following rules are used to determine whether a non-null reference to an object is a value of a reference type, T.

  • If the reference is to an instance of a class C, then:

    • If T is the type of a class D, then the reference is a value of T if C is D or a subclass of D;
    • If T is the type of an interface I, then the reference is a value of T if C implements I.
  • If the reference is to an array with component type SC, then:

    • If T is a class type, then the reference is a value of T if T is Object;

    • If T is an interface type, then the reference is a value of T if T is Cloneable or java.io.Serializable, as defined by the bootstrap class loader (§5.3);

    • If T is an array type TC[], that is, an array of components of type TC, then the reference is a value of T if one of the following is true:

      • TC and SC are the same type;
      • TC is the class type Object;
      • TC is a class or interface type, SC is a class or interface type, and the class or interface named by SC extends or implements the class or interface named by TC;
      • SC is an array type SCC[], and (applying these rules recursively) a reference to an array with component type SCC is a value of type TC.

Linking Exceptions

During resolution of the symbolic reference to the class, array, or interface type, any of the exceptions documented in §5.4.3.1 can be thrown.

Run-time Exception

Otherwise, if objectref is not null and is not a value of the type given by the resolved class, array, or interface type, the checkcast instruction throws a ClassCastException.

Notes

The checkcast instruction is very similar to the instanceof instruction (§instanceof). It differs in its treatment of null, its behavior when its test fails (checkcast throws an exception, instanceof pushes a result code), and its effect on the operand stack.