Reputation: 8346
I am trying to understand the string constant pool, how string literal objects are managed in constant pool, i am not able to understand why I am getting false
from below code 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
}
Upvotes: 7
Views: 162
Reputation: 1500065
The expression "abc" + "d"
is a constant expression, so the concatenation is performed at compile-time, leading to code equivalent to:
String s1 = "abc";
String s2 = "abcd";
String s3 = "abcd";
String s4 = s1 + "d";
The expression s1 + "d"
is not a constant expression, and is therefore performed at execution time, creating a new string object. Therefore although s2
and s3
refer to the same string object (due to constant string interning), s2
and s4
refer to different (but equal) string objects.
See section 15.28 of the JLS for more details about constant expressions.
Upvotes: 12
Reputation: 4075
s2
is created at compile-time. Memory is reserved for it and populated accordingly.
s1 + "d"
is evaluated at runtime. Because you are using two different strings (ie. s1
is a variable which could in theory be anything) the compiler cannot know in advance that you do not intend to change the value of the object reference.
Hence, it must allocate the memory dynamically.
Upvotes: 0