I've read this answer about how to check if a string is interned in Java, but I don't understand the following results:
String x = args[0]; // args[0] = "abc";
String a = "a";
String y = a + "bc";
System.out.println(y.intern() == y); // true
But if I declare a string literal:
String x = "abc";
String a = "a";
String y = a + "bc";
System.out.println(y.intern() == y); // false
Besides, without any string literal, the args[0]
seems to be directly interned:
// String x = "abc";
String y = args[0];
System.out.println(y.intern() == y); // true (???)
// false if the first line is uncommented
Why does y.intern() == y
change depending on whether x
is a literal or not, even for the example when the command-line argument is used?
I know literal strings are interned at compile time , but I don't get why it affects in the previous examples. I have also read several questions about string interning, like String Pool behavior , Questions about Java's String pool and Java String pool - When does the pool change? . However, none of them gives a possible explanation to this behaviour.
Edit:
I wrongly wrote that in third example the result doesn't change if String x = "abc";
is declared, but it does.
It is because y.intern()
gives back y
if the string was not interned before. If the string already existed, the call will give back the already existing instance which is most likely different from y
.
However, all this is highly implementation dependent so may be different on different versions of the JVM and the compiler.
Implementation details might differ. But this is exactly the behavior I would expect. Your first case means that commandline arguments are not interned by default. Hence y.intern()
returns the reference to y
after interning it.
The second case is where the VM automatically interns the literal, so that y.intern()
returns the reference to x
, which is different from y
.
And the last case again happens because nothing is interned by default, so the call to intern()
returns the reference to y
. I believe it is legal to intern String more aggressively, but this is the minimal behavior required by the spec as I understand it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.