Confused about comparing string in this example

前端 未结 2 1910
广开言路
广开言路 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:27

    Creating two strings with same string values does not guarantee they are both from the String Pool. You need to call s.intern() to ensure you get a String that has both same value and memory address from String Pool.

    There is a good chance the concatenation is causing the String to be read as String Object instead of a String literal. This is due to the compiler not knowing if fName + lName will result to a literal or not. If it's a String literal, it goes to the String Pool. If it's a String Object, it is is not guaranteed to go to the String Pool and be treated like any other Object.

提交回复
热议问题