JAVA ==与equals区别

 == 是一个运算符,Equals则是string对象的方法。

==在基本数据类型比较时,比较值是否相等;在比较引用对象时,比较地址是否相同。equals()只用于比较值相等。

1.基本数据类型比较

==既可以比较int,double类型,也可以比较String类型。相等为true,否则为false。

equals()是String对象的方法,只能用于比较String变量的值。相等为true,否则为false。 

例1:

代码: 

public static void main(String[] args) {
// TODO Auto-generated method stub
int a=11;
int b=11;
String c="abc";
String d="abc";
if(a==b)
System.out.println("true");
else
System.out.println("false");
if(c==d)
System.out.println("true");
else
System.out.println("false");
}

 结果:

true
true

2、引用对象比较

==比较栈内存中的地址是否相等 ,相等为true 否则为false。equals比较值,相等为true,否则为false。

 例2:

代码:

public static void main(String[] args) {
String d="abc";
String e=new String("abc");
if(e==d)
System.out.println("true");
else
System.out.println("false");
}

结果:

false 

true 

原文地址:https://www.cnblogs.com/bluewhy/p/4911221.html