7k7k笔试题(一):equals()和==的区别

来源:互联网 发布:js 读取数组最后一个 编辑:程序博客网 时间:2024/06/05 16:15

       参加7k7k笔试,遇到这样一个选择题,主要考String字符串、equals()、==的结合。

       public class Demo

       {

              public static void main(String args[])

              {

                     String str=new String("hello");

                     if(str=="hello")

                     {

                          System.out.println("true");

                     }      

                     else{

                           System.out.println("false");

                    }

        运行结果:false

        解释:首先要理解String str=new String("hello")的内存,括号中的“hello”表示在常量池中创建hello,new关键词又在堆中创建“hello”,所以这一句创建了两个对象。

    其次要理解“==”与“equals()”的区别。“==”要求既在内存地址上相等,又要在值上相等。而“equals()”只要求在值上相等即可。

    而if语句的括号内表示在常量池中创建的hello,而str表示堆中的hello,所以二者的内存地址不同,所以输出false。如果将==改为equals(),则输出true。

      例如:  

public class Demo10 {
     public static void main(String[] args) {
            String a="abc";
            String b=new String("abc");
            String c="abc";
            System.out.println(a==b);
            System.out.println(a==c);
            System.out.println(b==c);
            System.out.println(a.equals(b));
     }

}

输出:

false
true
false
true