I was curious as to why Strings can be created without a call to new String()
, as the API mentions it is an Object
of class
java.lang.String
So how are we able to use String s="hi"
rather than String s=new String("hi")
?
This post clarified the use of ==
operator and absence of new
and says this is due to String
literals being interned or taken from a literal pool by the JVM
, hence Strings
are immutable.
On seeing a statement such as
String s="hi"
for the first time what really takes place ?
Does the JVM
replace it like this String s=new String("hi")
, wherein an Object is created and "hi"
is added to the String literal pool and so subsequent calls such as String s1="hi"
are taken from the pool?
Is this how the underlying mechanism operates? If so, then is
String s=new String("Test"); String s1="Test";
the same as
String s="Test"; String s1="Test";
in terms of memory utilization and efficiency?
Also, is there any way by which we can access the String Pool to check how many String
literals are present in it, how much space is occupied, etc.?
How Does String pool work in Java? JVM automatically checks if the same value exists in the string constant pool or not. if yes, it occupies the already existing value. If no, it creates a new string by itself and adds it to the string pool.
String pool is an example of the Flyweight Design Pattern.
As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.
The Java string constant pool is an area in heap memory where Java stores literal string values. The heap is an area of memory used for run-time operations.
The Java compiler has special support for string literals. Suppose it did not, then it would be really cumbersome to create strings in your source code, you'd have to write something like:
// Suppose that we would not have string literals like "hi" String s = new String(new char[]{ 'h', 'i' });
To answer your questions:
More or less, and if you really want to know the details, you'd have to study the source code of the JVM, which you can find at OpenJDK, but be warned that it's huge and complicated.
No, those two are not equivalent. In the first case you are explicitly creating a new String
object:
String s=new String("Test");
which will contain a copy of the String
object represented by the literal "Test"
. Note that it is never a good idea to write new String("some literal")
in Java - strings are immutable, and it is never necessary to make a copy of a string literal.
There's no way I know of to check what's in the string pool.
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