以下代码,控制台打印的结果是什么?
String s1 = "ab";
String s2 = "a" + "b";
String s3 = s1 + "b";
String s4 = new String("ab");
String s5 = new String("ab");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1 == s4);
System.out.println(s3 == s4);
System.out.println(s1 == s4.intern());
System.out.println(s4 == s5.intern());
System.out.println(s4.intern() == s5.intern());
String s6 = new StringBuilder("for").append("lan").toString();
System.out.println(s6 == s6.intern());
String s7 = new StringBuilder("forlan").toString();
System.out.println(s7 == s7.intern());
打印结果
true
false
false
false
true
false
true
true
false
总结
- 采用new创建的字符串对象不进入字符串池
- 字符串相加时,都是静态字符串,会加到字符串池,
- 字符串相加时,其中含有变量,不会加到字符串池中
- String.intern()的作用:字符串在常量池存在,返回常量引用;不存在,放入该字符串,返回该字符串引用