The return of String.intern() explained

前端 未结 3 1553
粉色の甜心
粉色の甜心 2020-12-20 11:54

Consider:

String s1 = new StringBuilder(\"Cattie\").append(\" & Doggie\").toString();
System.out.println(s1.intern() == s1); // true why?
System.out.prin         


        
相关标签:
3条回答
  • 2020-12-20 12:06

    s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.

    On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.

    I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.

    0 讨论(0)
  • 2020-12-20 12:11

    String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.

    Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.

    That is explained here: What is Java String interning?

    0 讨论(0)
  • 2020-12-20 12:18

    When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    So java string must already be in the pool. hence it is giving false.

    You can print all strings in pool

    How to print the whole String pool?

    Here is an example to get all string if you are using openjdk.

    0 讨论(0)
提交回复
热议问题