Say I have a function that takes in a string argument like
func("abc")
Will "abc"
be interned (stored in string pool)? If func("abc")
will be called a billion times, will java create a billion copies of "abc" string objects in the pool?
Say I have a function that takes in a string argument like
func("abc")
Will "abc"
be interned (stored in string pool)? If func("abc")
will be called a billion times, will java create a billion copies of "abc" string objects in the pool?
No. In string pool only one copy will be created and all variable which have same string value, will be pointed to that copy.
You can see below diagram for more clarity:
https://cdn.journaldev.com/wp-content/uploads/2012/11/String-Pool-Java1.png
Yes, "abc" will be stored in string pool. A new string is not created unless you explicitly create one with new
operator.
It is not recommended to force creation of new object. But even when you do, it doesn't lead to memory leak as the new object is bound to certain scope and will be garbage collected when it is no longer referenced
From the Java SE 13 docs, please read the following excerpt:
A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).
Moreover, a string literal always refers to the same instance of class String. This is because 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 (§12.5).
String "interning" in Java is storing a String object in a pool so that multiple copies of a string literal in your code refer to the same String object, instead of multiple 'identical' String objects. Perhaps, the following example will clarify it a bit more:
String hello = "Hello"; //A new String object with the value "Hello" is created in the String pool; the variable hello references that object in the pool
System.out.println(hello == "Hello"); //prints true
So in your case, even if you keep calling the method func
billion times with the same String literal, only 1 String object with the value 'abc' exists in the pool and all the literals "abc" reference the same object.
for (long i = Integer.MAX_VALUE; i <= Integer.MAX_VALUE; i++)
func("abc"); //Only 1 String object is created
However, if you explicitly create new String objects from a literal, you might end up having multiple String objects with the same value in the memory until the ones not in context are garbage collected.
for (long i = Integer.MAX_VALUE; i <= Integer.MAX_VALUE; i++)
func(new String("abc")); //multiple String objects with the same value are created and will continue to exist until garbage collected.