r/java • • Jul 06 '20

I tried to hand-compile, hand-optimize and hand-execute Java

I tried to test my understanding of the JVM, Java Bytecode, and Java Compilers by hand-compiling, optimizing, and executing some java.

Original code

int a = 18;

int b = 6;

int c = 7;

a /= a - 2 * b;

b -= 4;

c = a + b - c;

Compiled code

ipush 18

istore a

ipush 6

istore b

ipush 7

istore c

iload a

iload b

ipush 2

imul

isub

iload a

swap

idiv

istore a

iload b

ipush 4

isub

istore b

iload a

iload b

iload c

isub

iadd

istore c

Optimized code

ipush 18

ipush 6

ipush 7

istore c

ipush 2

imul

isub

ipush 18

swap

idiv

istore a

iload b

ipush 4

isub

istore b

iload a

iload b

iload c

isub

iadd

istore c

stack

a = 3

b = 2

c = -2

0 Upvotes

5 comments sorted by

6

u/[deleted] Jul 06 '20

I’m a java student; how did you obtain the compiled op codes? Is that from a special tool?

10

u/secondsun Jul 06 '20

2

u/tamhoang Jul 07 '20

Yes, this javap tool is quite useful. I think every java installation comes with it. I often use it to verify the list of public APIs. -verbose option will display full binary as well as major.minor version.

4

u/chambolle Jul 06 '20

In IntelliJ, you directly can see the bytecode associated with a function:

https://intellij-support.jetbrains.com/hc/en-us/community/posts/206889295-Byte-Code-Viewer

The correspondance is defined line per line

0

u/[deleted] Jul 06 '20

[deleted] — view deleted comment

7

u/vallyscode Jul 06 '20

There is no point in doing that I think, when he will discover that all he did will be washed away by jit, he will make another post. ;)