StringBuffer class
In this chapter you will learn:
Why do we need StringBuffer
String
represents fixed-length, immutable character sequences.
StringBuffer
represents growable and writeable character sequences.
StringBuffer
will automatically grow to make room for such additions.
Java manipulate StringBuffers behind the scenes when you are using the overloaded + operator.
Create StringBuffer
StringBuffer()
Creates a string buffer with no characters in it and an initial capacity of 16 characters.StringBuffer(CharSequence seq)
Creates a string buffer that contains the same characters as the specified CharSequence.StringBuffer(int capacity)
Creates a string buffer with no characters in it and the specified initial capacity.StringBuffer(String str)
Creates a string buffer initialized to the contents of the specified string.
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer(20);
System.out.println(sb.capacity());//from ja v a2 s. co m
}
}
The output:
Using new StringBuffer(String str)
public class Main {
/*from j a va2s . c o m*/
public static void main(String[] arg) {
StringBuffer aString = new StringBuffer("ABCDE");
String phrase = "abced";
StringBuffer buffer = new StringBuffer(phrase);
System.out.println(aString);
System.out.println(buffer);
}
}
The followoing code always insert to the start of a StringBuffer
.
public class Main {
public static void main(String args[]) {
Object objectRef = "hello";
String string = "goodbye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'K';
int integerValue = 7;
long longValue = 10000000;
float floatValue = 2.5f;
double doubleValue = 33.3;
/* ja v a 2 s .co m*/
StringBuffer buffer = new StringBuffer();
buffer.insert(0, objectRef);
buffer.insert(0, " ");
buffer.insert(0, string);
buffer.insert(0, " ");
buffer.insert(0, charArray);
buffer.insert(0, " ");
buffer.insert(0, charArray, 3, 3);
buffer.insert(0, " ");
buffer.insert(0, booleanValue);
buffer.insert(0, " ");
buffer.insert(0, characterValue);
buffer.insert(0, " ");
buffer.insert(0, integerValue);
buffer.insert(0, " ");
buffer.insert(0, longValue);
buffer.insert(0, " ");
buffer.insert(0, floatValue);
buffer.insert(0, " ");
buffer.insert(0, doubleValue);
System.out.printf("buffer after inserts:\n%s\n\n", buffer.toString());
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to append to StringBuffer
- How to use the chained append() method
- How to add data in the middle of a StringBuffer
Home » Java Tutorial » String