Java字符串文字串联 [英] Java String literals concatenation

查看:113
本文介绍了Java字符串文字串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    public static void main(String[] args){
        one();
        two();
        three();
    }

    public static void one() {
        String s1 = "hill5";
        String s2 = "hill" + 5;
        System.out.println(s1==s2);
    }

    public static void two() {
        String s1 = "hill5";
        int i =5;
        String s2 = "hill" + i;
        System.out.println(s1==s2);
    }

    public static void three() {
        String s1 = "hill5";
        String s2 = "hill" + s1.length();
        System.out.println(s1==s2);
    }

输出

true 
false 
false 

字符串文字使用实习过程,那么为什么 two() three()为false。我可以理解为三()两()不清楚。但是需要对这两种情况做出适当的解释。

String literals use interning process,then why two() and three() is false.I can understand in case of three() but two() is not clear.but need proper explanation for both cases.

有人可以解释正确的理由吗?

Can someone please explain proper reason?

推荐答案

如果是2和3,编译器无法计算String的值,因为 hill + i 是一个运行时语句,对于 s1.length()

In case of 2 and 3 , Compiler cannot calculate the value of String , since hill + i is a runtime statement , same for s1.length()

在这里阅读我问了同样的案例 - 链接

read here which i asked the same case - link

这样认为 String s1和s2 正在使用编译时常量, s1 =hill5 s2 =hill+ 5 ,请记住,指定为文字的字符串是常量,其状态不能修改,因为字符串是不可变的

Think like this the String s1 and s2 are using compile time constant , s1="hill5" and s2="hill" + 5 , remember , string assigned as a literal is constant , its state cannot be modified , as String are immutable.

所以在编译时,编译器说哦是的,它们被计算为相同的值,我必须为s1和s2分配相同的引用。

So at Compile time , compiler says "oh yeah , they are calculated as same value , i must assign the same reference to s1 and s2".

但是在方法两()三()的情况下,编译器说我不知道,可能是我的价值可以随时改变,或者 s1.length() chang es任何时候,它是一个运行时的东西,所以编译器不会把s2的两个()三个()池中的方法,

But in case of method two() and three() , compiler says " i dont know ,may be value of i can be changed any time , or s1.length() changes any time " , its a runtime thing , so compiler doesn't put s2 of two() and three() method in pool ,

因此,它们是假的,因为在运行时,新对象一旦改变就会被创建!!

Hence , they are false because at runtime , new object is created as soon it get changed right !!

这篇关于Java字符串文字串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆