String字符串与常量池详解

概述

String是Java中最重要的类,掌握其内存机制对于优化和避免常见陷阱至关重要。

String创建方式

字面量方式

1
2
3
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true

new方式

String s3 = new String(“hello”);
String s4 = new String(“hello”);
System.out.println(s3 == s4); // false

连接方式

String s5 = “hello” + “world”; // 编译期优化
String s6 = new String(“hello”) + new String(“world”); // 堆内存

常量池位置演变

  • JDK < 1.7:PermGen(方法区)
  • JDK 1.7:堆内存
  • JDK 1.8+:MetaSpace(本地内存)

intern()方法详解

String s1 = new String(“hello”);
String s2 = s1.intern();
String s3 = “hello”;
System.out.println(s2 == s3); // true

常见问题

Q: == 和 equals 的区别? A: == 比较地址,equals 比较内容

Q: 字符串拼接的性能问题? A: 大量拼接使用StringBuilder,避免String连接

Q: intern()的作用? A: 将堆中的字符串放入常量池,返回常量池中的引用

Q: 创建对象个数问题? A: new String(“abc”) 在常量池不存在时创建2个对象,存在时创建1个