instanceof 0xc1

Pops a reference; pushes 1 if it is of a type, else 0.

Opcode
0xc1 (193)
Family
Objects and types
Operands
  • 2 bytes: constant pool index
Length
3 bytes
Operand stack
…, objectref → …, result (int)
Can throw
nothing at run time (beyond linking errors)

What it does

Pops a reference and pushes 1 if it is an instance of the type, 0 if not. null gives 0.

A type pattern (o instanceof String s, Java 16) compiles to the same instanceof, then a checkcast and a store into the new variable.

How often javac uses it

In JDK 25.0.5's java.base module, instanceof appears 2,895 times in 1,052 of its 7,391 classes: 0.15% of all instructions, the 77th most common of 194 opcodes in use. Some of the methods that use it: java.io.DataInputStream.readLine, java.io.DataOutputStream.writeUTF, java.io.File.equals, java.io.FileInputStream.transferTo.

Examples

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

static int oldStyle(Object o) in InstanceofPattern, compiled by javac 25
12if (o instanceof String) {
0aload_0 // o
1instanceof #7// String
13String s = (String) o;
7aload_0 // o
8checkcast #7// String
11astore_1 // s
14return s.length();
12aload_1 // s
13invokevirtual #13// String.length() : int
16return -1;

Open in the viewer

static String cast(Object o) in Tour, compiled by javac 25
96if (o == null) throw new IllegalArgumentException("null");
0aload_0 // o
4new #57// IllegalArgumentException
7dup
8ldc #59// "null"
10invokespecial #61// new IllegalArgumentException(String)
97if (!(o instanceof CharSequence)) return null;
14aload_0 // o
15instanceof #64// CharSequence
98return (String) o;
23aload_0 // o
24checkcast #16// String

Open in the viewer

Related instructions

checkcast Checks that the reference on top of the stack is of a type (throws ClassCastException if not).ifeq Pops an int; jumps if it is equal to zero.

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