I was reading this wiki article on how some code is translated to Java bytecode
.
I came across this example:
Consider the following Java code:
outer:
for (int i = 2; i < 1000; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
continue outer;
}
System.out.println (i);
}
A Java compiler might translate the Java code above into byte code as follows,
assuming the above was put in a method:
0: iconst_2
1: istore_1
2: iload_1
3: sipush 1000
6: if_icmpge 44
9: iconst_2
10: istore_2
11: iload_2
12: iload_1
13: if_icmpge 31
16: iload_1
17: iload_2
18: irem
19: ifne 25
22: goto 38
25: iinc 2, 1
28: goto 11
31: getstatic #84; //Field java/lang/System.out:Ljava/io/PrintStream;
34: iload_1
35: invokevirtual #85; //Method java/io/PrintStream.println:(I)V
38: iinc 1, 1
41: goto 2
44: return
- I do not understand a single line of the
bytecode.
I want to understand some part of it if not all. or what some of these lines mean such asiconst_2
? - is
bytecode
and.class
file same or.class
files containsbytecode?
. The picture below shows both.class
andbytecode
are same - If they are different, how is
bytecode
extracted from.class
files by theJVM
?
some of the posts in SO talk about bytecode
in general, but I do not see any post that explains the relationship between class
and bytecode
if any and how to read bytecode
contents as a user (not as a JVM).
Sometimes I find there is an assumption it has to be terribly complication when it is not. It is actually very simple.
iconst_2
stands for the integer constant 2The .class contains more than byte code. It also contains some constants e.g. String literals and large primitives. However, you can treat them as one and the same.
The diagram is a simplified view. In simple terms they are the same thing.
A .class has a specific format which if you follow that format you will find the byte code. As you can see there is more than just byte code in the file, but the byte code is the only bit you should care about. (Actually you shouldn't really care about the byte code in 99% of cases)
From the Class file format linked above.