Confused about comparing string in this example

前端 未结 2 1894
广开言路
广开言路 2021-01-17 03:58

I know that \"==\" compare reference and the a java String is immutable and use a string pool cache but I\'m still confusing on this example :

 final String         


        
2条回答
  •  借酒劲吻你
    2021-01-17 04:06

    Since fName is final and initialized with a literal String, it's a constant expression.

    So the instruction

    String name2 = fName + "Gosling"
    

    is compiled to

    String name2 = "James" + "Gosling"
    

    which is compiled to

    String name2 = "JamesGosling"
    

    So, in the bytecode, you have the equivalent of

    String name2 = "JamesGosling";
    String name3 = "JamesGosling";
    

    So both name2 and name3 reference the same literal String, which is interned.

    On the other hand, lName is not final, and is thus not a constant expression, and the concatenation happens at runtime rather than at compile time. So the concatenation creates a new, non-interned String.

提交回复
热议问题