intern 方法有什么作用?

JDK 源码里已经对这个方法进行了说明:

     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this {@code String} object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this {@code String} object is added to the
     * pool and a reference to this {@code String} object is returned.
     * <p>
  • 如果当前字符串的内容已存在于字符串常量池(即通过 equals() 方法比较返回 true,表示内容相同),则直接返回字符串常量池中的字符串引用。
  • 否则,将该字符串对象添加到字符串常量池中,并返回字符串对象的引用。

标签: java, Java面试题, Java问题合集, Java编程, Java问题精选, Java常见问题