JAVA学习(面向对象之比较==和equals的区别)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43271086/article/details/91379742

Java程序中测试两个变量相等有两种方式:一种是利用==运算符,另一种是利用equals方法。

当使用==运算符判断两个变量是否相等,如果两个变量是基本类型变量,且数值相等,则当两个变量相等的时候,返回true。

但是对于引用变量类型变量,只有当他们指向同一个目标的时候才相等,注意等号不能用于比较父子类的对象关系。

下来我们看一段代码

public class EqualTest {
    public static void main(String[] args) {
        int it=65;
        float f1=65.0f;
        System.out.println("65和65.0f是否相等?"+(it==f1));
        char ch='A';
        System.out.println("65和A是否相等"+(it==ch));
        String str1= new String("hello");
        String str2=new String("hello");
        System.out.println("str1和str2"+(str1==str2));
        System.out.println("str1是否equals str2"+(str1.equals(str2)));
        //System.out.println("hello"==new EqualTest());
    }
}

请大家将这个运行在自己电脑上查看结果

在这里,我重点讲述str1和str2使用==和equals的区别

String str1= new String("hello");
String str2=new String("hello");

比较1:

System.out.println("str1和str2"+(str1==str2));

运行结果:false

原因:当两个变量进行比较的时候,只有他们指向同一个对象才能输出true,所以这里创建了两个string,属于两个堆内存区,即他们不是一个对象

比较2:

System.out.println("str1是否equals str2"+(str1.equals(str2)));

运行结果:true

原因:equals是一种值比较,不考虑位置,所以输出为true

比较3:

System.out.println("hello"==new EqualTest());

运行结果:无法运行。

原因:因为java.lang.String和EqualTest之间不存在继承关系。

接下在解决String中一个很迷的地方

hello与new String (“hello”)的区别

当程序使用hello的字符串直接量的时候,JVM会在常量池中管理这些字符串。

当程序使用new String(“hello”)的时候,JVM会在常量池创建一个字符串直接量,然后使用new String创建一个新的对象,所以就创建可两个字符串对象。

重点:JVM常量池只保存一个字符串直接量。

代码展示:
 

public class EqualTest {
    public static void main(String[] args) {
        String s1="我是小菜鸡";
        String s2="我是";
        String s3="小菜鸡";
        String s4="我是"+"小菜鸡";
        String s5="我"+"是"+"小菜鸡";
        String s6=s2+s3;
        String s7=new String("我是小菜鸡");
        System.out.println(s1==s4);
        System.out.println(s1==s5);
        System.out.println(s1==s6);
        System.out.println(s1==s7);
    }
}

运行结果:

true    true     false     false

剖析后两个错误原因:

比较1:

System.out.println(s1==s6);

原因:s6后面的值不能在编译阶段就确定下来。

比较2:

System.out.println(s1==s7);

原因:使用new String()创建对象的时候是在运行时进行的,他被保存在堆内存中,不会放入常量池中

猜你喜欢

转载自blog.csdn.net/weixin_43271086/article/details/91379742