Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

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

Explore Character, String, StringBuffer, and StringTokenizer

  • Print
  • Feedback

Page 9 of 10

String s = "abc";
String t = "def";
String u = "";
for (int i = 0; i < 100000; i++)
     u = u.concat (s).concat (t);


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.

Create a StringBuffer object via any of the following constructors:

  • public StringBuffer() creates a new StringBuffer object that contains no characters but can contain up to 16 characters before automatically expanding. StringBuffer has an initial capacity of 16 characters.
  • public StringBuffer(int initCap) creates a new StringBuffer that contains no characters and up to initCap characters before automatically expanding. If initCap is negative, this constructor throws a NegativeArraySizeException object. StringBuffer has an initial capacity of initCap.
  • public StringBuffer(String str) creates a new StringBuffer that contains all characters in the str-referenced String and up to 16 additional characters before automatically expanding. StringBuffer's initial capacity is the length of str's string plus 16.


The following code fragment demonstrates all three constructors:

StringBuffer sb1 = new StringBuffer ();
StringBuffer sb2 = new StringBuffer (100);
StringBuffer sb3 = new StringBuffer ("JavaWorld");


StringBuffer sb1 = new StringBuffer (); creates a StringBuffer with no characters and an initial capacity of 16. StringBuffer sb2 = new StringBuffer (100); creates a StringBuffer with no characters and an initial capacity of 100. Finally, StringBuffer sb3 = new StringBuffer ("JavaWorld"); creates a StringBuffer containing JavaWorld and an initial capacity of 25.

StringBuffer method sampler

Since we already examined StringBuffer's constructor methods, we now examine the nonconstructor methods. For brevity, I focus on only 13 methods.

Note
Like String, many StringBuffer methods require an index argument for accessing a character in the StringBuffer's value array (or a character array argument). That index/offset is always zero-based.


  • public StringBuffer append(char c) appends c's character to the contents of the current StringBuffer's value array and returns a reference to the current StringBuffer. Example: StringBuffer sb = new StringBuffer ("abc"); sb.append ('d'); System.out.println (sb); (output: abcd).
  • public StringBuffer append(String str) appends the str-referenced String's characters to the contents of the current StringBuffer's value array and returns a reference to the current StringBuffer. Example: StringBuffer sb = new StringBuffer ("First,"); sb.append (" second"); System.out.println (sb); (output: First, second).
  • public int capacity() returns the current StringBuffer's current capacity (that is, value's length). Example: StringBuffer sb = new StringBuffer (); System.out.println (sb.capacity ()); (output: 16).
  • public char charAt(int index) extracts and returns the character at the index position in the current StringBuffer's value array. This method throws an IndexOutOfBoundsException object if index is negative, equals the string's length, or exceeds that length. Example: StringBuffer sb = new StringBuffer ("Test string"); for (int i = 0; i < sb.length (); i++) System.out.print (sb.charAt (i)); (output: Test string).
  • public StringBuffer deleteCharAt(int index) removes the character at the index position in the current StringBuffer's value array. If index is negative, equals the string's length, or exceeds that length, this method throws a StringIndexOutOfBoundsException object. Example: StringBuffer sb = new StringBuffer ("abc"); sb.deleteCharAt (1); System.out.println (sb); (output: ac).
  • public void ensureCapacity(int minimumCapacity) ensures the current StringBuffer's current capacity is larger than minimumCapacity and twice the current capacity. If minimumCapacity is negative, this method returns without doing anything. The following code demonstrates this method:

    StringBuffer sb = new StringBuffer ("abc"); 
    System.out.println (sb.capacity ()); 
    sb.ensureCapacity (20);
    System.out.println (sb.capacity ());
    


    The fragment produces the following output:

  • Print
  • Feedback

Resources