深入学习String类

public class Test {
    public static void main(String[] args) {
        String s1 = "a";
        String s2 = "b";
        String s3 = s1 + s2;
        String s4 = "ab";
        System.out.println(s3 == s4);
    }
}

运行结果为:

false
View Code

 

JVM运行过程为:在堆的常量池中创建一个String对象存放值a,在栈中创建一个对象的引用s1指向该对象;s2同理。第三行代码,运行期间JVM首先创建一个StringBuilder类,并用s1完成初始化,之后调用append方法合并s2,接着用Stringbuilder类的toString创建一个String对象,并将其引用赋值给s3.s4为创建一个String对象放到堆的常量池中,s4存放其引用。s3与s4肯定是不同的。

public class Test {
    public static void main(String[] args) {
        String s1 = "a" + "b";
        String s2 = "ab";
        System.out.println(s1 == s2);
    }
}
true
View Code

编译期间JVM就完成了常量字符串的拼接,并将字符串“ab”放在常量池中,并将其引用赋值给s1。为s2赋值时,首先查询常量池发现有“ab”,就将其引用赋给s2,即s1和s2是同一个引用。故为true.

 再看一个例子:

public class Test {
    public static void main(String[] args)  {
        String a = "hello2"; 
        final String b = "hello";
        String d = "hello";
        String c = b + 2; 
        String e = d + 2;
        System.out.println((a == c));
        System.out.println((a == e));
    }
}

  
true
false
View Code

对于b因为有final修饰,故编译期就当成常量处理,c指向的就是拼接后的常量“hello2”,a也是指向常量池中的hello2,故a == c 返回true.再看程序运行到第5行时,首先创建一个StringBulider类型的对象,并用变量d的值完成初始化,之后再调用append方法拼接“2”,并调用StringBuilder对象的toString()方法创建一个String对象,并将其引用赋值给e,故e == a返回false

 

 



posted @ 2016-07-26 22:16  sonia123  阅读(111)  评论(0)    收藏  举报