Reputation: 1112
According to this article ScjpTipLine-StringsLiterally I was coding some examples like :
public static void main(String[] args) {
String literalString1 = "someString";
String literalString2 = "someString";
String string1 = new String("someString");
System.out.println(literalString1 == literalString2);
System.out.println(literalString1 == string1);
try {
Field stringValue = String.class.getDeclaredField("value");
stringValue.setAccessible(true);
char[] charValue = "someString".toCharArray();
Arrays.fill(charValue, 'a');
stringValue.set(literalString1, charValue);
} catch (Exception e) {}
System.out.println(literalString1);
System.out.println(literalString2);
System.out.println(string1);
}
The ouput is the expected :
true
false
aaaaaaaaaa
aaaaaaaaaa
someString
but if you change slightly the code above replacing the line
char[] charValue = "someString".toCharArray();
with
char[] charValue = (char[]) stringValue.get(literalString1);
you get
true
false
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
which is an unexpected output since the new String("someString"); the JVM is obliged to create a new String object on the heap at run-time, rather than using the literalString1 and literalString2 from the string literal pool.
Thanks in advance
Upvotes: 0
Views: 228
Reputation: 60033
which is an unexpected output since the new String("someString"); the JVM is obliged to create a new String object on the heap at run-time
It's obligated to create a new String object, yes.
However, a String object is usually just a header with a few fields, and a pointer to backing array. And the JVM is free to reuse that backing array.
Strings are supposed to be immutable, if you do fiddly things to try and violate that immutability, you don't get any guarantees as to how they're going to behave.
Upvotes: 1