不知道大家有没有思考过一个这样的问题,Java 中 String 类不是基本数据类型,但是我们在日常使用中,却可以像基本数据类型中一样使用,例如:

  1. int a1 = 1;
  2. String s1 = "s1";

这里就要提到字面量和常量池的概念了,JVM 在方法区中专门有一块常量池区域用来存这些常量。

String.intern()

这个方法很少用,早年间为了应付面试,背过相关的八股文,但是面试完就忘了。最近又是复习为了面试,点进这个方法看了下:

  1. /**
  2. * Returns a canonical representation for the string object.
  3. * <p>
  4. * A pool of strings, initially empty, is maintained privately by the
  5. * class {@code String}.
  6. * <p>
  7. * When the intern method is invoked, if the pool already contains a
  8. * string equal to this {@code String} object as determined by
  9. * the {@link #equals(Object)} method, then the string from the pool is
  10. * returned. Otherwise, this {@code String} object is added to the
  11. * pool and a reference to this {@code String} object is returned.
  12. * <p>
  13. * It follows that for any two strings {@code s} and {@code t},
  14. * {@code s.intern() == t.intern()} is {@code true}
  15. * if and only if {@code s.equals(t)} is {@code true}.
  16. * <p>
  17. * All literal strings and string-valued constant expressions are
  18. * interned. String literals are defined in section 3.10.5 of the
  19. * <cite>The Java&trade; Language Specification</cite>.
  20. *
  21. * @return a string that has the same contents as this string, but is
  22. * guaranteed to be from a pool of unique strings.
  23. */
  24. public native String intern();

该方法详细描述了它的用法和用例,非常贴心,相对比网上的人云亦云,注释上一目了然,现在想想这大概是比以前成熟的表现之一了吧,会先自己看官文,更有耐心找答案,而不是去看别人怎么说的。

用法:当调用这个方法时,如果在 String 常量池中有这个值,那么直接返回,如果没有,那么会添加到 String 常量池中。