|
|
The java.lang Package Certification - StringBuffer Class
- used to modify or manipulate the contents of a string
- StringBuffer objects are NOT implicitly created; the following will not compile
StringBuffer sb = "Hello";
StringBuffer sb = { "Hello" };
public StringBuffer(int capacity)
public synchronized void ensureCapacity(int minimum)
public int capacity()
public int length()
public void setLength(int newLength)
- the String methods which return a new object ie concat(), replace(), etc actually use StringBuffer behind the scenes to make the modifications and then returns the final String using toString(). For example, the following code (JJ pg 208)
String s = "";
s = s + "a" + "b";
- is treated, by the compiler, as something similar to
String s = "";
s = new StringBuffer("").append("a").append("b").toString();
- the StringBuffer class does not inherit from String
- to use a StringBuffer object as a parameter to a method requiring a String, use the StringBuffer toString() method. For example, to print the result of a StringBuffer object manipulation
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb.toString() );
- StringBuffer has overloaded append() and insert() methods to convert any type, including Object and character arrays, to a String; both methods return the original StringBuffer object
- the reverse() method returns the original StringBuffer object with the characters in reverse order
- you can access and modify specific characters or a range of characters
public char charAt(int index)
public void setCharAt(int index, char ch)
public StringBuffer replace(int start, int end, String str)
public StringBuffer deleteCharAt(int index)
public StringBuffer delete(int start, int end)
Note: the subString() method returns a String
public String subString(int start)
public String subString(int start, int end)
- there are no methods to remove part of a buffer; you need to create a character array and build a new buffer with the portion of the array you're interested in;
this can be done using
public void getChars(int srcBegin, int srcEnd,
char dst[], int dstBegin)
Example Code
|