- 首先String不属于8种基本数据类型,是一个对象,默认值为null,new String()和new String("")都是声明一个空字符串,而不是null。
- 面试时经常被问到:
String s = “hello”;和String s = new String(“hello”);的区别。
这里我们先说说常量池。
常量池是在编译期被确定,并被保存在已编译的.class文件中的一些数据。它包括了关于类、方法、接口等中的常量,也包括字符串常量。
` public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello world";
String s3 = s1+" world";
String s4 = "hello"+" world";
String s5 = new String( "abc ");
System.out.println(s2==s3); //false,实际上是new StringBuffer(s1).append(" world");
System.out.println(s2==s4); //true
}
“hello"和” world"都是字符串常量,它们在编译期就被确定了,多个字符串常量连接时,结果也是字符串常量,因此s2==s4。
而s5通过new创建字符串时,这里 "abc "本身就是pool中的一个对象,而在运行时执行new String()时,将pool中的对象复制一份放到heap中,并且把heap中的这个对象的引用交给s5持有。ok,这条语句就创建了2个String对象。
- intern()的意思:
当一个String实例str调用intern()方法时,Java查找常量池中是否有相同Unicode的字符串常量,如果有,则返回其的引用,如果没有,则在常量池中增加一个Unicode等于str的字符串并返回它的引用
public static void main(String[] args) {
String ss0 = "abc";
String ss1 = new String("abc");
System.out.println(ss0==ss1); // false
ss1 = ss1.intern(); //查找常量池是否有abc的引用,如果有则返回,如果没有则创建
System.out.println(ss0==ss1); // true
}
```java