使用Javap分析Java代碼裏的static final的工作原理

Created by Jerry Wang, last modified on Oct 05, 2016

I have written the following test code:

I would like to test the difference with “static int” and “static final int”.
Use javap to decompile .class file:

The result is listed below:

According to JVM instruction list explanation in wiki: https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
sipush 545: push int value 545 to stack
putstatic #16: put the stack value 545 to static class field number3

aload_0: load a reference onto the stack from local variable 0
invokespecial: invoke instance method on object objectref and puts the result on the stack (might be void); the method is identified by method reference index in constant pool
ldc: push a constant #index from a constant pool (String, int or float) onto the stack
Here we can know the fact that the value of result 512 * 623 has already been calculated during compilation and stored in constant pool index #29.
istore_1: store int value into variable 1
getstatic: get a static field value of a class, where the field is identified by field reference in the constant pool index
imul: multiply two integers
new: create new object of type identified by class reference in constant pool index
dup: duplicate the value on top of the stack

You might wonder how we can know each # represents. In order to get the table you can use javap -v instead:


We can also know that the "Value: " + product1 + " , " + product2 is coverted automatically by JVM to create a new StringBuilder instance and call append method to achieve string concatenation.

要獲取更多Jerry的原創文章,請關注公衆號"汪子熙":

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章