562 Strings and Characters Chapter 10 13 StringBuffer (Web hosting contract)
Friday, November 16th, 2007562 Strings and Characters Chapter 10 13 StringBuffer buffer = 14 new StringBuffer( “Hello, how are you?” ); 15 16 String output = “buffer = ” + buffer.toString() + 17 “nlength = ” + buffer.length() + 18 “ncapacity = ” + buffer.capacity(); 19 20 buffer.ensureCapacity( 75 ); 21 output += “nnNew capacity = ” + buffer.capacity(); 22 23 buffer.setLength( 10 ); 24 output += “nnNew length = ” + buffer.length() + 25 “nbuf = ” + buffer.toString(); 26 27 JOptionPane.showMessageDialog( null, output, 28 “StringBuffer length and capacity Methods”, 29 JOptionPane.INFORMATION_MESSAGE ); 30 31 System.exit( 0 ); 32 } 33 34 } // end class StringBufferCapLen Fig. 10.13 StringBufferlengthand capacitymethods (part 2 of 2). The program contains one StringBuffer called buffer. Lines 13 14 of the program use the StringBufferconstructor that takes a Stringargument to instantiate and initialize the StringBuffer with “Hello, how are you?”. Lines 16 18 append to output the contents, the length and the capacity of the StringBuffer. Notice in the output window that the capacity of the StringBufferis initially 35. Remember that the StringBuffer constructor that takes a String argument creates a StringBuffer object with an initial capacity that is the length of the Stringpassed as an argument plus 16. Line 20 expands the capacity of the StringBufferto a minimum of 75 characters. Actually, if the original capacity is less than the argument, the method ensures a capacity that is the greater of the number specified as an argument or twice the original capacity plus 2. If the StringBuffer s current capacity is more than the specified capacity, the StringBuffer s capacity remains unchanged. Line 23 uses method setLength to set the length of the StringBufferto 10. If the specified length is less than the current number of characters in the StringBuffer, Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01