BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java StringBuffer class With Examples

Last Updated: October 25, 2022 by Chaitanya Singh | Filed Under: java

Java StringBuffer class is used to create mutable strings. A mutable string is the one which can be modified. StringBuffer is an alternative to Java String class. In this guide, we will discuss StringBuffer class in detail. We will also cover important methods of Java StringBuffer class with examples.

Constructors of StringBuffer class

ConstructorDescription
StringBuffer()This is the default constructor of the StringBuffer class, it creates an empty StringBuffer instance with the default capacity of 16.
StringBuffer(String str)This creates a StringBuffer instance with the specified string.
StringBuffer(int capacity)This creates StringBuffer instance with the specified capacity instead of the default capacity 16.
StringBuffer(CharSequence cs)It creates a StringBuffer instance with the specified character sequence.

Example of various constructors of StringBuffer class:

public class JavaExample {
  public static void main(String args[]) {
    //creating StringBuffer object using default constructor
    StringBuffer sb = new StringBuffer();
    //appending a string to newly created instance
    sb.append("BeginnersBook.com");
    System.out.println("First String: "+sb);

    //Using StringBuffer(String str) constructor
    String str = "hello";
    StringBuffer sb2 = new StringBuffer(str);
    System.out.println("Second String: "+sb2);

    //Using StringBuffer(int Capacity) constructor
    StringBuffer sb3 = new StringBuffer(24);
    System.out.println("Capacity of sb3: "+sb3.capacity());

    //creating StringBuffer(CharSequence cs) constructor
    StringBuffer sb4 = new StringBuffer("Welcome");
    System.out.println("Fourth String: "+sb4);
  }
}

Output: