my java class
private static final String constantString = "Constant";
private static final Integer constantInteger = 5;
public static void main(String[] args) {
String s2 = constantString + "append"; // LINENUMBER 9
Integer i2 = constantInteger + 7; // LINENUMBER 10
}
Byte code
LINENUMBER 9 L0
LDC "Constantappend"
ASTORE 1
L1
LINENUMBER 10 L1
GETSTATIC TestClass.constantInteger : Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue()I
BIPUSH 7
IADD
Question No1 : Why compiler not replacing final Integer (constantInteger) value with 5,but for String it did!
if remove final keyword for Integer variable
java code :
private static Integer constantInteger = 5;
byte code :
LINENUMBER 10 L1
GETSTATIC TestClass.constantInteger : Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue()I
BIPUSH 7
the byte code is same in two different cases (static final Integer , static Integer)
Question No 2 : Then What is the use of making Integer final ?
The compiler does not bother to notice that a final Integer with a non-null value is, necessarily, non-null. So it goes ahead and unboxes it. It is entirely possible that the JIT compiler will improve this on the way to machine code; it seems pretty unlikely either way that this is a real problem for the performance of your application.
‘final’ is about semantics, not performance. The language guarantees the semantics; the performance is entirely at the whim of implementors. So, to answer ‘question #2’ explicitly: the point of final is to have the semantics of preventing modification. Also note the rules for embedded anonymous classes, where they may only use final local variables.