对于基本数据类型,==比较值,对于对象,比较内存地址。
equals方法是需要用户重写的,它的行为由程序员定义。现在jdk中的类重写这个方法,比较的都是内容(如String类)。
public class stringComp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1=new String("woko");
String str2="woko";
String str3="woko";
String str4=new String("woko");
if(str2==str3){
System.out.println("str2=str3");
}
if(str2.equals(str3)){
System.out.println("str2 is equals with str3");
}
if(str1==str4){
System.out.println("str1=str4");
}
if(str1.equals(str4)){
System.out.println("str1 is equals with str4");
}
if(str1==str2){
System.out.println("str1= str2");
}
if(str1.equals(str2)){
System.out.println("str1 is equals with str2");
}
}
}
输出 :
str2=str3
str2 is equals with str3
str1 is equals with str4
str1 is equals with str2