April 23, 2022

Java StringBuilder With Method Examples

StringBuilder in Java is a mutable sequence of characters which means using this class you can create mutable strings (String that can be modified). The API provided by StringBuilder class is compatible with StringBuffer with one noticeable difference, with StringBuilder there is no guarantee of synchronization.

When StringBuffer is being used by a single thread it is recommended that StringBuilder be used instead of StringBuffer as it will be faster as there is no synchronization overhead.

Why is StringBuilder class required

You may be wondering why is StringBuilder or StringBuffer class required when String class is already there with an extensive API.

In the post String in Java we have already seen that String objects are immutable and their values cannot be changed after they are created. Because of this immutability property when you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation. That may lead to creation of lots of intermediate String objects if String is modified several times which in turn means more memory being used for these intermediate objects.

Using StringBuilder or StringBuffer you can avoid this problem of creating several objects as these classes are mutable.

Important points about Java StringBuilder

Some of the important points about StringBuilder class.

  1. StringBuilder in Java provides much of the functionality of String class with one prominent deviation that StringBuilder is mutable.
  2. StringBuilder has an API compatible with StringBuffer except one design difference StringBuilder is not synchronized so it is not thread safe like StrinBuffer.
  3. Every StringBuilder is created with a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Java StringBuilder Constructors

There are four constructors in StringBuilder class.

  1. StringBuilder()- Constructs an empty string builder and an initial capacity of 16 characters.
    StringBuilder sb = new StringBuilder();
  2. StringBuilder(int capacity)- Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
    StringBuilder sb = new StringBuilder(30);
  3. StringBuilder(CharSequence seq)- Constructs a string builder that contains the same characters as the specified CharSequence. Here CharSequence is an interface which is implemented by CharBuffer, Segment, String, StringBuffer, StringBuilder.
  4. StringBuilder(String str)- Constructs a string builder initialized to the contents of the specified string.
    StringBuilder sb = new StringBuilder("Hello");

Java StringBuilder method examples

append method

append method in StringBuilder class is overloaded so as to accept data of any type. This method appends the string representation of the given data type to existing buffer. The append method always adds these characters at the end of the buffer.

public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hello");
    sb.append(" ");
    //chaining several appends
    sb.append("World").append(" ").append(123);
    System.out.println("Appended String- " + sb.toString());
  }
}
Output
Appended String- Hello World 123

As you can see from the example append is used with both String and int as argument as it is overloaded for these data types. You can also chain several append methods as done in the example.

insert method

insert method is also overloaded in StringBuilder class so as to accept data of any type. This method is used to insert the string representation of the given data type to existing buffer. The insert method adds the characters at a specified point.

insert method takes two arguments first an integer indicating the position where characters are to be inserted in the buffer and second argument is the text to be inserted.

public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hello");
    sb.insert(5, " World");
    System.out.println("String after insert- " + sb);
  }
}
Output
String after insert- Hello World
length and capacity methods
  • capacity()- Returns the current capacity of the StringBuilder.
  • length()- Returns the number of characters in this sequence.
public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(30);
    sb.append("Hello");
    System.out.println("Capacity of StringBuilder- " + sb.capacity());
    System.out.println("Length of StringBuilder- " + sb.length());
  }
}
Output
Capacity of StringBuilder- 30
Length of StringBuilder- 5

Here you can see that StringBuilder is created with the capacity as 30 so the capacity is displayed as 30 where as number of characters in the buffer is 5 so the length is displayed as 5.

reverse method
  • reverse()- Reverses the existing StringBuilder.
public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hello");
    System.out.println("Reversed- " + sb.reverse());
  }
}
Output
Reversed- olleH
replace method
  • replace(int start, int end, String str)- Replaces the characters in a substring of this sequence (start to end-1) with characters in the specified String.
public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hello");
    sb.replace(3, 5, "ena");
    System.out.println("String- " + sb);
  }
}
Output
String- Helena
delete and deleteCharAt methods
  • delete(int start, int end)- Removes the characters in a substring of this sequence. start which indicates the beginning index is inclusive where as end which indicates the ending index is exclusive.
  • deleteCharAt(int index)- Removes the char at the specified position in this sequence.
public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hello");
    sb.delete(1, 3);
    System.out.println("After deletion- " + sb);
    System.out.println("Length of StringBuilder- " + sb.length());
  }
}
Output
After deletion- Hlo
Length of StringBuilder- 3
public class StringLiteral  {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hello");
    sb.deleteCharAt(4);
    System.out.println("After deletion- " + sb);
    System.out.println("Length of StringBuilder- " + sb.length());
  }
}
Output
After deletion- Hell
Length of StringBuilder- 4

Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html

That's all for the topic Java StringBuilder With Method Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment