`
pengfeicao521
  • 浏览: 140451 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

java中String类的理解

阅读更多
一,关于String类的说明
1.String使用private final char value[]来实现字符串的存储,也就是说String对象创建之后,就不能
再修改此对象中存储的字符串内容,就是因为如此,才说String类型是不可变的(immutable).

2.String类有一个特殊的创建方法,就是使用""双引号来创建.例如new String("i am")实际创建了2个
String对象,一个是"i am"通过""双引号创建的,另一个是通过new创建的.只不过他们创建的时期不同,
一个是编译期,一个是运行期(new)!

3.java对String类型重载了+操作符,可以直接使用+对两个字符串进行连接.

4.运行期调用String类的intern()方法可以向String Pool中动态添加对象.

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";//在stringpool创建的常量,在编译期就已经确定
    String s4 = "sss" + s1;//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中.
6.使用"aa" + s1以及new String("aa" + s1)形式创建的对象是否加入到String Pool中我不太确定,可能是必须
调用intern()方法才会加入,希望高手能回答

还有个特殊发现:
String s1 = "s1" + "s2"编译后会在String Pool中加入"s1s2"和"s1" 2个常量,但是没有加入"s2",不知道是什么规律??试了String s1 = "s1" + "s2" + "s3" + "s4",还是只加入了"s1s2s3s4"和"s1",好像除了第一个后面的都不加入了.

还有几个经常考的面试题:
1.
String s1 = new String("s1") ;
String s2 = new String("s1") ;
上面创建了几个String对象?
答案:3个 ,编译期Constant Pool中创建1个,运行期heap中创建2个.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics