Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final String vs final Integer

Tags:

java

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 ?

like image 717
invariant Avatar asked Dec 07 '22 10:12

invariant


1 Answers

Speculation: reason is string interning. The compiler interns strings and has optimization for concatenation of interned strings. But it does not intern Numbers, and apparently lacks the optimization.

I can't think of any reason why it couldn't optimize the Integer case, other than it just hasn't been implemented in compiler. As mentioned in other answers, Integer + involves boxing / unboxing operations, quite different from string + and its implicit StringBuilder optimizations and interning logic. So String + optimization probably comes "for free" from compiler implementation point if view.

like image 92
hyde Avatar answered Dec 24 '22 08:12

hyde