The return of String.intern() explained

前端 未结 3 1572
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题