Bytecode practice: compile, inspect and trace
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Reading bytecode comes down to a few moves you repeat: compile with a known target, disassemble with the right javap options, match instructions to source lines, trace values through the stack, and recognise the calls javac adds for you.
Skill 1: compile, inspect and compare
Compile with a known target first: javac --release 17 (add -g if you want local variable names). Then disassemble with javap -c -p, and check the version with javap -v when deployment is involved.
static int percent(int attended, int total) { return attended * 100 / total;}
static boolean isShort(int attended, int total) { return percent(attended, total) < 75;}Example 1 · Inspect a method and the call to it
javac --release 17 Attendance.javajavap -c Attendance static int percent(int, int);
Code:
0: iload_0
1: bipush 100
3: imul
4: iload_1
5: idiv
6: ireturn
static boolean isShort(int, int);
Code:
0: iload_0
1: iload_1
2: invokestatic #7 // Method percent:(II)I
5: bipush 75
7: if_icmpge 14
10: iconst_1
11: goto 15
14: iconst_0
15: ireturnWhat this code does
percent: loadattended, push 100 withbipush,imul, loadtotal,idiv. The order matchesattended * 100 / total, left to right, because*and/have the same precedence.isShortloads both arguments, callsinvokestatic percent:(II)I, and compares the result with 75. javac tests the opposite (if_icmpge 14) to jump toiconst_0(false); falling through pushesiconst_1(true).percent(42, 60)is 70, so the program prints70% short: true.
The same source can give different bytecode for different targets, so always say which target you used.
Then match each block of instructions to a source line. Arguments are loaded first, the operation follows, the result is stored or returned. A call to your own method shows up as an invoke with the method's name and descriptor, so isShort calling percent is easy to find.
Skill 2: trace arithmetic and loops
To trace a method, write the local slots on one line and the operand stack on another, then apply one instruction at a time. Arithmetic pops two and pushes one; the value on top is the right operand.
static int countAbove(int[] marks, int cutoff) { int count = 0; for (int i = 0; i < marks.length; i++) { if (marks[i] >= cutoff) { count++; } } return count;}For loops, first find the shape: a test that jumps out (if_icmpge for i < n), the body, an iinc and a goto back to the test. Then trace only one or two passes; the rest repeat. Count how often each part runs: the test runs once more than the body.
Example 2 · A counting loop to trace
javap -c Attendance static int countAbove(int[], int);
Code:
0: iconst_0
1: istore_2
2: iconst_0
3: istore_3
4: iload_3
5: aload_0
6: arraylength
7: if_icmpge 26
10: aload_0
11: iload_3
12: iaload
13: iload_1
14: if_icmplt 20
17: iinc 2, 1
20: iinc 3, 1
23: goto 4
26: iload_2
27: ireturnWhat this code does
- Slots:
marks0,cutoff1,count2,i3. Offsets 4 to 7 are the loop testi < marks.length(witharraylength);ialoadat 12 readsmarks[i];if_icmplt 20skipscount++whenmarks[i] < cutoff. - For
{35, 72, 40, 18, 90}with cutoff 40, the body runs 5 times, the test 6 times,iinc 3, 1(i++) 5 times andiinc 2, 1(count++) 3 times, for 72, 40 and 90. The method returns 3.
Skill 3: spot boxing and string concatenation
Boxing shows up as invokestatic Integer.valueOf and unboxing as checkcast Integer followed by invokevirtual intValue. A single source line such as votes.put(name, votes.getOrDefault(name, 0) + 1) hides both, plus Map calls through invokeinterface.
Example 3 · Hidden boxing and concatenation in a vote counter
javac --release 17 VoteCount.javajavap -c VoteCount static java.util.Map<java.lang.String, java.lang.Integer> count(java.util.List<java.lang.String>);
Code:
0: new #7 // class java/util/TreeMap
3: dup
4: invokespecial #9 // Method java/util/TreeMap."<init>":()V
7: astore_1
8: aload_0
9: invokeinterface #10, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
14: astore_2
15: aload_2
16: invokeinterface #16, 1 // InterfaceMethod java/util/Iterator.hasNext:()Z
21: ifeq 67
24: aload_2
25: invokeinterface #22, 1 // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
30: checkcast #26 // class java/lang/String
33: astore_3
34: aload_1
35: aload_3
36: aload_1
37: aload_3
38: iconst_0
39: invokestatic #28 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
42: invokeinterface #34, 3 // InterfaceMethod java/util/Map.getOrDefault:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
47: checkcast #29 // class java/lang/Integer
50: invokevirtual #40 // Method java/lang/Integer.intValue:()I
53: iconst_1
54: iadd
55: invokestatic #28 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
58: invokeinterface #44, 3 // InterfaceMethod java/util/Map.put:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
63: pop
64: goto 15
67: aload_1
68: areturn
static java.lang.String report(java.util.Map<java.lang.String, java.lang.Integer>);
Code:
0: ldc #47 // String
2: astore_1
3: aload_0
4: invokeinterface #49, 1 // InterfaceMethod java/util/Map.keySet:()Ljava/util/Set;
9: invokeinterface #53, 1 // InterfaceMethod java/util/Set.iterator:()Ljava/util/Iterator;
14: astore_2
15: aload_2
16: invokeinterface #16, 1 // InterfaceMethod java/util/Iterator.hasNext:()Z
21: ifeq 55
24: aload_2
25: invokeinterface #22, 1 // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
30: checkcast #26 // class java/lang/String
33: astore_3
34: aload_1
35: aload_3
36: aload_0
37: aload_3
38: invokeinterface #56, 2 // InterfaceMethod java/util/Map.get:(Ljava/lang/Object;)Ljava/lang/Object;
43: invokestatic #60 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
46: invokedynamic #63, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
51: astore_1
52: goto 15
55: aload_1
56: invokevirtual #67 // Method java/lang/String.trim:()Ljava/lang/String;
59: areturnWhat this code does
- In
count, one source line becomes offsets 34 to 63:Integer.valueOf(0)boxes the default,getOrDefaultis called,checkcastandintValueunbox the result,iaddadds 1,valueOfboxes again, andputstores it. That is three hidden calls per ballot. - In
report,text += ...puts aninvokedynamicinside the loop (offset 46), so every name builds a newString.votes.get(name)is passed throughString.valueOf(Object), not unboxed. The program printsAsha=3 Meena=1 Ravi=2.
String concatenation shows up as invokedynamic makeConcatWithConstants on Java 9+ targets. Inside a loop that grows one string (text += ...), it means a new String every pass. When an Integer is concatenated, javac calls String.valueOf(Object) instead of unboxing, so null prints as null rather than throwing.
Skill 4: explain class file version errors
An UnsupportedClassVersionError names two class file versions: the class's version and the highest the JVM accepts. Subtract 44 from each to get Java releases (65 → Java 21, 61 → Java 17, 55 → Java 11, 52 → Java 8).
Example 4 · Turn version errors into advice
import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;
public class VersionErrorDemo { static final Pattern VERSIONS = Pattern.compile("class file version (\\d+)\\.0\\).*up to (\\d+)\\.0");
static String explain(String message) { Matcher m = VERSIONS.matcher(message); if (!m.find()) { return "Not a class file version error"; } int classJava = Integer.parseInt(m.group(1)) - 44; int jvmJava = Integer.parseInt(m.group(2)) - 44; return "Compiled for Java " + classJava + ", running on Java " + jvmJava + ". Fix: javac --release " + jvmJava + ", or run on Java " + classJava + " or newer."; }
public static void main(String[] args) { List<String> errors = List.of( "ResultServer has been compiled by a more recent version of the Java Runtime " + "(class file version 65.0), this version of the Java Runtime only " + "recognizes class file versions up to 61.0", "ErpBatch has been compiled by a more recent version of the Java Runtime " + "(class file version 61.0), this version of the Java Runtime only " + "recognizes class file versions up to 55.0", "Exception in thread \"main\" java.lang.NoSuchMethodError: 'java.util.List java.util.List.reversed()'"); for (String e : errors) { System.out.println(explain(e)); } }}Compiled for Java 21, running on Java 17. Fix: javac --release 17, or run on Java 21 or newer. Compiled for Java 17, running on Java 11. Fix: javac --release 11, or run on Java 17 or newer. Not a class file version error
What this code does
- The regular expression captures the two numbers from the standard
UnsupportedClassVersionErrormessage; subtracting 44 turns them into Java releases. - The third message is a
NoSuchMethodError, not a version error: the class loaded fine, butList.reversed()does not exist on that JVM. Its fix is to compile with--releasefor the older Java, so javac reports the missing method at compile time.
Then the fix is one of two: rebuild with javac --release <server's Java>, or run on a newer JVM.
A different error, NoSuchMethodError for a JDK method, usually means the code was compiled against a newer JDK with -target but without --release, and then run on an older JVM. The class version is fine, but a method it calls does not exist there.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
A javap -v header shows major version: 55 and flags: (0x0021) ACC_PUBLIC, ACC_SUPER. Answer in two lines: the oldest Java that can run it, and whether the class is public.
Java 11 Yes, the class is public (ACC_PUBLIC)
Exercise 2· Easy
Write the bytecode for static int twice(int x) { return x * 2; }, one instruction per line, without offsets.
iload_0 iconst_2 imul ireturn
Exercise 3· Medium
Trace static int f(int a, int b) { return (a + b) * (a - b); } for f(7, 3). Its bytecode is iload_0, iload_1, iadd, iload_0, iload_1, isub, imul, ireturn. Write each instruction and the stack after it.
iload_0 [7] iload_1 [7, 3] iadd [10] iload_0 [10, 7] iload_1 [10, 7, 3] isub [10, 4] imul [40] ireturn returns 40
Exercise 4· Medium
Use the countAbove bytecode from Example 2 with marks = {55, 30, 80, 41} and cutoff = 50. Count how many times each runs, one per line: the loop test if_icmpge, iaload, iinc 2, 1 (count++), iinc 3, 1 (i++). Then the return value.
if_icmpge: 5 iaload: 4 iinc 2, 1: 2 iinc 3, 1: 4 returns: 2
Exercise 5· Medium
This excerpt comes from one source line inside a loop. Write that source line (the map is votes, the loop variable is name), then name the three hidden method calls javac added.
34: aload_135: aload_336: aload_137: aload_338: iconst_039: invokestatic #28 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;42: invokeinterface #34, 3 // InterfaceMethod java/util/Map.getOrDefault:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;47: checkcast #29 // class java/lang/Integer50: invokevirtual #40 // Method java/lang/Integer.intValue:()I53: iconst_154: iadd55: invokestatic #28 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;58: invokeinterface #44, 3 // InterfaceMethod java/util/Map.put:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;63: popvotes.put(name, votes.getOrDefault(name, 0) + 1); Integer.valueOf (boxing the 0) intValue (unboxing the result of getOrDefault) Integer.valueOf (boxing the new count)
Exercise 6· Medium
Rewrite report from Example 3 with one StringBuilder and entrySet(), so there is no invokedynamic inside the loop. Print the report for Asha=3, Meena=1, Ravi=2 (in a TreeMap) and for an empty map inside brackets.
Asha=3 Meena=1 Ravi=2 []
Exercise 7· Hard
The college election app says the president poll is not a tie, although both candidates have 200 votes. Fix isTie so both lines print true, and keep the Map<String, Integer>.
import java.util.HashMap;import java.util.Map;
public class TieCheck { static boolean isTie(Map<String, Integer> votes, String a, String b) { return votes.get(a) == votes.get(b); }
public static void main(String[] args) { Map<String, Integer> classRep = new HashMap<>(); classRep.put("Asha", 45); classRep.put("Ravi", 45);
Map<String, Integer> presidentPoll = new HashMap<>(); presidentPoll.put("Meena", 200); presidentPoll.put("Kabir", 200);
System.out.println("Class rep tie: " + isTie(classRep, "Asha", "Ravi")); System.out.println("President tie: " + isTie(presidentPoll, "Meena", "Kabir")); }}Class rep tie: true President tie: true
Exercise 8· Hard
Before deploying a college ERP to a Java 17 server, check four JARs by the major version of their classes: erp-core.jar 61, pdf-export.jar 55, sms-alerts.jar 65, old-reports.jar 52. Write DeployCheck that prints each JAR, its version, the Java it needs and OK or UnsupportedClassVersionError, then how many JARs must be rebuilt.
erp-core.jar major 61 = Java 17 OK pdf-export.jar major 55 = Java 11 OK sms-alerts.jar major 65 = Java 21 UnsupportedClassVersionError old-reports.jar major 52 = Java 8 OK 1 jar(s) must be rebuilt with --release 17
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of From Source to Bytecode
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: What class loading means