先看这段代码,猜猜输出结果:
package strong;
public class Stringtest {
public static void main(String[] args) {
String a="a";
String b="b";
String c="ab";
String d=new String("ab");
if(a+b==c){
System.out.println("a+b==c");
}else{
System.out.println("a+b!=c");
}
if(a+b==d){
System.out.println("a+b==d");
}else{
System.out.println("a+b!=d");
}
/
if(c==d){
System.out.println("c==d");
}else{
System.out.println("c!=d");
}
if(c.equals(d)){
System.out.println("c equals d");
}else{
System.out.println("c does not equal d!");
}
//
if((a+b).equals(c)){
System.out.println("a+b equals c");
}else{
System.out.println("a+b does not equal c!");
}
if((a+b).equals(d)){
System.out.println("a+b equals d");
}else{
System.out.println("a+b does not equal d!");
}
}
}
输出:
a+b!=c
a+b!=d
c!=d
c equals d
a+b equals c
a+b equals d
1.String.equals()方法比较的是字符串的内容
2.“==”比较的是 String 实例的引用
所以a+b和c,d不是同一个引用,c和d也不是同一个引用