A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 2015天马行空 中级黑马   /  2015-10-29 14:42  /  240 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文



字符串有一个容易混淆的地方,下面我们就这个容易混淆的地方,做一些代码解释.
字符串一旦被赋值就不能被改动。
                        注意:这里的改动指的是字符串的内容,而不是字符串对象的引用。
                B:String s = new String("hello");和String s = "hello";有区别吗?是什么呢?
                       new 出出来的字符串是现在堆内存中创建对象,然后再指向常量池中的对象;
                       直接赋值是将引用直接指向字符串常量池的对象;
                        前者创建了两个对象。
                        后者创建了一个对象。
                看程序,写结果
                        String s1 = new String("hello");
                        String s2 = new String("hello");
                        System.out.println(s1==s2);//false
                        System.out.println(s1.equals(s2));true

                        String s3 = new String("hello");
                        String s4 = "hello";
                        System.out.println(s3==s4);//false
                        System.out.println(s3.equals(s4));//true

                        String s5 = "hello";
                        String s6 = "hello";
                        System.out.println(s5==s6);//true
                        System.out.println(s5.equals(s6));//true
               
                        String s7 = "hello";
                        String s8 = "world";
                        String s9 = "helloworld";
                        System.out.println(s9==s7+s8);
                        System.out.println(s9=="hello"+"world");


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马