1

I referred to a few posts on Stackoverflow and other sites about Java string pool.

So, when we do:

String s1 = "Emilia";

It creates a string object in the string pool. [Assumming we started from an empty string pool]

Now when we do,

String s2 = "Emilia";

How does java assign the same object reference to s2 also?

Does it iterate through all the string pool objects and compare the value? I suppose there should be a better approach for this.

Bhargav Jhaveri
  • 2,123
  • 1
  • 18
  • 23
  • 3
    The whole point of a spec is that you don't need to know how it's implemented. Unless there is further specification somewhere, each compiler is free to decide how it wants to do it. I usually imagine a HashMap in my head, but that's just an abstraction that yields the same result without any real knowledge of what the compiler is doing. Your suggested method is a perfectly valid way to implement string caching, but I imagine no one uses it in practice because it is quite inefficient. – Mad Physicist Apr 21 '17 at 21:47
  • I am voting to close this as "Too Broad" because a real answer would have to be a survey of existing compilers as well as a tutorial on the theory behind their choices to be complete. – Mad Physicist Apr 21 '17 at 21:49
  • @MadPhysicist The actual string pool is implemented by the runtime classloader, not the compiler. It's implemented by `String.intern` (which is a native method). – 4castle Apr 21 '17 at 22:01
  • @4castle. True. But the decision to intern literals is carried out by the compiler. – Mad Physicist Apr 21 '17 at 22:05
  • 2
    @MadPhysicist The compiler is required to generate bytecode which will instruct the classloader to intern the string literal, but "each compiler is free to decide how it wants to do it" should instead be "each classloader is free to decide how it wants to do it", because the compiler is required to follow the bytecode specification. The compiler doesn't have any implementation freedom in how it interns the string, because it doesn't actually do the interning. – 4castle Apr 21 '17 at 22:11
  • @4castle. I am not disagreeing with you. I am just pointing out that my argument applies as much to the classloader as it would to the compiler if it was the one doing it. – Mad Physicist Apr 21 '17 at 22:14

0 Answers0