详解equals和==的区别

对于字符串变量:
1、如果使用的类重写了equals()方法,那么equals()比较的是字符串中包含的内容是否相同,否则equals()和==一样比较的是内存地址;
2、==始终比较的是两个变量的内存地址;

public class Test1 {
public static void main(String[] args) {
    String s1,s2,s3="abc",s4="abc";
    s1=new String("abc");
    s2=new String("abc");
    System.out.println(s1==s2);//false
    System.out.println(s3==s4);//true
     StringBuffer buf1 = new StringBuffer("a");
     StringBuffer buf2 = new StringBuffer("a");
     System.out.println(buf1.equals(buf2));//false,
     //因为StringBUffer没有重写Object的equals()方法
}
}

对于非字符串变量:
“==”和”equals”方法的作用是相同的都是用来比较其
对象在堆内存的首地址,即用来比较两个引用变量是否指向同一个对象。
另外:
1、 如果是基本类型比较,那么只能用==来比较,不能用equals,否则编译不能通过;

public class Test2 {
public static void main(String[] args) 
{
int a = 5;
int b = 4;
int c = 5;
System.out.println(a == b);//结果是false
System.out.println(a == c);//结果是true
System.out.println(a.equals(c));//错误,编译不能通过
}
}

2、 对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的。

public class Test2 {
public static void main(String[] args) {
    Integer n1 = new Integer(30);
    Integer n2 = new Integer(30);
    Integer n3 = new Integer(31);
    System.out.println(n1==n2);//false
    System.out.println(n1.equals(n2));//true
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值