Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The StringBuilder class
2.1.
Features
2.2.
Constructors
2.3.
Methods/Functions
2.4.
Basic operations
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

StringBuilder Class in Java

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Strings are a sequence of characters enclosed within double-quotes. The String class in Java is used to create an immutable sequence of characters, i.e. the string cannot be altered within the same string object. If we try to modify the string, a new String object is created, and the new value is updated. 

The StringBuilder class overcomes the limitations of the String class by creating a sequence of mutable characters. This allows the modification of a string within the existing object and does not require creating a new one.

The StringBuilder class

Class Signature:

public final class StringBuilder
    extends Object
    implements Serializable, CharSequence

 

Creation of instances:

StringBuilder object_name = new StringBuilder();

 

You can also read about the topic of Java Destructor, and Duck Number in Java.

Features

  • The StringBuilder class is very much similar to the StringBuffer class, the only difference being that the former provides no guarantee of synchronisation. Hence, it is used only by single threads.
     
  • ‘Insert’ and ‘append’ are the principal methods of the StringBuilder class that are overloaded to accept values of any type.
     
  • Every string builder has a character capacity that will create a new internal buffer to accommodate more characters upon exceeding.
     
  • Passing a null value to StringBuilder’s constructors or methods results in NullPointerException.

Constructors

  • StringBuilder()

    • It constructs a string builder with no characters but an initial capacity of 16 characters by default.
       
StringBuilder object_name = new StringBuilder();


Try this code by yourself on Online Java Compiler.
 

  • StringBuilder(CharSequence seq)

    • CharSequence is an interface that provides read-only access to different types of character sequences. In simple words, it is a readable sequence of char values.
       
    • The constructor creates a string builder containing the same characters as the specified CharSequence.
       
StringBuilder object_name = new StringBuilder(“aabbcc”);

 

  • StringBuilder(int capacity)

    • It constructs a string builder with no characters but a specified capacity to hold characters.
       
StringBuilder object_name = new StringBuilder(10);

 

  • StringBuilder(String str)

    • It constructs a string builder initialised with the characters of the given string.
       
StringBuilder object_name = new StringBuilder(“hello”);

Methods/Functions

Method

Parameter

Type 

Description 

append() boolean b StringBuilder It appends the string representation of the boolean argument to the sequence.
char c It appends the string representation of the char argument to the sequence.
char[ ] str It appends the string representation of the char array argument to the sequence.
char[ ] str, int offset, int len It appends the string representation of a subarray of the char array argument to the sequence.
CharSequence s It appends CharSequence to the sequence.
CharSequence s, int start, int end It appends a subsequence of the specified CharSequence to the sequence.
double d It appends the string representation of the double argument to the sequence.
float f It appends the string representation of the float argument to the sequence.
int i It appends the string representation of the int argument to the sequence.
long lng It appends the string representation of the long argument to the sequence.
Object obj It appends the string representation of the object argument to the sequence.
String str It appends the specified string to the sequence.
StringBuffer sb It appends the specified StringBuffer to the sequence.
appendCodePoint() int codePoint StringBuilder It appends the string representation of the codePoint argument to the sequence.
capacity() - int  It returns the current capacity.
charAt() int index char It returns the character present at the specified index.
codePointAt() int index int It returns Unicode code points at the specified index in the sequence.
codePointBefore() It returns the Unicode code point before a specified index in the sequence.
codePointCount() int beginIndex, int endIndex int It returns the number of Unicode code points in the specified range of the sequence.
delete() int start, int end StringBuilder It removes the set of characters under a given range in the sequence.
deleteCharAt() int index StringBuider It removes the character at the given index.
ensureCapacity() int minimumCapacity void It ensures that the capacity is at least equal to the given minimum value.
getChars() int srcBegin,  int srcEnd, char[ ] dst, int dstBegin void It copies a set of characters from a given range in the sequence to a destination char array.
indexOf() String str int It returns the index of the first occurrence of the given string in the sequence.
String str, int fromIndex It returns the index of the first occurrence of the given string in the sequence from a specified index.
insert() int offset, boolean b StringBuilder It inserts the string representation of the specified boolean argument into the sequence.
int offset, char c It inserts the string representation of the specified char argument into the sequence.
int offset, char[ ] str It inserts the string representation of a char array argument into the sequence.
int index, char[ ] str, int offset, int len It inserts the string representation of a subarray of the str array argument into the sequence.
int dstOffset, CharSequence s It inserts the specified CharSequence into the sequence.
int dstOffset, CharSequence s, int start, int end It inserts a subsequence of the specified CharSequence into the sequence.
int offset, double d It inserts the string representation of the specified double argument into the sequence.
int offset, float f It inserts the string representation of the specified float argument into the sequence.
int offset, int i It inserts the string representation of the specified int argument into the sequence.
int offset, long lng It inserts the string representation of the specified long argument into the sequence.
int offset, Object obj It inserts the string representation of the specified object argument into the sequence.
int offset, String str It inserts the given string into the sequence.
lastIndexOf() String str int It returns the index of the last occurrence of the given substring in the sequence.
String str, int fromIndex It returns the index of the last occurrence of the given substring from the specified index in the sequence.
length() - int It returns the length of the sequence.
replace() int start, int end, String str StringBuilder It replaces the characters in a given range in the sequence with the specified string.
reverse() - StringBuilder It replaces the current character sequence with its reverse.
setChatAt() int index, char ch void Character ch is placed at the specified index.
setLength() int newLength void It sets the length of the character sequence.
subSequence() int start, int end CharSequence It returns a new character sequence from a given range in the sequence.
substring() int start String It returns a new string of characters present from the specified index to the end of the sequence.
int start, int end It returns a new string of characters present within the given range from the sequence.
toString() - String It returns a string format of the data in the sequence.
trimToSize() - void It tries to reduce the storage space used for the character sequence.

Also see, Hashcode Method in Java and Swap Function in Java

Basic operations

The insert() and append() methods, as mentioned before, perform the two main operations of inserting and appending characters to a given sequence. Let us see the methods of the StringBuilder class in action with the help of this example.

import java.util.*;
import java.util.concurrent.*;

public class Main 
{
  public static void main(String[] args) throws Exception
  {
    StringBuilder str = new StringBuilder("ABC");

    System.out.println("String = "+ str.toString());

    str.append("D");
    System.out.println("\nAppending D => "+ str.toString());
    str.append("EFG",0,2);
    System.out.println("Appending EF => "+ str.toString());
    str.append(26);
    System.out.println("Appending 26 => "+ str.toString());

    System.out.println("\nCharacter at index 4 = "+ str.charAt(4));
    StringBuilder reverseStr = str.reverse();
    System.out.println("\nReverse String => "+ reverseStr.toString());

    str.insert(2,"GHI");
    System.out.println("\nInsertion => "+ str.toString());

    System.out.println("\nLength of the String => "+ str.length());

    System.out.println("\nSubString => "+ str.substring(2,6));

    str.replace(4,5,"G");
    System.out.println("\nReplacing I with G => "+ str.toString());

    System.out.println("\nIndex of G in the String = "+ str.indexOf("G"));
    System.out.println("Last index of G in the String = "+ str.lastIndexOf("G"));

    str.delete(4,6);
    System.out.println("\nAfter deleting \'GF\' from the String = "+ str.toString());

    str.appendCodePoint(48);
    System.out.println("\nAppending code point => "+ str);

    int capacity = str.capacity();
    System.out.println("\nCapacity of StringBuilder => "+ capacity);
  }
}

 

Output:

String = ABC

Appending D => ABCD
Appending EF => ABCDEF
Appending 26 => ABCDEF26

Character at index 4 = E

Reverse String => 62FEDCBA

Insertion => 62GHIFEDCBA

Length of the String => 11

SubString => GHIF

Replacing I with G => 62GHGFEDCBA

Index of G in the String = 2
Last index of G in the String = 4

After deleting 'GF' from the String = 62GHEDCBA

Appending code point => 62GHEDCBA0

Capacity of StringBuilder => 19

Check out this problem - Longest Subarray With Sum K 

Must Read: Java System Out Println

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

Q: Briefly explain the StringBuffer class?

It is a thread-safe, mutable sequence of characters like the String Builder. The content and length of a string buffer can be modified without creating a new object. Unlike string builders, string buffers are safe for use by multiple threads as they provide synchronisation. It ensures that all the operations on an instance occur in a serial order that is consistent with the order of the method calls made by each of the participating threads.

Q: What are Unicode code points?

A code point is a non-negative number that identifies a character in the Unicode standard. Unicodes are like ASCII codes but are stretched to 16 bits, which is sufficient to encode the characters of all the languages in the world. It currently defines over 1000000 characters, and each of them has its own unique code point.

Key Takeaways

String Manipulation is an important part of almost every application or program. Classes like String and StringBuilder enable programmers to deal with string values or data efficiently. This blog explains the StringBuilder class in Java and its features. It also lists the different functions and methods offered by the class and shows how to implement them.

Recommended problems -

 

Check out the official Coding Ninjas Blog site and visit our Library for more.

Previous article
StringBuffer Class
Next article
StringTokenizer in Java
Live masterclass