What javac does with everyday Java code
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Much of what you write in Java is shorthand that javac expands into more bytecode: a method call becomes one of several invoke instructions, list.add(78) hides a call to Integer.valueOf, and + on strings and lambdas both become invokedynamic. javap -c shows the hidden work.
Method calls: four invoke instructions
javac picks the invoke instruction from how a method is declared and called. invokestatic calls a static method; no object is needed. invokevirtual calls an instance method through a class type, and the JVM picks the override from the object's real class at run time.
Example 1 · Calls of every kind
interface Payment { String pay(int amount);}
class UpiPayment implements Payment { public String pay(int amount) { return "UPI Rs " + amount; }}
class CashbackUpi extends UpiPayment { public String pay(int amount) { return super.pay(amount) + " + Rs 10 cashback"; // the parent's version }}
public class InvokeDemo { private int count;
static int gst(int amount) { return amount * 18 / 100; }
private void addOne() { count++; }
void run() { UpiPayment upi = new UpiPayment(); Payment p = upi;
int tax = gst(500); String a = upi.pay(500); // through a class type String b = p.pay(500); // through an interface type addOne();
System.out.println(tax + ", " + a + ", " + b + ", count " + count); System.out.println(new CashbackUpi().pay(500)); }
public static void main(String[] args) { new InvokeDemo().run(); }}90, UPI Rs 500, UPI Rs 500, count 1 UPI Rs 500 + Rs 10 cashback
What this code does
run()makes a static call (gst), a call through the class typeUpiPayment, a call through the interface typePayment, a private call (addOne) and a constructor call.CashbackUpi.paycalls its parent'spaywithsuper.- Both
aandbcall the same method on the same object, so they print the same text. Only the bytecode differs, as the next example shows.
Example 2 · javap: which invoke for which call
javac --release 17 InvokeDemo.javajavap -c InvokeDemojavap -c CashbackUpi void run();
Code:
0: new #13 // class UpiPayment
3: dup
4: invokespecial #15 // Method UpiPayment."<init>":()V
7: astore_1
8: aload_1
9: astore_2
10: sipush 500
13: invokestatic #16 // Method gst:(I)I
16: istore_3
17: aload_1
18: sipush 500
21: invokevirtual #20 // Method UpiPayment.pay:(I)Ljava/lang/String;
24: astore 4
26: aload_2
27: sipush 500
30: invokeinterface #24, 2 // InterfaceMethod Payment.pay:(I)Ljava/lang/String;
35: astore 5
37: aload_0
38: invokevirtual #27 // Method addOne:()V
41: getstatic #30 // Field java/lang/System.out:Ljava/io/PrintStream;
44: iload_3
45: aload 4
47: aload 5
49: aload_0
50: getfield #7 // Field count:I
53: invokedynamic #36, 0 // InvokeDynamic #0:makeConcatWithConstants:(ILjava/lang/String;Ljava/lang/String;I)Ljava/lang/String;
58: invokevirtual #40 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
61: getstatic #30 // Field java/lang/System.out:Ljava/io/PrintStream;
64: new #46 // class CashbackUpi
67: dup
68: invokespecial #48 // Method CashbackUpi."<init>":()V
71: sipush 500
74: invokevirtual #49 // Method CashbackUpi.pay:(I)Ljava/lang/String;
77: invokevirtual #40 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
80: return
$ javap -c CashbackUpi
...
public java.lang.String pay(int);
Code:
0: aload_0
1: iload_1
2: invokespecial #7 // Method UpiPayment.pay:(I)Ljava/lang/String;
5: invokedynamic #11, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
10: areturnWhat this code does
new+dup+invokespecial <init>is how everynew UpiPayment()looks.gstisinvokestatic,upi.payisinvokevirtual,p.payisinvokeinterface(the, 2counts the argument slots, including the object), and privateaddOneisinvokevirtualbecause the class targets Java 17.- In
CashbackUpi.pay,super.pay(amount)isinvokespecial UpiPayment.pay: it must run exactly the parent's version, not the override inCashbackUpi. Compiled with--release 8, the call toaddOnewould beinvokespecialtoo.
invokeinterface does the same through an interface type. invokespecial calls one exact method with no override lookup: constructors (<init>) and super.method() calls. Before Java 11, javac also used it for private methods. Since Java 11, classes compiled for 11 or later call private methods with invokevirtual (or invokeinterface inside an interface), as part of a feature called nestmates.
A fifth one, invokedynamic, does not name a target method at all. The first time it runs, a bootstrap method builds the target and links it, and later runs reuse that link. javac uses it for string + and for lambdas.
Autoboxing becomes valueOf and intValue
Autoboxing is the automatic conversion between a primitive such as int and its wrapper class such as Integer. It is a compiler feature: javac inserts Integer.valueOf(x) to box and x.intValue() to unbox. Collections need boxing, because List<Integer> stores objects, never raw ints.
static int total(List<Integer> marks) { int sum = 0; for (int m : marks) { // each m is unboxed sum += m; } return sum;}
// in main:List<Integer> marks = new ArrayList<>();marks.add(78); // 78 is boxed into an Integermarks.add(91);int first = marks.get(0); // unboxed back to intSystem.out.println(first + " " + total(marks));The hidden calls have three effects. Boxing can create objects (valueOf caches only -128 to 127 by default). Comparing two Integer objects with == compares references, not numbers. And unboxing null calls intValue() on null, which throws NullPointerException on a line that looks like simple arithmetic.
Example 3 · Boxing calls hidden in a list of marks
javac --release 17 BoxingDemo.javajavap -c BoxingDemo static int total(java.util.List<java.lang.Integer>);
Code:
0: iconst_0
1: istore_1
2: aload_0
3: invokeinterface #7, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
8: astore_2
9: aload_2
10: invokeinterface #13, 1 // InterfaceMethod java/util/Iterator.hasNext:()Z
15: ifeq 38
18: aload_2
19: invokeinterface #19, 1 // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
24: checkcast #23 // class java/lang/Integer
27: invokevirtual #25 // Method java/lang/Integer.intValue:()I
30: istore_3
31: iload_1
32: iload_3
33: iadd
34: istore_1
35: goto 9
38: iload_1
39: ireturn
public static void main(java.lang.String[]);
Code:
0: new #29 // class java/util/ArrayList
3: dup
4: invokespecial #31 // Method java/util/ArrayList."<init>":()V
7: astore_1
8: aload_1
9: bipush 78
11: invokestatic #32 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
14: invokeinterface #36, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
19: pop
20: aload_1
21: bipush 91
23: invokestatic #32 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
26: invokeinterface #36, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
31: pop
32: aload_1
33: iconst_0
34: invokeinterface #40, 2 // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
39: checkcast #23 // class java/lang/Integer
42: invokevirtual #25 // Method java/lang/Integer.intValue:()I
45: istore_2
46: getstatic #44 // Field java/lang/System.out:Ljava/io/PrintStream;
49: iload_2
50: aload_1
51: invokestatic #50 // Method total:(Ljava/util/List;)I
54: invokedynamic #56, 0 // InvokeDynamic #0:makeConcatWithConstants:(II)Ljava/lang/String;
59: invokevirtual #60 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
62: returnWhat this code does
marks.add(78)isbipush 78,invokestatic Integer.valueOf,invokeinterface List.add, and apopthat throws away thebooleanthataddreturns.marks.get(0)isList.get,checkcast Integerandinvokevirtual intValue.- In
total, the for-each loop over aListbecameiterator(),hasNext()andnext(), each throughinvokeinterface, and every element is unboxed withintValue()beforeiadd. The program prints78 169.
Example 4 · The Integer cache and unboxing null
public class CacheDemo { public static void main(String[] args) { Integer a = 127; // Integer.valueOf(127) Integer b = 127; Integer c = 128; // Integer.valueOf(128) Integer d = 128;
System.out.println("127 == 127: " + (a == b)); System.out.println("128 == 128: " + (c == d)); System.out.println("128 equals 128: " + c.equals(d)); System.out.println("unboxed 128 == 128: " + (c.intValue() == d.intValue()));
Integer missing = null; try { int marks = missing; // missing.intValue() System.out.println(marks); } catch (NullPointerException e) { System.out.println("Unboxing null: NullPointerException"); } }}127 == 127: true 128 == 128: false 128 equals 128: true unboxed 128 == 128: true Unboxing null: NullPointerException
What this code does
Integer.valueOfreturns cached objects for -128 to 127, so both 127s are the same object and==is true. 128 is outside the default cache, so eachvalueOf(128)makes a new object and==compares two different references.- Compare wrapper values with
equalsor unbox first.int marks = missing;compiles tomissing.intValue(), which throwsNullPointerExceptionwhenmissingisnull. The cache's upper limit can be raised with a HotSpot option, so never rely on==for wrappers.
Predict the output
What javac adds for boxing
Pick the call the Java compiler writes for you.
Round 1 of 3
Line 1 stores an int in an Integer.
String concatenation with invokedynamic
Since Java 9, name + " - coach S" + coach compiles to a single invokedynamic that calls makeConcatWithConstants from java.lang.invoke.StringConcatFactory. The bytecode only pushes the variable parts; the constant text is stored as a recipe in the class file.
static String ticket(String name, int coach, int seat) { return name + " - coach S" + coach + ", seat " + seat;}
static String slowJoin(String[] names) { String all = ""; for (String n : names) { all = all + n + " "; } return all.trim();}Example 5 · Concatenation in Java 17 and Java 8 bytecode
javac --release 17 ConcatDemo.javajavap -c ConcatDemojavac --release 8 ConcatDemo.javajavap -c ConcatDemo$ javac --release 17 ConcatDemo.java && javap -c ConcatDemo
static java.lang.String ticket(java.lang.String, int, int);
Code:
0: aload_0
1: iload_1
2: iload_2
3: invokedynamic #7, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;II)Ljava/lang/String;
8: areturn
static java.lang.String slowJoin(java.lang.String[]);
Code:
0: ldc #11 // String
2: astore_1
3: aload_0
4: astore_2
5: aload_2
6: arraylength
7: istore_3
8: iconst_0
9: istore 4
11: iload 4
13: iload_3
14: if_icmpge 38
17: aload_2
18: iload 4
20: aaload
21: astore 5
23: aload_1
24: aload 5
26: invokedynamic #13, 0 // InvokeDynamic #1:makeConcatWithConstants:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
31: astore_1
32: iinc 4, 1
35: goto 11
38: aload_1
39: invokevirtual #16 // Method java/lang/String.trim:()Ljava/lang/String;
42: areturn
$ javac --release 8 ConcatDemo.java && javap -c ConcatDemo
static java.lang.String ticket(java.lang.String, int, int);
Code:
0: new #7 // class java/lang/StringBuilder
3: dup
4: invokespecial #9 // Method java/lang/StringBuilder."<init>":()V
7: aload_0
8: invokevirtual #10 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: ldc #14 // String - coach S
13: invokevirtual #10 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
16: iload_1
17: invokevirtual #16 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
20: ldc #19 // String , seat
22: invokevirtual #10 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
25: iload_2
26: invokevirtual #16 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
29: invokevirtual #21 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
32: areturnWhat this code does
- With
--release 17, all ofticketis three loads and oneinvokedynamic; its descriptor(Ljava/lang/String;II)Ljava/lang/String;lists just the three variable parts. With--release 8, the same line is aStringBuilderwith fourappendcalls. The program printsKabir - coach S4, seat 32either way. - In
slowJoin, theinvokedynamicsits inside the loop (offsets 11 to 35), so every pass builds a newStringfromallandn. That is the hidden cost aStringBuildercreated once before the loop avoids.
The JVM then picks a fast way to build the string at run time. Up to Java 8, javac wrote a new StringBuilder() followed by one append call per part and a final toString(). Code compiled with --release 8 still looks like that, even on a new JDK.
Neither way helps inside a loop. all = all + n + " " builds a brand-new String on every pass, copying everything so far, so the work grows with the square of the number of names. Use one StringBuilder across the loop instead.
Enhanced for loops and lambdas in bytecode
The enhanced for loop (for (int m : marks)) has no instruction of its own. Over an array, javac writes a normal index loop with arraylength, iaload and hidden locals for the array copy, the length and the index.
static int countPassed(int[] marks, IntPredicate passed) { int count = 0; for (int m : marks) { if (passed.test(m)) { count++; } } return count;}
// in main:int cutoff = 40;IntPredicate passed = m -> m >= cutoff;System.out.println("Passed: " + countPassed(marks, passed));names.forEach(System.out::println);Example 6 · A for-each over an array and a lambda
javac --release 17 LambdaDemo.javajavap -c -p LambdaDemo static int countPassed(int[], java.util.function.IntPredicate);
Code:
0: iconst_0
1: istore_2
2: aload_0
3: astore_3
4: aload_3
5: arraylength
6: istore 4
8: iconst_0
9: istore 5
11: iload 5
13: iload 4
15: if_icmpge 44
18: aload_3
19: iload 5
21: iaload
22: istore 6
24: aload_1
25: iload 6
27: invokeinterface #7, 2 // InterfaceMethod java/util/function/IntPredicate.test:(I)Z
32: ifeq 38
35: iinc 2, 1
38: iinc 5, 1
41: goto 11
44: iload_2
45: ireturn
public static void main(java.lang.String[]);
Code:
... // offsets 0-28 build the marks array
29: bipush 40
31: istore_2
32: iload_2
33: invokedynamic #13, 0 // InvokeDynamic #0:test:(I)Ljava/util/function/IntPredicate;
38: astore_3
39: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
42: aload_1
43: aload_3
44: invokestatic #22 // Method countPassed:([ILjava/util/function/IntPredicate;)I
47: invokedynamic #28, 0 // InvokeDynamic #1:makeConcatWithConstants:(I)Ljava/lang/String;
52: invokevirtual #32 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
55: ldc #38 // String Asha
57: ldc #40 // String Ravi
59: invokestatic #42 // InterfaceMethod java/util/List.of:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/List;
62: astore 4
64: aload 4
66: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
69: dup
70: invokestatic #48 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
73: pop
74: invokedynamic #54, 0 // InvokeDynamic #2:accept:(Ljava/io/PrintStream;)Ljava/util/function/Consumer;
79: invokeinterface #58, 2 // InterfaceMethod java/util/List.forEach:(Ljava/util/function/Consumer;)V
84: return
private static boolean lambda$main$0(int, int);
Code:
0: iload_1
1: iload_0
2: if_icmplt 9
5: iconst_1
6: goto 10
9: iconst_0
10: ireturnWhat this code does
countPassed: the for-each overint[]became a copy of the array (slot 3), its length (slot 4), an index (slot 5) andiaload, withif_icmpgeandgotoaround it.passed.test(m)isinvokeinterface IntPredicate.test.- In
main,iload_2pushescutoffandinvokedynamic ... test:(I)Ljava/util/function/IntPredicate;builds the lambda object around it. The body sits inlambda$main$0(int, int): the capturedcutoffis parameter 0 andmis parameter 1.System.out::printlnbecomesinvokedynamic ... acceptwith no extra method; theObjects.requireNonNullcall checks thatSystem.outis not null.
Over a List or any Iterable, it calls iterator(), then hasNext() and next() through invokeinterface, plus a checkcast and unboxing for List<Integer>.
A lambda becomes two things. Its body moves into a private static method named like lambda$main$0, and captured local variables become its first parameters. At the place where the lambda is created, an invokedynamic asks LambdaMetafactory to build an object that implements the interface. A method reference such as System.out::println usually needs no extra method at all.
Next step
Check your understanding
11 quick questions