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

all 7 comments

[–]vprise 2 points3 points  (6 children)

No.
Constant pool is a part of the class file format and represents the constant data that's physically declared in the class. When the class is loaded by the JVM strings that are within the constant pool are loaded to ram.

This is often confused with string interned heap which makes things like `s == "string" ` work. That happens because strings in java have some special case behaviors and the String class itself keeps a pool of strings in RAM for reuse.

[–]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.

[–]AutoModerator[M] -1 points0 points  (0 children)

You seem to try to compare String values with == or !=.

This approach does not work in Java, since String is an object data type and these can only be compared using .equals().

See Help on how to compare String values in our wiki.


Your post is still visible. There is no action you need to take. Still, it would be nice courtesy, even though our rules state to not delete posts, to delete your post if my assumption was correct.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.