首页 > 代码库 > Java 字符串比较(2)

Java 字符串比较(2)

public class Test2 {
public static void main(String[] args) {
String a = "aaa";
String b = "bbb";
String c = "aaa" + "bbb";
String d = "aaabbb";
String e = a + b;
String f = "aaa" + b;
String g = a + "bbb";

System.out.println("c == d:" + (c == d));
System.out.println("c == e:" + (c == e));
System.out.println("c == f:" + (c == f));
System.out.println("c == g:" + (c == g));

System.out.println("c equals d:" + (c.equals(d)));
System.out.println("c equals e:" + (c.equals(e)));
System.out.println("c equals f:" + (c.equals(f)));
System.out.println("c equals g:" + (c.equals(g)));
}
}

控制台输出:

c == d:true
c == e:false
c == f:false
c == g:false
c equals d:true
c equals e:true
c equals f:true
c equals g:true

关键:两个匿名String对象通过“+“连接的话,会直接指向拼接后的堆内存地址,所以c==d。

匿名String对象与String实例对象通过“+”连接的话,不会做类似操作,所以后面3中都返回false。

 

Java 字符串比较(2)