checkcast 0xc0

Checks that the reference on top of the stack is of a type (throws ClassCastException if not).

Opcode
0xc0 (192)
Family
Objects and types
Operands
  • 2 bytes: constant pool index
Length
3 bytes
Operand stack
…, objectref → …, objectref
Can throw
ClassCastException

What it does

Checks that a reference is an instance of a type, leaving it on the stack, and throws ClassCastException if not. null always passes.

javac emits it for casts, and also for casts you never wrote: generic types are erased, so String s = list.get(0) compiles to invokeinterface List.get returning Object, then checkcast String. A pattern such as o instanceof String s is an instanceof followed by a checkcast.

How often javac uses it

In JDK 25.0.5's java.base module, checkcast appears 14,072 times in 2,837 of its 7,391 classes: 0.72% of all instructions, the 39th most common of 194 opcodes in use. Some of the methods that use it: java.io.ClassCache.get, java.io.Console.instantiateConsole, java.io.DataInputStream.readLine, java.io.DataOutputStream.writeUTF.

Examples

From the sample classes, compiled by javac 25 with -g. Each Java line is shown above the bytecode it compiled to; checkcast is highlighted.

public static EnumSwitch$Size[] values() in EnumSwitch.Size, compiled by javac 25
6enum Size { SMALL, MEDIUM, LARGE }
0getstatic #13// EnumSwitch$Size.$VALUES : EnumSwitch$Size[]
3invokevirtual #17// [LEnumSwitch$Size;.clone() : Object
6checkcast #18// EnumSwitch$Size[]

Open in the viewer

static String first(List names) in Bridge, compiled by javac 25
18return names.get(0);
0aload_0 // names
2invokeinterface #19, 2// List.get(int) : Object
7checkcast #25// String

Open in the viewer

Related instructions

instanceof Pops a reference; pushes 1 if it is of a type, else 0.athrow Throws the exception on top of the stack.

Specification: JVMS §6.5, checkcast (Java SE 25).