Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are string objects when created using tostring methods stored in memory in Java?

Tags:

java

string

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); 
  1. In the constant pool
  2. On the heap (the area of new operator object)
like image 962
Prakruti Pathik Avatar asked Jul 24 '15 10:07

Prakruti Pathik


People also ask

Where are string values stored in memory in Java?

In Java, strings are stored in the heap area.

In which memory string objects are stored?

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.

When we create a string object it is created in which memory?

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.

Where are string objects stored in memory using new keyword?

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.


2 Answers

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.

like image 168
TheLostMind Avatar answered Sep 19 '22 14:09

TheLostMind


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.

like image 21
Jesper Avatar answered Sep 19 '22 14:09

Jesper