对于基本数据类型而言“==”比较的是数值是否相同
(基本数据类型:
``浮点型:float(4 byte), double(8 byte)
整型:byte(1 byte), short(2 byte), int(4 byte) , long(8 byte)
字符型: char(2 byte)
布尔型: boolean(“true"和"false”)
)
public class test04 {
public static void main(String[] args) {
int a=3;
int b=3;
System.out.println(a=b);//true
}
}
上面代码比较的是两个变量的数值是否相同
对于引用类型"=="比较的是引用指向的地址值是否相同
public class test04 {
public static void main(String[] args) {
String a="abc";
String b="abc";
String s1=new String("abc");
String s2=new String("abc");
System.out.println(a==b);//true,因为是在字符量常量中
System.out.println(b==s1);//false
System.out.println(s1==s2);//false
}
}
基本数据没有equal方法只能用“==”比较,引用类型其实本质上也是比较两个对象引用地址是否相同,但是常见的类重写了equal()方法,所以它比较的是两个对象的值是否相同。如:String
Objet源码
public boolean equals(Object obj) {
return (this == obj);
}
String源码
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
总结:==比较基本数据类型比较的是值是否相同,比较引用类型比较的是指向的地址是否相同。equal()比较引用类型本质上比较的还是引用地址是否相同,只不过如:String,Integer重写了equal方法所以比较的是值是否相同。