Java中String的equals和==

(1)==
①用于基本数据类型的比较。
②判断引用是否指向堆内存的同一块地址
(2)equals
①用于判断两个变量是否是对同一个对象的引用,即判断堆内存中的内容是否相同。
②String重写了Object的equals()方法。(主要判断两个字符串的内容是否一样)源码如下

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;
    }

(3)例子
①对象不同,内容相同(==为false,equals为true)

public class TestString {

    public static void main(String[] args) {

        String s1 = new String("aa");
        String s2 = new String("aa");

        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}
false
true

②对象相同(==为true,equals为true)

public class TestString {

    public static void main(String[] args) {

        String s1 = new String("aa");
        String s2 = s1;

        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}
true
true

③String作为一个基本类型(==为true,equals为true)

public class TestString {

    public static void main(String[] args) {

        String s1 = "aa";
        String s2 = "aa";

        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}
true
true

(4)重要知识点
①如果String缓冲池内不存在与其指定值相同的String对象,那么虚拟机将为其*新建一个String对象,并放到缓冲池中。
②如果String缓冲池内存在与其指定值相同的String对象,那么直接返回已存在的String对象的引用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值