public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("q1: true");
q1();
System.out.println("q2: false");
q2();
System.out.println("q3: false");
q3();
System.out.println("q4: true");
q4();
System.out.println("q5: false false false true true");
q5();
System.out.println("q6: false");
q6();
}
//String s1 = "abc";直接在常量池找abc,有就返回引用,没有就创建返回引用
public static void q1() {
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2);
}
// new String("abc"); 在heap堆中创建对象。每次创建都是不同的
public static void q2() {
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2);
}
//1.常量相加,编译时直接组合S4="a"+"bc" == s4="abc"
//2.变量和常量相加,会调用stringBuilder.append()在heap堆上创建新对象 s4=s2+"bc"
//3.变量与变量同2 s4=s2+s3
public static void q3() {
String s1 = "abc";
String s2 ="a";
String s3 = "bc";
String s4 = s2 + s3;
System.out.println(s1 == s4);
}
//对于final字段,编译时直接替换成 s4="a"+"bc" == s4="abc"
public static void q4() {
String s1 = "abc";
final String s2 = "a";
final String s3 = "bc";
String s4 = s2 + s3;
System.out.println(s1 == s4);
}
//一个对象如果调用了intern()方法,首先查询常量池中是否存在,有返回常量池的引用
//没有则在常量池中创建则引用该对象(jdk1.7之后),之前是复制一个副本放到常量池
public static void q5() {
String s = new String("abc");
String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 == s2);
System.out.println(s == s1.intern());
System.out.println(s == s2.intern());
System.out.println(s1 == s2.intern());
System.out.println(s1 == s.intern());
}
//new的对象始终在堆里
public static void q6()
{
String s = new String("abc");
s.intern();
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s1 == s2);
}
String.intern()
最新推荐文章于 2025-07-11 10:19:23 发布