Java中“==”和“equales()”的区别

在判断字符串相等时,==是在比较对象地址是否相等,而equales()是在比较两个对象中的值是否相等

结合代码分析:

String s1="abc";
String s2="abc";
String a1=new String("abc");
String a2=new String("abc");
System.out.println("s1地址:"+System.identityHashCode(s1));
System.out.println("s2地址:"+System.identityHashCode(s2));
System.out.println("a1地址:"+System.identityHashCode(a1));
System.out.println("a2地址:"+System.identityHashCode(a2));
System.out.println(s1.equals(s2));
System.out.println(s1.equals(a1));
System.out.println(a1.equals(a2));
if(s1==s2) System.out.println("true");else System.out.println("false");
if(s1==a1) System.out.println("true");else System.out.println("false");
if(a1==a2) System.out.println("true");else System.out.println("false");

运行结果是

s1地址:460141958
s2地址:460141958
a1地址:1163157884
a2地址:1956725890
true
true
true
true
false
false
posted @ 2021-09-20 15:52  琉璃若火  阅读(180)  评论(0)    收藏  举报