How the substring() function of String class works..


Consider the following code

String s1 = "Monday";
String s = s1.substring(0,3);
or
s1.substring(0,3).equals("Mon")

substring is clever. It does not make a deep copy of the substring the way most languages do. It just creates a pointer into the original immutable String, i.e. points to the value char[] of the base string, and tracks the starting offset where the substring starts and count of how long the substring is.
The downside of this cleverness is a tiny substring of a giant base String could suppress garbage collection of that big String in memory even if the whole String were no longer needed. (actually its value char[] array is held in RAM; the String object itself could be collected.)
If you know a tiny substring is holding a giant string in RAM, that would otherwise be garbage collected, you can break the bond by using

String s = new String(s1.substring(0,3));

One thought on “How the substring() function of String class works..

  1. 18.11.2012KatqZdraveite,imame ka6ta na dva etaja ,grub stroej do porkiv v s.Beli Iskar..Imame ideq da q prevarnem v ka6ta za gosti no neznaem dali imame pravo i 6ans za nqkakav vid subsidiq po proekt.Blagodarq za otdelenoto vreme.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s