Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

Java String literals concatenation

    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);
    }

Output is

true 
false 
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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

So at Compile time , compiler says "oh yeah , they are calculated as same value , i must assign the same reference to s1 and 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 !!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...