title: How to use less memory when assign big new String
body: <p>Java String is immutable so </p>
  
  <p>when you create a string, a block of memory is assigned for it in the heap, and when you change its value, a new block of memory is created for that string, and the old one becomes eligible for garbage collection, for example</p>
  
  <pre><code>String str = func1_return_big_string_1()"; //not literal
  String str= func2_return_big_string_2()"; //not literal
  </code></pre>
  
  <p>But as garbage collection takes time to kick in so we are practically have memory in heap containing both big string 1 &amp; 2. They can be a issue for me if this happens a lot.</p>
  
  <p>Is there a way to make big string 2 to use the same location in memory of string 1 so we don't need have extra space when we assign big string 2 to str.</p>
  
  <p>Edit:
  Thanks for all the input and in the end I realized I shouldn't expecting java code to behave like c++ code(i.e, different memory footprint). I have wrote a c++ 11 demo which works as expected, biggest memory footprint is around 20M (biggest file I was trying to load) with rvalue reference and move assignment operator all kick in as expected.
  Below demo done in VS2012 with c++ 11.</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;vector&gt;
  #include &lt;fstream&gt;
  #include &lt;thread&gt;
  using namespace std;
  
  string readFile(const string &amp;fileName)
  {
      ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
  
      ifstream::pos_type fileSize = ifs.tellg();
      ifs.seekg(0, ios::beg);
  
      vector&lt;char&gt; bytes(fileSize);
      ifs.read(&amp;bytes[0], fileSize);
  
      return string(&amp;bytes[0], fileSize);
  }
  
  class test{
  public:
      string m_content;
  };
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      string base("c:\\data");
      string ext(".bin");
      string filename;
      test t;
      //std::this_thread::sleep_for(std::chrono::milliseconds(5000));
      cout &lt;&lt; "about to start" &lt;&lt; endl;
      for(int i=0; i&lt;=50; ++i) {
          cout &lt;&lt; i &lt;&lt; endl;
          filename = base + std::to_string(i) + ext;
          //rvalue reference &amp; move assignment operator here
          //so no unnecessary copy at all
          t.m_content = readFile(filename);
          cout &lt;&lt; "szie of content" &lt;&lt; t.m_content.length() &lt;&lt; endl;
      }
      cout &lt;&lt; "end" &lt;&lt; endl;
      system("pause");
      return 0;
  }
  </code></pre>