Java StringBuffer class is used to create mutable String objects. The StringBuffer class in Java is the same as String class except it is mutable (it can be changed).
Important Constructors of StringBuffer Class
Constructor | Description |
StringBuffer() | It creates an empty String buffer with the initial capacity of 16. |
StringBuffer(String str) | It creates a String buffer with the specified string.. |
StringBuffer(int capacity) | It creates an empty String buffer with the specified capacity as length. |
Creating a StringBuffer Object
Creating string buffer object using StrigBuffer class and also testing its mutability as follows:
public class Demo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("study");
System.out.println(sb);
// modifying object
sb.append("java");
System.out.println(sb); // Output: studyjava
}
}
Important methods of StringBuffer class
append()
This method will concatenate the string representation of any type of data to the end of the StringBuffer object.
append() method has several overloaded forms.
StringBuffer append(String str)
StringBuffer append(int n)
StringBuffer append(Object obj)
Ex:
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("text");
str.append(123);
System.out.println(str); //text123
}
}
insert()
This method inserts one string into another.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, int num)
StringBuffer insert(int index, Object obj)
Here the first parameter gives the index at which position the string will be inserted and string representation of second parameter is inserted into StringBuffer object.
Ex:
public class Demo {
public static void main(String[]args) {
StringBuffer str = new StringBuffer("test");
str.insert(2, 123);
System.out.println(str);
}
}
reverse()
This method reverses the characters within a StringBuffer object.
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
}
}
replace()
This method replaces the string from specified start index to the end index.
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
}
}
capacity()
This method returns the current capacity of StringBuffer object.
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
}
0 comments:
Post a Comment