Java String is immutable so
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
String str = func1_return_big_string_1()"; //not literal
String str= func2_return_big_string_2()"; //not literal
But as garbage collection takes time to kick in so we are practically have memory in heap containing both big string 1 & 2. They can be a issue for me if this happens a lot.
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.
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.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <thread>
using namespace std;
string readFile(const string &fileName)
{
    ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
    ifstream::pos_type fileSize = ifs.tellg();
    ifs.seekg(0, ios::beg);
    vector<char> bytes(fileSize);
    ifs.read(&bytes[0], fileSize);
    return string(&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 << "about to start" << endl;
    for(int i=0; i<=50; ++i) {
        cout << i << endl;
        filename = base + std::to_string(i) + ext;
        //rvalue reference & move assignment operator here
        //so no unnecessary copy at all
        t.m_content = readFile(filename);
        cout << "szie of content" << t.m_content.length() << endl;
    }
    cout << "end" << endl;
    system("pause");
    return 0;
}
 
     
     
     
    