Detailed examples of Java constant pool

Detailed examples of Java constant pool

The constant pool of java contains a series of constant values such as classes, interfaces, methods and strings. The constant pool is determined during compilation and saved in * Class file

1、 For the same constant value, only one copy is saved in the constant pool.

Moreover, when a string is linked by multiple string constants, multiple strings are composed of one string constant.

For example:

The result is:

Note: the string created by new string() is not a constant and cannot be determined during compilation. Therefore, it cannot be put into the constant pool, but has its own address space.

2、 Constant pools are loaded by the JVM during runtime and can be expanded.

String. The intern () method is a way to expand the constant pool. When an object STR of string calls the intern () method, Java first retrieves whether there are string constants with the same Unicode encoding in the constant pool. If yes, the reference of the string constant is returned; If not, add a string constant with Unicode encoding equal to STR to the constant pool, and return the reference of the string constant.

For example:

The output result is:

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>