HexplainedJavaThread dumpsHeap dumpsAbout
ViewerFormatWhat javac doesOpcodesConstantsAttributesVersionsJAR
Java class files › What javac does › Compile-time constants

What javac does

Compile-time constants

Copied into the code that uses them, so they are never read at run time.

A static final field initialised with a compile-time constant is not read at run time at all. javac copies its value into the code that uses it, and records it in a ConstantValue attribute on the field.

The source

// Compile-time constants: copied into the code that uses them, so getstatic never happens.
public class Constants {
    static final int LIMIT = 1000;
    static final String NAME = "limit";
    static final long BIG = 1L << 40;
    static final int COMPUTED = Integer.parseInt("7");

    static int check(int n) {
        if (n > LIMIT) {
            System.out.println(NAME + " exceeded");
            return COMPUTED;
        }
        return (int) (BIG >> 38);
    }
}

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

What to look for

  • n > LIMIT compiles to sipush 1000: there is no getstatic.
  • NAME + " exceeded" is folded into one String constant, "limit exceeded".
  • (int) (BIG >> 38) is folded too: the method returns iconst_4.
  • COMPUTED is set by a method call, so it is not a constant: it gets a real getstatic, and a putstatic in the static initialiser.
  • The catch: another class that uses LIMIT keeps the copied value until it is recompiled, even after you change it here.

Constants.class

static int check(int n)

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

9if (n > LIMIT) {
0iload_0 // n
1sipush 1000
4if_icmple 19
10System.out.println(NAME + " exceeded");
7getstatic #9// System.out : PrintStream
10ldc #15// "limit exceeded"
12invokevirtual #17// PrintStream.println(String) : void
11return COMPUTED;
15getstatic #23// Constants.COMPUTED : int
18ireturn
13return (int) (BIG >> 38);
19iconst_4
20ireturn

Open in the viewer

static { … }

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

6static final int COMPUTED = Integer.parseInt("7");
0ldc #27// "7"
2invokestatic #29// Integer.parseInt(String) : int
5putstatic #23// Constants.COMPUTED : int
8return

Open in the viewer

← Pattern-matching switchAll topicsassert →

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.