字符串比较==和equals

java中的数据类型分为字符型,数值型,布尔型和引用类型,其中字符型、数值型、布尔型统称为基本数据类型

1、观察基本数据类型的比较,利用“==”进行比较

public class MyInterface{
    public static void main(String[] args){
        int x = 23;
        int y = 23;
        System.out.println(x == y); //return value:true
    }
}

观察用 “==”进行String对象的比较

public class MyInterface{
    public static void main(String[] args){
        String str1 = "Hello";
        String str2 = new String("Hello");
        System.out.println(str1 == str2);

    }
}

上述代码返回值是false,这是为什么呢?

因为String是引用类型,直接使用“== “ 比较的是指向字符串的引用,即存储字符串的地址,在java中遇到new关键字就要开辟新空间,所以返回值为false

如果要比较字符串的内容就需要用String类的equals()方法进行比较如下述代码

public class MyInterface{
    public static void main(String[] args){
        String str1 = "Hello";
        String str2 = new String("Hello");
        System.out.println(str1.equals(str2)); //input:true
    }
}

2、再观察下面的代码

public class MyInterface{
    public static void main(String[] args){
        String str1 = "Hello";
        String str2 = "Hello";
        System.out.println(str1 == str2); //input:true
    }
}

上面的代码使用”==“比较时返回值却为 true,这就涉及到java中的对象池的概念。

对象池:JVM底层会自动维护一个字符串的对象池,如果现在采用直接赋值的形式进行String的对象实例化,该对象会自动保存在这个对象池中。如果下次继续使用直接赋值的模式声明String对象,此时对象池若有指定内容,则直接使用;如果没有,则开辟新的堆空间将其保存在对象池中供下次使用

上述代码中str2指向的字符串与第一次的字符串的内容相同,JVM没有新开辟空间,所以用 == 比较地址的时候,返回true

 

 

3、在用java判断用户输入的字符串是否与特定字符串相等,请看下面代码:

public class MyInterface{
    public static void main(String[] args){
        String str = null; //假设由用户输入

        //System.out.println(str.equals("hehe")); //运行时异常
        /**Exception in thread "main"           
           java.lang.NullPointerException
        at MyInterface.main(MyInterface.java:229)*/


        System.out.println("hehe".equals(str));  //返回false
    }
}

所以在比较字符串是否相等时,使用 :

String str  = " ";

"特定字符串".equals(str2);    //推荐使用该形式

str2.equals(特定字符串);        //有可能产生空指针异常

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值