Madhesh Madhesh - 1 month ago 14
Java Question

Best way to get part of content from string in java

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!!!

Answer

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