I was doing one assignment, and I got this following question.
Where are the string objects created with the toString()
method stored in memory?
String a = Integer.toString(10);
In Java, strings are stored in the heap area.
String objects created with new operator are stored in the heap memory area and there is no sharing of storage for the same contents of different string objects.
2. Using new keyword. We can create new String objects using the new keyword. When we create new string literals using the new keyword, memory is allocated to those String objects in the Java heap memory outside the String Pool.
Whenever you create a string object using string literal, that object is stored in the string constant pool and whenever you create a string object using new keyword, such object is stored in the heap memory.
They all go into the heap memory. Only String literals and interned strings go into the String constants pool.
The only exceptions are classes like String
:
public String toString() { return this; }
It just returns the current string (if it is on heap, it returns from the heap / if it is on string constants pool, it returns from the string constants pool)
Note : If toString()
is NOT overridden to return a String Literal explicitly, the String representation (ClassName@hexValueOfHashCode) is always created on the heap.
It depends on the implementation of the toString()
method that you are calling.
The toString()
method creates the String
object, so depending on how it does this (and whether it interns the string or not), the returned String
will be in the string pool or not.
Note that toString()
is just a method like any other method. There is no magic that handles the return value of the toString()
method in any special way. (Strings returned by toString()
are, for example, not interned automatically). It works in exactly the same way as with any other method that returns a String
.
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