Java中的“==“与“equals()“的对比,Java的字符串常量池概念

Java中的"=="与"equals()"的对比,Java的字符串常量池概念

Java中的"=="在判断基本类型数据时

当比较基本数据类型的时候比较的是数值。

public class Demo_1 {
    public static void main(String[] args){
        int i = 10;
        int j = 10;
        boolean b = (i==j);
        System.out.println(b);
    }
}
/*
输出结果:
true
*/

"=="在判断引用数据类型时

当比较引用类型数据时比较的是引用(指针)。

public class Demo_1 {
    public static void main(String[] args) {
        String str1 =new String ("zzh");
        String str2 = "zzh";
        System.out.println(str1==str2);
      }
}
/*
输出结果:
false
*/

equals()方法

对比上一个Java实例

public class Demo_1 {
    public static void main(String[] args) {
        String str1 =new String ("zzh");
        String str2 = "zzh";
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));
      }
}
/*
输出结果:
false
true
*/

用equals()方法对比str1与str2时发现返回的布尔类型的值为true

在0bject中就存在equals()方法,但仍需要引用同一个对象时才返回true,Object时所有类的父类,所以一般定义的类中都会根据自己的需要重写equals()方法,例如在String中,就重写了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;
    }

字符串常量池

String s1 = "hello,world!";
String s2 = "hello,world!";

在执行完第一行代码后,常量池就已经存在了"hello,world",在当第二句代码运行时,就不会重新申请内存空间,而是将已有字符串的地址返回给引用变量时s2,

所以这时判断s1==s2会返回true

public class Demo {
    public static void main(String[] args) {
        String str1 =new String ("zzh");
        String str2 = "zzh";
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));
        String str3 = "zzh";
        String str4 = "zzh";
        System.out.println(str3==str4);
        System.out.println(str3.equals(str4));
    }
}
/*
输出结果:
false
true
true
true
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值