以下列出五种情况,每个方法的注释中对每个情况进行了解析:
private void str1() {
/**
* 创建了三个对象,包括两个new的字符串对象,以及第一次new时在常量池中创建"Hello"对象
* s1和s2分别指向堆内存中不同的位置,所以输出为false
*/
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);
}
private void str2() {
/**
* 程序只在常量池中创建一个"World"字符串对象
* s1和s2都指向常量池中的"World",输出为true
*/
String s1 = "World";
String s2 = "World";
System.out.println(s1 == s2);
}
private void str3() {
/**
* 经过编译器优化只会在常量池中创建了一个"Hello World"对象
* s1和s2都指向常量池中的"Hello World",输出为true
*/
String s1 = "Hello World";
String s2 = "Hello " + "World";
System.out.println(s1 == s2);
}
private void str4() {
/**
* 在常量池中创建了三个对象
* s4由两个变量相加,不能在编译时确定下来,不能直接引用常量池中的"Hello World"对象,所以输出为false
*/
String s1 = "Hello World";
String s2 = "Hello ";
String s3 = "World";
String s4 = s2 + s3;
System.out.println(s1 == s4);
}
private void str5() {
/**
* 在常量池创建了三个对象
* 在编译时会将s2和s3替换为它的值,所以s4由两个常量相加而指向常量池中的"Hello World"对象,所以输出为true
*/
String s1 = "Hello World";
final String s2 = "Hello ";
final String s3 = "World";
String s4 = s2 + s3;
System.out.println(s1 == s4);
}