0

If i write

String s1 = "True";
String s2 = "True";

s1==s2 will return true. During compiletime, as i understand it, a 'String pool' is created, where strings which are created this way ends up. When creating s2 the compiler will check the string pool for said string, and if such string exist, point towards the same one.

String s3 = new String("False");
String s4 = new String("False");

s3==s4 will return false. Objects created with the new command will be created in heap space. So these generates two objects and point towards different strings, despite their ''contents'' being identical. (s3.equals(s4) would return true).

Now, this is what i don't understand.

String s5 = "False";
String sx = ""F";
String s6 = sx + "alse";

this returns false, and i do not understand why. These strings should all be created during compiletime, and end up in the string pool, no? s5 should generate an object in the stringpool, sx should generate an object in stringpool. This i am certain of, but how exactly does s6 create its object?

As i understand it, concatenation of string literals occurs during compiletime, so for example String s1 = "True"; String s2 = "T" + "rue"; s1==s2 returns true, since jvm checks the stringpool for "True".

Thanks!

edit: This question differs because the threads i checked did not address the situation where i first create two strings and create a third one by using one of the two previous reference and another string, such as sx + "alse" above.

Rewbert
  • 347
  • 1
  • 3
  • 11
  • Changed to proper quotes and added why this differs from previous threads i went through. – Rewbert Jan 23 '15 at 15:52
  • 1
    See the first part of the linked question and the second part of the accepted answer. – Sotirios Delimanolis Jan 23 '15 at 15:53
  • Okay i think i understand now. Did not run into that thread while i was searching for my answer. Thanks! – Rewbert Jan 23 '15 at 15:57
  • what you're expecting is a constant folding optimization. But at the moment, the static java compiler javac, is not smart enough to perform this optimization at compile time and the statement String s6 = sx + "alse"; is translated into a string concatenation statement like this **String s6 = new StringBuilder(String.valueOf(sx)).append("alse").toString()**. As your calling new() there, the returned references will never be the same. May be future versions of javac will be embed this trick but now these kind of optimizations are confined to JIT compiler at runtime :) – Arkantos Jan 23 '15 at 17:52

0 Answers0