日期:2014-05-20 浏览次数:20836 次
String str1="abc";
String str2="hello"+str1;//在堆中创建一个String对象存放 "hello" + str1;
String str3="hello"+str1;//同上
System.out.println((str2==str3));//两个引用指向堆中不同的对象,值为false
String str1="abc";
String str2="hello"+"abc";//因为是两个常量相加,在常量池中创建一个新的常量 "hello" + "abc"
String str3="hello"+"abc";//同上
System.out.println((str2==str3));//两个引用指向常量池中同一个对象,值为true
public class Stringequals {
public static void main(final String[] args) {
System.out.println(test01());
System.out.println(test02());
System.out.println(test03());
System.out.println(test10());
System.out.println(test20());
System.out.println(test30());
}
private static boolean test01() {
String str1 = "abc";
String str2 = "hello" + str1;
String str3 = "hello" + str1;
return str2 == str3;
}
private static boolean test02() {
String str2 = "hello" + "abc";
String str3 = "hello" + "abc";
return str2 == str3;
}
private static boolean test03() {
String str2 = new String("hello"+"abc");
String str3 = "hello" + "abc";
return str2 == str3;
}
private static boolean test10() {
String str1 = "abc";
String str2 = "hello" + str1;
String str3 = "hello" + str1;
return str2.equals(str3);
}
private static boolean test20() {
String str2 = "hello" + "abc";
String str3 = "hello" + "abc";
return str2.equals(str3);
}
private static boolean test30() {
String str2 = new String("hello"+"abc");
String str3 = "hello" + "abc";
return str2.equals(str3);
}
}