Java StringBuffer class is a mutable class in java. It means We can change the string when we are going to use StringBuffer class in Java. StringBuffer is same as String class only the difference is it can be modified.
Example:
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello Codebun"); System.out.println(sb); } }
Important points about StringBuffer class in Java.
StringBuffer is a mutable class in Java.
StringBuffer is thread safe class in Java.
The default capacity of the buffer is 16. it increases the capacity by (oldcap*2)+2.
Constructor from StringBuffer class
StringBuffer(): It will create an empty String with default capacity 16.
StringBuffer(String str): Create a StringBuffer like a String.
StringBuffer(int n): StringBuffer with customized capacity.
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer(); StringBuffer sb1 = new StringBuffer("Hello Codebun"); StringBuffer sb2 = new StringBuffer(5); System.out.println(sb.append("Hello Codebun")); System.out.println(sb1); System.out.println(sb2.append("Hello Codebun")); } }
StringBuffer Class methods:
insert()
insert() method is used to insert a method at a position in the String
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello Codebun"); sb.insert(6, "Java"); System.out.println(sb); } //outout : Hello JavaCodebun }
append()
append() method is used to append a string at the end of String.
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello Codebun "); System.out.println(sb.append("Java")); } // outout : Hello Codebun Java }
reverse()
Used to reverse a String.
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello Codebun "); System.out.println(sb.reverse()); } // outout : nubedoC olleH }
delete()
To delete a String or substring.
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello Codebun "); System.out.println(sb.delete(2, 8)); } // outout : Hedebun }
replace()
To replace a String or Substring.
public class Main { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello Codebun "); System.out.println(sb.replace(2, 5, "Bhupi")); } // outout : HeBhupi Codebun }