- String对象、常量池、String.intern()方法的实现原理、for循环执行顺序、逻辑与(&&)等相关内容的考察
- 代码:
public class StringTest {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "hello";
String str3 = "he"+"llo";
String str4 = "he";
String str5 = "llo";
String str6 = str4 + str5;
String str7 = new String("hello");
String str8 = new String("hello").intern();
System.out.println("------普通String测试结果------");
System.out.println("str1 == str2 ? "+(str1 == str2));//str1 == str2 ? true
//str3创建的过程中,"he","llo"都已经存在缓存池中,得到的str3="hello"已经存在缓冲池中,所以直接引用str1
System.out.println("str1 == str3 ? "+(str1 == str3));//str1 == str3 ? true
System.out.println("str1 == str6 ? "+(str1 == str6));//str1 == str6 ? false
//str7 创建的对象存在于堆内存中,不能直接引用
System.out.println("str1 == str7 ? "+(str1 == str7));//str1 == str7 ? false
System.out.println("---------intern测试结果---------");
System.out.println("str1.intern() == str2.intern() ? "+(str1.intern() == str2.intern()));//str1.intern() == str2.intern() ? true
System.out.println("str1.intern() == str3.intern() ? "+(str1.intern() == str3.intern()));//str1.intern() == str3.intern() ? true
System.out.println("str1.intern() == str6.intern() ? "+(str1.intern() == str6.intern()));//str1.intern() == str6.intern() ? true
System.out.println("str1 == str6.intern() ? "+(str1 == str6.intern()));//str1 == str6.intern() ? true
System.out.println("str1.intern() == str7.intern() ? "+(str1.intern() == str7.intern()));//str1.intern() == str7.intern() ? true
System.out.println("str1 == str7.intern() ? "+(str1 == str7.intern()));//str1 == str7.intern() ? true
System.out.println("str1 == str8 ? "+(str1 == str8));//str1 == str8 ? true
System.out.println("-----------------华丽的分割线-----------------");
int i=0;
for (foo('A'); foo('B')&&i<2 ; foo('C')) {
i++;
foo('D');
}
}
static boolean foo(char c){
System.out.print(c);
return true;
}
}
- 输出:
---------普通String测试结果---------
str1 == str2 ? true
str1 == str3 ? true
str1 == str6 ? false
str1 == str7 ? false
---------intern测试结果---------
str1.intern() == str2.intern() ? true
str1.intern() == str3.intern() ? true
str1.intern() == str6.intern() ? true
str1 == str6.intern() ? true
str1.intern() == str7.intern() ? true
str1 == str7.intern() ? true
str1 == str8 ? true
-----------------华丽的分割线-----------------
ABDCBDCB



