且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Javap分析Java代码里的static final的工作原理

更新时间:2022-09-10 19:23:19

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

I have written the following test code:使用Javap分析Java代码里的static final的工作原理I would like to test the difference with “static int” and “static final int”.

Use javap to decompile .class file:使用Javap分析Java代码里的static final的工作原理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


使用Javap分析Java代码里的static final的工作原理

使用Javap分析Java代码里的static final的工作原理You might wonder how we can know each # represents. In order to get the table you can use javap -v instead:使用Javap分析Java代码里的static final的工作原理使用Javap分析Java代码里的static final的工作原理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.