java中操作符“==”与对象equals()方法的比较

java中操作符“==”与对象equals()方法的比较

1、“==” 用来比较两个操作元是否相等,操作元可以是基本数据类型,也可以是引用类型。. 2、equals()方法用来比较两个对象是否相等。

对象为基本类型 int a=1,b=2; a==b //false int a=1,b=1; a==b //true

对象为引用类型 Integer int1=new Integer(1); Integer int2=new Integer(1); Integer int3=int1; int1==int2 //false int1.equals(int2) //true int1==int3 //true 引用了同一个对象 int1.equals(int3) //true String str1=“hello”,str2=“world” str1==str2 //false str1.equals(str2) //true

总结:实际运用中,基本类型的比较一般采用“==”,String类型的比较一般采用equals(),比如if(a.equals(“hello”))