· public StringBuffer insert(int offset, String str) inserts the str-referenced String's characters into the current StringBuffer beginning at the index that offset identifies. Any characters starting at offset move upwards. If str contains a null reference, the null character sequence is inserted into the StringBuffer. Example: StringBuffer sb = new StringBuffer ("ab"); sb.insert (1, "cd"); System.out.println (sb); (output: acdb).
· public int length() returns the value stored in count. In other words, this method returns a string's length. If the string is empty, length() returns 0. A StringBuffer's length differs from its capacity; length specifies value's current character count, whereas capacity specifies the maximum number of characters that store in that array. Example: StringBuffer sb = new StringBuffer (); System.out.println (sb.length ()); (output: 0).
· public StringBuffer replace(int start, int end, String str) replaces all characters in the current StringBuffer's value array that range between indexes start and one position less than end (inclusive) with characters from the str-referenced String. This method throws a StringIndexOutOfBoundsException object if start is negative, exceeds the value array's length, or is greater than end. Example: StringBuffer sb = new StringBuffer ("abcdef"); sb.replace (0, 3, "x"); System.out.println (sb); (output: xdef).
· public StringBuffer reverse() reverses the character sequence in the current StringBuffer's value array. Example: StringBuffer sb = new StringBuffer ("reverse this"); System.out.println (sb.reverse ()); (output: siht esrever).
· public void setCharAt(int index, char c) sets the character at position index in the current StringBuffer's value array to c's contents. If index is negative, equals value's length, or exceeds that length, this method throws an IndexOutOfBoundsException object. Example: StringBuffer sb = new StringBuffer ("abc"); sb.setCharAt (0, 'd'); System.out.println (sb); (output: dbc).
· public void setLength(int newLength) establishes a new length for the current StringBuffer's value array. Every character in that array located at an index less than newLength remains unchanged. If newLength exceeds the current length, null characters append to the array beginning at the newLength index. If necessary, StringBuffer expands by creating a new value array of the appropriate length. This method throws an IndexOutOfBoundsException object if newLength is negative. The following fragment demonstrates this method:
StringBuffer sb = new StringBuffer ("abc");
System.out.println (sb.capacity ());
System.out.println (sb.length ());
sb.setLength (100);
System.out.println (sb.capacity ());
System.out.println (sb.length ());
System.out.println ("[" + sb + "]");
The fragment produces this output (in the last line, null characters, after abc, appear as spaces):
19
3
100
100
[abc ]
No comments:
Post a Comment