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
}
Java String literal is created by using double quotes.
In Java, strings are stored in the heap area. Why Java strings stored in Heap, not in Stack? String Literal is created by using a double quote.
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character.
The answer is: 2 String objects are created. str and str2 both refer to the same object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With