先上示例代码如下:
String a="hello";
String b=new String("hello");
if(a==b)
{
System.out.println("a==b");
}
else
{
System.out.println("a!=b");
}
if(a.equals(b))
{
System.out.println("a equals b");
}
else
{
System.out.println("a not equals b");
}
输出结果为:
a!=b
a equals b
区别总结:
- ==比较的是变量的地址。因为s1是变量其hello在常量池,而s2是对象其hello在堆中,故s1,s2的地址不同。
- equals比较的是变量的内容。s1,s2的内容相同都为hello。