Working with StringBuilder Class in Java

Working with StringBuilder Class in Java

The StringBuilder is a sequence of characters that is mutable (modified or changed). The StringBuilder class has been made such that users have the option of using mutable literals rather than the immutable objects of the String class. The StringBuilder class closely relates to the StringBuffer class with some differences. Both these classes allow for mutable objects but unlike the StringBuffer class, Stringbuilder is unsynchronized therefore not thread-safe.

Class Hierarchy

java.long.Object
>java.lang
>>Class StringBuilder

Syntax: public final class StringBuilder extends object implements Serializable, CharSequence

StringBuilder Constructors

  • StringBuilder() – This creates an empty string builder with the default size of 16 characters in it. The characters start with index 0.
  • StringBuilder (int capacity) – This creates an empty string builder with a fixed length as specified in ‘capacity’.
  • StringBuilder (CharSequence seq) – This will create a string builder with the characters contained in seq.
  • StringBuilder (String str) – This constructor is similar to the one before. The string builder is initialized to the string str and adapts itself to the length of str.

StringBuilder Methods

Below are some of the methods of StringBuilder with suitable examples

  • public Stringbuilder append(String str) – This method is used to add a string to the string builder.
    Example:

    class Sample1
    {
    public static void main (String args [])
    {
    StringBuilder sb = new StringBuilder(“Hello”);
    append(”World”);
    System.out.println(sb);
    }
    }

     

    OUTPUT: Hello World

  • public Stringbuilder insert (int offset, String str) To insert a String at a particular index.
    Example:

    class Sample2
    {
    public static void main (String args [])
    {
    StringBuilder sb = new StringBuilder(“Hello”);
    insert(1, “World”);
    System.out.println(sb);
    }
    }
    

     

    OUTPUT: HWorldello

  • public StringBuilder replace (int startIndex, int endIndex, String str) – To replace the string with another string str.
    Example:

    class Sample3
    {
    public static void main (String args [])
    {
    StringBuilder sb = new StringBuilder(“Hello”);
    replace(1,3, “World”);
    Sstem.out.println(sb);
    }
    }

     

    OUTPUT: HWorldlo

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.