详解Java String字符串对象的创建及管理(2)

String的创建方法一般有如下几种

1.直接使用""引号创建;

2.使用new String()创建;

3.使用new String("someString")创建以及其他的一些重载构造函数创建;

4.使用重载的字符串连接操作符+创建。

例1

String s1 = "sss111";

    //此语句同上
    String s2 = "sss111";

    
    System.out.println(s1 == s2); //结果为true

例2

String s1 = new String("sss111");
   
    
    String s2 = "sss111";
   
    
    System.out.println(s1 == s2); //结果为false

例3

String s1 = new String("sss111");
    
    s1 = s1.intern();
   
    String s2 = "sss111";
   
    
    System.out.println(s1 == s2);

例4

String s1 = new String("111");
    String s2 = "sss111";
   
    
    String s3 = "sss" + "111";
   
    
    String s4 = "sss" + s1;
   
    System.out.println(s2 == s3); //true
    System.out.println(s2 == s4); //false
    System.out.println(s2 == s4.intern()); //true

例5

这个是The Java Language Specification中3.10.5节的例子,有了上面的说明,这个应该不难理解了

package testPackage;
    class Test {
            public static void main(String[] args) {
                    String hello = "Hello", lo = "lo";
                    System.out.print((hello == "Hello") + " ");
                    System.out.print((Other.hello == hello) + " ");
                    System.out.print((other.Other.hello == hello) + " ");
                    System.out.print((hello == ("Hel"+"lo")) + " ");
                    System.out.print((hello == ("Hel"+lo)) + " ");
                    System.out.println(hello == ("Hel"+lo).intern());
            }
    }
    class Other { static String hello = "Hello"; }

    package other;
    public class Other { static String hello = "Hello"; }

输出结果为true true true true false true,请自行分析!

结果上面分析,总结如下:

1.单独使用""引号创建的字符串都是常量,编译期就已经确定存储到String Pool中;

2.使用new String("")创建的对象会存储到heap中,是运行期新创建的;

3.使用只包含常量的字符串连接符如"aa" + "aa"创建的也是常量,编译期就能确定,已经确定存储到String Pool中;

4.使用包含变量的字符串连接符如"aa" + s1创建的对象是运行期才创建的,存储在heap中;

5.使用"aa" + s1以及new String("aa" + s1)形式创建的对象是否加入到String Pool中我不太确定,可能是必须调用intern()方法才会加入。

还有几个经常考的面试题:

1.

String s1 = new String("s1") ;
String s2 = new String("s1") ;
上面创建了几个String对象?
答案:3个 ,编译期Constant Pool中创建1个,运行期heap中创建2个.

2.

String s1 = "s1";
String s2 = s1;
s2 = "s2";
s1指向的对象中的字符串是什么?
答案: "s1"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值