Saturday, December 17, 2011

Java's character and assorted string classes support text-processing - 17


u.concat (s) creates a String containing the u-referenced String's characters followed by the s-referenced String's characters. The new String's reference subsequently returns and identifies a String, named a to prevent confusion, on which concat (t) is called. The concat (t) method call results in a new String object, b, that contains a's characters followed by the t-referenced String's characters. a is discarded (because its reference disappears) and b's reference assigns to u (which results in u becoming eligible for garbage collection).
During each loop iteration, two Strings are discarded. By the loop's end, assuming garbage collection has not occurred, 200,000 Strings that occupy around 2,000,000 bytes await garbage collection. If garbage collection occurs during the loop, this portion of a program's execution takes longer to complete. That could prove problematic if the above code must complete within a limited time period. The StringBuffer class solves this problem.
StringBuffer objects
In many ways, the java.lang.StringBuffer class resembles its String counterpart. For example, as with String, a StringBuffer object stores a character sequence in a character array that StringBuffer's private value field variable references. Also, StringBuffer's private count integer field variable records that array's character number. Finally, both classes declare a few same-named methods with identical signatures, such as public int indexOf(String str).
Unlike String objects, StringBuffer objects represent mutable, or changeable, strings. As a result, a StringBuffer method can modify a StringBuffer object. If the modification produces more characters than value can accommodate, the StringBuffer object automatically creates a new value array with double the capacity (plus two additional array elements) of the current value array, and copies all characters from the old array to the new array. (After all, Java arrays have a fixed size.) Capacity represents the maximum number of characters a StringBuffer's value array can store.

No comments: