Java String literals concatenation

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 !!

Leave a Comment