How are string literals created?

I am trying to understand a pool of string constants, how string literals are managed in a constant pool, I cannot understand why I get false from the code below, where s2 == s4

  public static void main(String[] args) { String s1 = "abc"; String s2 = "abcd"; String s3 = "abc" +"d"; String s4 = s1 + "d"; System.out.println(s2 == s3); // OP: true System.out.println(s2 == s4); // OP: false } 
+7
source share
2 answers

The expression "abc" + "d" is a constant expression, so concatenation is performed at compile time, which leads to the code equivalent:

 String s1 = "abc"; String s2 = "abcd"; String s3 = "abcd"; String s4 = s1 + "d"; 

The expression s1 + "d" not a constant expression and therefore is executed at run time, creating a new string object. Therefore, although s2 and s3 refer to the same string object (due to the constant internment of strings), s2 and s4 refer to different (but equal) string objects.

For more information on constant expressions, see JLS Section 15.28 .

+12
source

s2 is created at compile time. The memory is reserved for it and populated accordingly.

s1 + "d" is evaluated at runtime. Since you are using two different lines (i.e. s1 is a variable that could theoretically be something), the compiler cannot know in advance that you are not going to change the value of the object reference.

Therefore, it must allocate memory dynamically.

0
source

All Articles