HexplainedJavaThread dumpsHeap dumpsAbout
ViewerFormatWhat javac doesOpcodesConstantsAttributesVersionsJAR
Java class files › What javac does › instanceof patterns

What javac does

instanceof patterns

No new instructions: the same instanceof, then a checkcast into a new local.

Pattern matching for instanceof (Java 16) adds no new instructions. o instanceof String s compiles to exactly what the old idiom does: an instanceof test, then a checkcast and a store into a new local variable.

The source

// min-release: 16
// instanceof with a pattern: the same instanceof, then a checkcast into a new local.
public class InstanceofPattern {
    static int length(Object o) {
        if (o instanceof String s && !s.isEmpty()) {
            return s.length();
        }
        return -1;
    }

    static int oldStyle(Object o) {
        if (o instanceof String) {
            String s = (String) o;
            return s.length();
        }
        return -1;
    }
}

Compiled by javac 25 with -g and --release 17 to 25. Where releases produce different bytecode, each version is shown.

What to look for

  • Compare length() with oldStyle(): the same instanceof, ifeq, checkcast and astore_1.
  • The checkcast cannot fail, but it is still needed: it gives the value the type String for the verifier and for the calls that follow.
  • && !s.isEmpty() is just another branch after the variable is bound.

InstanceofPattern.class

static int length(Object o)

javac --release 17 to 25 (the same bytecode for every release)

5if (o instanceof String s && !s.isEmpty()) {
0aload_0 // o
1instanceof #7// String
4ifeq 24
7aload_0 // o
8checkcast #7// String
11astore_1 // s
12aload_1 // s
13invokevirtual #9// String.isEmpty() : boolean
16ifne 24
6return s.length();
19aload_1 // s
20invokevirtual #13// String.length() : int
23ireturn
8return -1;
24iconst_m1
25ireturn

Open in the viewer

static int oldStyle(Object o)

javac --release 17 to 25 (the same bytecode for every release)

12if (o instanceof String) {
0aload_0 // o
1instanceof #7// String
4ifeq 17
13String s = (String) o;
7aload_0 // o
8checkcast #7// String
11astore_1 // s
14return s.length();
12aload_1 // s
13invokevirtual #13// String.length() : int
16ireturn
16return -1;
17iconst_m1
18ireturn

Open in the viewer

← for, while and do-whileAll topicsText blocks →

By the author of this site

Reading bytecode is half the story; running it is the other half. You execute exactly this kind of code in Build a JVM in Rust: Class files, an interpreter, objects and invokedynamic from scratch, on the real JDK class library.

Read Chapter 1 free

Java and the JVM are trademarks of Oracle; this site is not affiliated with Oracle. Field names follow the Java Virtual Machine Specification; the explanations are our own.

Sister sites: What's in my DB · LLM Anatomy · Distribution Atlas · Notation Decoder · uresk.net

Made by Spencer Uresk · About · Files you open stay on your device.