Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out that given String is already in Java String pool?

Tags:

java

Is there any method or technique how to know that given String s is already in the String pool? How and when is Java String pool creating? What does initial members it contain?

like image 909
angry_gopher Avatar asked Apr 30 '13 18:04

angry_gopher


People also ask

Is String object stored in String pool?

The first string gets stored in the String Constant Pool, but the second string object gets stored out of the string pool in the Java heap memory. Here is the memory representation of the same.

How many String objects are created in the String pool?

The answer is: 2 String objects are created. str and str2 both refer to the same object. str3 has the same content but using new forced the creation of a new, distinct, object.

Does new String create object in String pool?

When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists.

Would the StringBuffer store its String in String pool?

StringBuffer never adds to the string pool.


1 Answers

My answer is: there is no general solution to that. What you can do is:

boolean wasAlreadyInterned = str.intern() == str;

but this has the side-effect, that now it is interned for sure.

JavaDoc of String#intern says, that the class String privately maintains a pool of strings, that is initially empty.

If you look at the implementation of the class String all you see is

public native String intern();

The Java Language Specification, Chapter 3.10.5, String literals says:

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.

like image 64
jlordo Avatar answered Sep 28 '22 08:09

jlordo