Note that this 'space saving' trick can turn its head against you; have a look at the following code snippet:
-
String humongous= ... ; // an extremely big String
-
String small= humongous.substring(0, 1): // a very small String
-
humongous= null; // free the big one?
-
The substring() method shares its char[] buffer with the String for which it is a substring and the entire String buffer can not be garbage collected. Line two from the above code snippet had better written as:
-
String small= new String(humongous.substring(0, 1));
-
The String constructor guarantees that a new char[] buffer will be used.
kind regards,
Jos