When should we use intern method of String on String literals

后端 未结 14 1068
生来不讨喜
生来不讨喜 2020-11-22 08:11

According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string

14条回答
  •  不知归路
    2020-11-22 08:46

    you should make out two period time which are compile time and runtime time.for example:

    //example 1 
    "test" == "test" // --> true 
    "test" == "te" + "st" // --> true
    
    //example 2 
    "test" == "!test".substring(1) // --> false
    "test" == "!test".substring(1).intern() // --> true
    

    in the one hand,in the example 1,we find the results are all return true,because in the compile time,the jvm will put the "test" to the pool of literal strings,if the jvm find "test" exists,then it will use the exists one,in example 1,the "test" strings are all point to the same memory address,so the example 1 will return true. in the other hand,in the example 2,the method of substring() execute in the runtime time, in the case of "test" == "!test".substring(1),the pool will create two string object,"test" and "!test",so they are different reference objects,so this case will return false,in the case of "test" == "!test".substring(1).intern(),the method of intern() will put the ""!test".substring(1)" to the pool of literal strings,so in this case,they are same reference objects,so will return true.

提交回复
热议问题