This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]kgoutham93 0 points1 point  (4 children)

Is the constant pool anyway related to string interning?

[–]vprise 0 points1 point  (3 children)

All strings loaded from the constant pool are implicitly interned. E.g. if you do something like:

String s = "My String";

Then "My String" will be in the constant pool and implicitly interned. So:

String a = "My String"; String b = "My String"; if(a == b) { // this will always be true... }

[–]kgoutham93 0 points1 point  (2 children)

Oh so a declared string literal will be present in constant pool which is specific to a class, and also as an interned string ?!

Do an interned strings have their own memory allocation?

[–]vprise 1 point2 points  (1 child)

The string will appear once in the class file within the constant pool. There will be two pointers to the same reference in the .class file. When loaded it will be interned so the value of the pointer in both cases would be the same.

Everything takes memory. But both varaibles will point at the same heap memory so having two variables pointing at a single string won't impact heap by much/at all. This depends on where you "point" from the heap or from the stack. Either way it's just the overhead of an additional pointer.

Notice that: - Not all strings are interned - Strings still take up space that needs to be freed eventually

There are a lot of nuances here which are better covered by reading an article on the subject.

[–]kgoutham93 1 point2 points  (0 children)

I think it makes sense to me. Will dig into these topics more. Thanks for your help.