I have a string like below
String empid = str.substring(0,2);
... but this string creates the same space for original string.so memory leak will happen.
I think you are referring to the behavior of
String in older versions of Java where
String.substring(...) created an object that shared the original
String object's backing array. As you point out, that could lead to a memory leak; e.g. if the original string became unreachable and the substring didn't.
The relevant code can be seen here:
This problem was fixed in Java 7.
Prior to Java 7, the standard workaround was to do something like this:
String empid = new String(str.substring(0, 2));
new String(...) creates a string that does not share its backing array with either the original string or the substring.)
However, this is only advisable if: