String常见问题

示例1 

    @Test
    public void test()
    {
        String s1 = "AB"; // "AB" 放到了字符串常量池种
        String s2 = new String("AB"); //new出来的对象,对象放堆上
        String s3 = "A"; 
        String s4 = "B";
        String s5 = "A" + "B"; // 编译期就确定的字符串相加  直接合并成"AB" 返回常量池中已有"AB"的地址  
// 因此这种情况下字符串拼接用"+"比StringBuilder性能好
String s6 = s3 + s4; //普遍变量,编译期不确定值,字符串的"+"操作其本质是创建了StringBuilder对象进行append操作,
//然后将拼接后的StringBuilder对象toString()方法处理成新对象
        System.out.println(s1==s2);
        System.out.println(s1==s5);
        System.out.println(s1 == s6);
        System.out.println(s1 == s6.intern()); //intern() 返回该字符串在常量池中的引用,如常量池中没有,则直接创建并返回引用
        System.out.println(s2 == s2.intern());
    }

我们知道java有3种常量池,分别为运行时常量池,class文件常量池,字符串常量池

直接通过双引号申请的字符串,会放入字符串常量池中

而new出来的String对象,则毫无疑问放到了堆上

运行结果

false
true
false
true
false

 

示例2 

    @Test
public void test2() {
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

      大家可以先想一下这道题的输出结果。为什么第一个比较结果为true,而第二个比较结果为fasle。这里面就是final变量和普通变量的区别了,当final变量是基本数据类型以及String类型时,如果在编译期间能知道它的确切值,则编译器会把它当做编译期常量使用。也就是说在用到该final变量的地方,相当于直接访问的这个常量,不需要在运行时确定。这种和C语言中的宏替换有点像。因此在上面的一段代码中,由于变量b被final修饰,因此会被当做编译器常量,所以在使用到b的地方会直接将变量b 替换为它的值。而对于变量d的访问却需要在运行时通过链接来进行。想必其中的区别大家应该明白了,

 

不过要注意,只有在编译期间能确切知道final变量值的情况下,编译器才会进行这样的优化,比如下面的这段代码就不会进行优化:

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

这段代码的输出结果为false。

这里要注意一点就是:

      不要以为某些数据是final就可以在编译期知道其值,通过变量b我们就知道了,在这里是使用getHello()方法对其进行初始化,他要在运行期才能知道其值。

 

待补充后续

 

posted on 2020-06-22 23:35  鑫男  阅读(239)  评论(0编辑  收藏  举报

导航