1. String类的两个构造方法

private final char value[];
private int hash;

public String() {
    this.value = "".value;
}
public String(String original) { this.value = original.value; this.hash = original.hash; }

2. new String中创建几个String对象?

1)创建两个String对象

public static void main(String[] args) {
    String y = new String("hello");
}

内存模型如下:

Java字符串池

2)创建一个String对象

public static void main(String[] args) {
    String x = "hello";
    String y = new String("hello");
}

内存模型如下:

Java字符串池

3. String的intern方法

String类私有地维护着一个初始为空的字符串池,当调用intern方法时:

1. 若字符串池中已包含一个等于此String对象的字符串(用 equals方法确定),则返回池中的字符串。
2. 否则,将此String对象添加到字符串池中,并返回池中的字符串。

public native String intern();

字符串池中存放的是String对象的引用,而非String对象本身。

实验:

public static void main(String[] args) {
    String x = "hel";
    x += "lo";
    String y = "ja";
    y += "va";
    System.out.println(x == x.intern()); // true
    System.out.println(y == y.intern()); // false
}

结论:字符串池中已包含一个等于"java"的字符串(JVM启动后在字符串池中加载的字符串还包括:"true"、"false"...)

内存模型如下:

intern()前

Java字符串池

intern()后

Java字符串池

4. 后记

Java字符串池

相关文章:

  • 2021-07-13
  • 2022-01-08
  • 2021-10-11
  • 2022-12-23
  • 2021-07-13
  • 2021-11-05
  • 2022-12-23
  • 2021-05-16
猜你喜欢
  • 2022-01-17
  • 2021-05-24
  • 2021-09-30
  • 2021-09-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案