Re: how actually string store in java machine
On 3/26/2014 11:32 AM, markspace wrote:
On 3/25/2014 7:37 PM, Roedy Green wrote:
On Tue, 25 Mar 2014 20:31:50 +0100, Jan Burse <janburse@fastmail.fm>
wrote, quoted or indirectly quoted someone who said :
http://stackoverflow.com/questions/16690815/shared-constant-pool
I was under the impression all string constants lived in the same pool
along with the interned strings. That would imply a shared constant
pool since day 1. Have I had this wrong since Java 1.0?
Yes, I'm pretty sure you've been wrong if that's what you thought. Each
class has its own pool of strings. If you have a class with a constant
string:
String a = "a";
String b = "a";
The constant "a" is only stored once, and a==b will be true. But that's
only for a single class file. Outside of the class file, each string is
unique and a different object. I don't think any implementations of the
JVM called String.intern() for each constant string read in each class
file.
// Foo.java:
public class Foo {
public static String HELLO = "Hello";
}
// FooBar.java:
public class FooBar {
public static void main(String[] unused) {
System.out.println("Foo.HELLO == \"Hello\": "
+ (Foo.HELLO == "Hello"));
}
}
.... prints
Foo.HELLO == "Hello": true
.... on my Java 1.7.0_51 system. You might also want to re-read
Section 3.10.5 of the Java Language Specification; for Java 7 and 8
it reads (in part)
"Moreover, a string literal always refers to the /same/
instance of class String. This is because string literals -
or, more generally, strings that are the values of constant
expressions (?15.28) - are "interned" so as to share unique
instances, using the method String.intern."
Java 6 words it a bit differently:
"String literals-or, more generally, strings that are the
values of constant expressions (?15.28)-are "interned" so
as to share unique instances, using the method String.intern."
.... and goes on to give a multi-class, multi-package example.
And certainly if you read a string from a file or the network, the VM
does not call String.intern() for you. That would be silly.
That would be silly, yes. But the handling of literals is
a different matter, and does not behave as you described.
--
Eric Sosman
esosman@comcast-dot-net.invalid