String 看程序写结果

来源:互联网 发布:古城户外的刀淘宝地址 编辑:程序博客网 时间:2024/04/27 16:02

1 String 类的== 和equals()方法

    String s1="hello";    String s2="hello";    System.out.println(s1==s2);  1    System.out.println(s1.equals(s2));  2    System.out.println("--------------------");    String s3=new String("hello");       String s4=new String("hello");     System.out.println(s3==s4);                  3     System.out.println(s3.equals(s4));         4     System.out.println("-----------");    System.out.println(s1==s3);               5     System.out.println(s1.equals(s3));       6    true   true  false  true  false    true     说明:只要子类重写了Object里面的equals()方法就是比较的是内容是否相等,==比较的是地址是否相等    1说明:因为没有new对象,直接把hello变量的地址给了s1和s2所以,地址相等     2说明:s1 和s2的内容也相等    3对于String new的对象,说明一下如下:    对于String s1="hello";    String s2=new String("hello");分别new了几个对象    s1 是引用类型,new了一个"hello"的字符串常量在常量池里面    s2 newString类的对象,而且也是new了一个字符串常量,所以一共两个对象

2字符串变量和字符串常量相加

        String s1 = "hello";          String s2 = "world";        String s3 = "helloworld";        System.out.println(s3 == s1 + s2);// false   1        System.out.println(s3.equals((s1 + s2)));//true ,         System.out.println(s3 == "hello" + "world");//true  2         System.out.println(s3.equals("hello" + "world"));//true        说明: 字符串变量相加,先开辟空间,在相加。             字符串常量相加:首先在字符串常量池找,有没有当前这个常量值,有,就直接返回,没有,需要创建!        1说明:首先  开辟一个空间,把s1和s2的相加之后的值放进去,所以地址不相等。        等价于new String("helloword";用反编译工具查看s3 == (new StringBuilder(String.valueOf(s1))).append(s2).toString()2说明:字符串常量相加,查看相加之后的常量在常量池里面有没有,发现有就返回helloword的地址,==左右都是helloword的地址,所以相等
原创粉丝点击