How many Strings are getting created with new operator.
let say I am creating a string with new operator.
String str = new String("Cat")
Will it create 2 strings one in heap and other one is in string pool?
if it creates string in string poll as well then what is the purpose of string intern method ?
How many objects?
When you write
"Cat", you end up populating the pool withCatand the"Cat"call loads this object from the pool. This typically happens already at compile time. Thennew String(...)will create a new string object, ignoring the pool completely.So this snippet leads to the creation of two objects. To clear up your confusion, consider the following example:
Here, two objects are created as well. All the
"Cat"calls will load the string out of the pool, sofirst == second == thirdandfourthwill be its own object since it usednew, which always leads to a creation of a new object, bypassing any sort of caching mechanisms.Whether the objects are created on the heap or stack is not really defined. Memory management is totally up to the JVM.
String pool details
For most of Java implementations, the string pool is created and populated already during compilation. When you write
"Cat", the compiler will put a string object representingCatinto this pool and the"Cat"in your code will be replaced by loading this object from the pool. You can see this easily when you disassemble a compiled program. For example, source code:disassembly (
javap -v):As you see, there is
and the section in the method is replaced by
which loads
Hello Worldfrom the string pool.String interning
Well, it gives you the possibility to swap out your string against the version from the pool. And to populate the pool with your string in case it did not exist there before. For example:
Use case
I have not seen a real world application for this feature yet though.
However, I could think of an use-case where you create, possibly long strings dynamically in your application and you know that they will re-occur later again. Then you can put your strings into the pool in order to trim down the memory footprint when they occur again later on.
So lets say you receive some long strings from HTTP responses and you know that the responses, most of the time, are the exact same and you also want to collect them in a
List:Without interning, you would end up keeping each string instance, including duplicates, alive in your memory. If you intern them however, you would not have duplicate string objects in memory:
Of course, this is a bit contrived as you could also just use a
Setinstead here.