8.7. The File Class

 
[Page 273 ( continued )]

8.4. The StringBuilder/StringBuffer Class

The StringBuilder / StringBuffer class is an alternative to the String class. In general, a StringBuilder / StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String . You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.

The StringBuilder class, introduced in JDK 1.5, is similar to StringBuffer except that the update methods in StringBuffer are synchronized. Use StringBuffer if it may be accessed by multiple tasks concurrently. Using StringBuilder is more efficient if it is accessed by a single task. The constructors and methods in StringBuffer and StringBuilder are almost the same. This section covers StringBuffer . You may replace StringBuffer by StringBuilder . The program can compile and run without any other changes.

The StringBuffer class has three constructors and more than thirty methods for managing the buffer and modifying strings in the buffer. You can create an empty string buffer or a string buffer from a string. The most frequently used methods are listed in Figure 8.8.

Figure 8.8. The StringBuffer class provides the methods for processing a string buffer.


[Page 274]

8.4.1. Modifying Strings in the Buffer

You can append new contents at the end of a string buffer, insert new contents at a specified position in a string buffer, and delete or replace characters in a string buffer.

The StringBuffer class provides several overloaded methods to append boolean , char , char array , double , float , int , long , and String into a string buffer. For example, the following code appends strings and characters into strBuf to form a new string, "Welcome to Java" .

 StringBuffer strBuf =   new   StringBuffer(); strBuf.append(   "Welcome"   ); strBuf.append(   ' '   ); strBuf.append(   "to"   ); strBuf.append(   ' '   ); strBuf.append(   "Java"   ); 

The StringBuffer class also contains overloaded methods to insert boolean , char , char array , double , float , int , long , and String into a string buffer. Consider the following code:

 strBuf.insert(   11   ,   "HTML and "   ); 

Suppose strBuf contains "Welcome to Java" before the insert method is applied. This code inserts "HTML and " at position 11 in strBuf (just before J ). The new strBuf is "Welcome to HTML and Java" .

You can also delete characters from a string in the buffer using the two delete methods, reverse the string using the reverse method, replace characters using the replace method, or set a new character in a string using the setCharAt method.

For example, suppose strBuf contains "Welcome to Java" before each of the following methods is applied:

 strBuf.delete(   8   ,   11   ) changes the buffer to   Welcome Java   . strBuf.deleteCharAt(   8   ) changes the buffer to   Welcome o Java   . strBuf.reverse() changes the buffer to   avaJ ot emocleW   . strBuf.replace(   11   ,   15   ,   "HTML"   ) changes the buffer to   Welcome to HTML   . strBuf.setCharAt(     ,   'w'   ) sets the buffer to   welcome to Java   . 

Note

All these modification methods except setCharAt do two things: (1) change the contents of the string buffer, (2) return the reference of the string buffer. For example, the following statement

 StringBuffer strBuf1 = strBuf.reverse(); 

reverses the string in the buffer and assigns the reference of the buffer to strBuf1 . Thus strBuf and strBuf1 both point to the same StringBuffer object. Recall that a method with nonvoid return value type may be invoked as a statement if you are not interested in the return value of the method. In this case, the return value is simply ignored. For example, in the following statement

 strBuf.reverse(); 

the return value is ignored.


Tip

If a string does not require any change, use String rather than StringBuffer . Java can perform some optimizations for String , such as sharing interned strings.



[Page 275]

8.4.2. The toString , capacity , length , setLength , and charAt Methods

The StringBuffer class provides many other methods for manipulating string buffers.

  • The toString() method returns the string from the string buffer.

  • The capacity() method returns the current capacity of the string buffer. The capacity is the number of characters it is able to store without having to increase its size .

  • The length() method returns the number of characters actually stored in the string buffer.

  • The setLength(newLength) method sets the length of the string buffer. If the newLength argument is less than the current length of the string buffer, the string buffer is truncated to contain exactly the number of characters given by the newLength argument. If the newLength argument is greater than or equal to the current length, sufficient null characters ( '\u0000' ) are appended to the string buffer so that length becomes the newLength argument. The newLength argument must be greater than or equal to .

  • The charAt(index) method returns the character at a specific index in the string buffer. The first character of a string buffer is at index , the next at index 1 , and so on. The index argument must be greater than or equal to , and less than the length of the string buffer.

Note

The length of the string is always less than or equal to the capacity of the buffer. The length is the actual size of the string stored in the buffer, and the capacity is the current size of the buffer. The buffer's capacity is automatically increased if more characters are added to exceed its capacity. Internally, a string buffer is an array of characters, so the buffer's capacity is the size of the array. If the buffer's capacity is exceeded, the array is replaced by a new array. The new array size is 2 * (the previous array size + 1) .


Tip

You can use new StringBuffer(initialCapacity) to create a StringBuffer with a specified initial capacity . By carefully choosing the initial capacity, you can make your program more efficient. If the capacity is always larger than the actual length of the buffer, the JVM will never need to reallocate memory for the buffer. On the other hand, if the capacity is too large, you will waste memory space.


8.4.3. Example: Ignoring Nonalphanumeric Characters When Checking Palindromes

Listing 8.1, CheckPalindrome.java, considered all the characters in a string to check whether it was a palindrome. Write a new program that ignores nonalphanumeric characters in checking whether a string is a palindrome . A sample run of the program is shown in Figure 8.9.

Figure 8.9. The program checks whether a string is a palindrome, ignoring nonalphanumeric characters.
(This item is displayed on page 277 in the print version)

Here are the steps to solve the problem:

1.
Filter the string by removing the nonalphanumeric characters. This can be done by creating an empty string buffer, adding each alphanumeric character in the string to a string buffer, and returning the string from the string buffer. You can use the isLetterOrDigit(ch) method in the Character class to check whether character ch is a letter or a digit.

2.
Obtain a new string that is the reversal of the filtered string. Compare the reversed string with the filtered string using the equals method.


[Page 276]

The complete program is shown in Listing 8.3.

Listing 8.3. PalindromeIgnoreNonAlphanumeric.java
 1   import   javax.swing.JOptionPane;  2  3   public class   PalindromeIgnoreNonAlphanumeric {  4  /** Main method */  5   public static void   main(String[] args) {  6  // Prompt the user to enter a string  7     String s = JOptionPane.showInputDialog(   "Enter a string:"   );  8  9  // Declare and initialize output string  10     String output =   "Ignoring nonalphanumeric characters, \nis "   11       + s +   " a palindrome? "   + isPalindrome(s); 12 13  // Display the result  14     JOptionPane.showMessageDialog(   null   , output); 15   } 16 17  /** Return true if a string is a palindrome */  18    public static boolean   isPalindrome(String s) {  19  // Create a new string by eliminating nonalphanumeric chars  20     String s1 = filter(s); 21 22  // Create a new string that is the reversal of s1  23     String s2 = reverse(s1); 24 25  // Compare if the reversal is the same as the original string  26   return   s2.equals(s1); 27   } 28 29  /** Create a new string by eliminating nonalphanumeric chars */  30   public static   String filter(String s) { 31  // Create a string buffer  32  StringBuffer strBuf =   new   StringBuffer();  33 34  // Examine each char in the string to skip alphanumeric char  35   for   (   int   i =     ; i <  s.length()  ; i++) { 36   if   (  Character.isLetterOrDigit(s.charAt(i))  ) { 37  strBuf.append(s.charAt(i));  38       } 39     } 40 41  // Return a new filtered string  42   return   strBuf.toString(); 43   } 44 45  /** Create a new string by reversing a specified string */  46   public static   String reverse(String s) { 47     StringBuffer strBuf =   new   StringBuffer(s); 48  strBuf.reverse();   // Use the reverse method for StringBuffer object  49   return   strBuf.toString(); 50   } 51 } 

The filter(String s) method (lines 30 “43) examines each character in string s and copies it to a string buffer if the character is a letter or a numeric character. The filter method returns the string in the buffer. The reverse(String s) method (lines 46 “50) creates a new string that reverses the specified string s . The filter and reverse methods both return a new string. The original string is not changed.


[Page 277]

The program in Listing 8.1 checks whether a string is a palindrome by comparing pairs of characters from both ends of the string. Listing 8.3 uses the reverse method in the StringBuffer class to reverse the string, then compares whether the two strings are equal to determine whether the original string is a palindrome.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net