2

I have a string like below

12SELVASOFTWAREENGINEER................323

This string length is more than 10000

First two letter of this string is employee Id

So i can get my employee id like below

String empid = str.substring(0,2);

but this string creates the same space for original String, so memory leak will happen.

How to avoid this?

Is their any alternative or efficient way is their for getting the part of the string in java

Any help will be greatly appreciated!!!

Nicolas Filotto
  • 41,524
  • 11
  • 90
  • 115
Madhesh
  • 1,508
  • 1
  • 27
  • 53

3 Answers3

5

... 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)); 

(The 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:

  • you are using an old release of Java,
  • the original string is likely to be large, and
  • the substring is likely to be long-lived.
Stephen C
  • 669,072
  • 92
  • 771
  • 1,162
1

If you intend to keep in memory your original String, using str.substring(0,2) can still be used as it will only reuse the backing array of your original String so it won't affect your memory footprint.

However if you intend to get rid of your original String and want to consume less memory, then you could build a new String instance from the first (charAt(0)) and the second (charAt(1)) character of your original String as next:

String sub = new String(new char[]{s.charAt(0), s.charAt(1)});
Nicolas Filotto
  • 41,524
  • 11
  • 90
  • 115
1

This should work perfectly well:

String orig = "12SELVASOFTWAREENGINEER................323";

String empId = orig.substring(0, 2);

Why should there be a memory leak?

If you mean the memory that's held by orig, you can reset orig afterwards like so:

orig = null;

This will allow the long string to be collected by the garbage collector. The empId will still keep its value - in case you might fear that it gets cleared as well.

Ridcully
  • 23,014
  • 7
  • 67
  • 82