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?
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.
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.
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.
StringBuffer never adds to the string pool.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With