Movatterモバイル変換


[0]ホーム

URL:


Open In App

In Java, the StringBuilder class (part of the java.lang package) provides a mutable sequence of characters. Unlike the String class (which is immutable), StringBuilder allows modification of character sequences without creating new objects, making it memory-efficient and faster for frequent string operations.

Declaration:

StringBuilder sb = new StringBuilder("Initial String");

stringbuilder
StringBuilder Class

Example: : Basic Demonstration of StringBuilder

Java
publicclassGeeks{publicstaticvoidmain(String[]args){StringBuildersb=newStringBuilder("GeeksforGeeks");System.out.println("Initial StringBuilder: "+sb);sb.append(" is awesome!");System.out.println("After append: "+sb);}}

Output
Initial StringBuilder: GeeksforGeeksAfter append: GeeksforGeeks is awesome!

The append() method adds the given string to the end of the existing sequence without creating a new object. This makes StringBuilder efficient for concatenation operations.

StringBuilder Constructors

StringBuilder class provides multiple constructors for different use cases.

  1. StringBuilder() :Creates an empty builder with a default capacity of 16 characters.
  2. StringBuilder(int capacity) :Creates an empty builder with a specified initial capacity.
  3. StringBuilder(String str) : Initializes the builder with the content of the given String.
  4. StringBuilder(CharSequence cs) :Initializes the builder with the given CharSequence (for example, String or StringBuffer).

Example:

Java
publicclassStringBuilderConstructorsDemo{publicstaticvoidmain(String[]args){StringBuildersb1=newStringBuilder();sb1.append("Hello");System.out.println("sb1: "+sb1);StringBuildersb2=newStringBuilder(50);sb2.append("This has initial capacity 50");System.out.println("sb2: "+sb2);StringBuildersb3=newStringBuilder("Geeks");sb3.append("ForGeeks");System.out.println("sb3: "+sb3);CharSequencecs="Java";StringBuildersb4=newStringBuilder(cs);sb4.append("Programming");System.out.println("sb4: "+sb4);}}

Output
sb1: Hellosb2: This has initial capacity 50sb3: GeeksForGeekssb4: JavaProgramming

Commonly Used Methods in StringBuilder

The StringBuilder class provides various methods for string manipulation.

Example: Using StringBuilder Methods

Java
publicclassGeeks{publicstaticvoidmain(String[]args){StringBuildersb=newStringBuilder("GeeksforGeeks");System.out.println("Initial: "+sb);sb.append(" is awesome!");System.out.println("After append: "+sb);sb.insert(13," Java");System.out.println("After insert: "+sb);sb.replace(0,5,"Welcome to");System.out.println("After replace: "+sb);sb.delete(8,14);System.out.println("After delete: "+sb);sb.reverse();System.out.println("After reverse: "+sb);System.out.println("Capacity: "+sb.capacity());System.out.println("Length: "+sb.length());charc=sb.charAt(5);System.out.println("Character at index 5: "+c);sb.setCharAt(5,'X');System.out.println("After setCharAt: "+sb);Stringsub=sb.substring(5,10);System.out.println("Substring (5–10): "+sub);sb.reverse();// Revert for searchSystem.out.println("Index of 'Geeks': "+sb.indexOf("Geeks"));sb.deleteCharAt(5);System.out.println("After deleteCharAt: "+sb);Stringresult=sb.toString();System.out.println("Final String: "+result);}}

Output:

Initial: GeeksforGeeks
After append: GeeksforGeeks is awesome!
After insert: GeeksforGeeks Java is awesome!
After replace: Welcome toforGeeks Java is awesome!
After delete: Welcome eeks Java is awesome!
After reverse: !emosewa si avaJ skee emocleW
Capacity: 60
Length: 29
Character at index 5: e
After setCharAt: !emosXwa si avaJ skee emocleW
Substring (5?10): Xwa s
Index of 'Geeks': -1
After deleteCharAt: Welcoe eeks Java is awXsome!
Final String: Welcoe eeks Java is awXsome!

In the above program, we use different methods of the StringBuilder class to perform different string manipulation operations such as append(), insert(), reverse() and delete().

Important StringBuilder Methods

MethodDescriptionExample
append(String str)Appends the specified string to the end of the StringBuilder.sb.append("Geeks");
insert(int offset, String)Inserts the specified string at the given position in the StringBuilder.sb.insert(5, " Geeks");
replace(int start, int end, String)Replaces characters in a substring with the specified string.sb.replace(6, 11, "Geeks");
delete(int start, int end)Removes characters in the specified range.sb.delete(5, 11);
reverse()Reverses the sequence of characters in the StringBuilder.sb.reverse();
capacity()Returns the current capacity of the StringBuilder.int cap = sb.capacity();
length()Returns the number of characters in the StringBuilder.int len = sb.length();
charAt(int index)Returns the character at the specified index.char ch = sb.charAt(4);
setCharAt(int index, char)Replaces the character at the specified position with a new character.sb.setCharAt(0, 'G');
substring(int start, int end)Returns a new String that contains characters from the specified range.String sub = sb.substring(0, 5);
ensureCapacity(int minimum)Ensures the capacity of the StringBuilder is at least equal to the specified minimum.sb.ensureCapacity(50);
deleteCharAt(int index)Removes the character at the specified position.sb.deleteCharAt(3);
indexOf(String str)Returns the index of the first occurrence of the specified string.int idx = sb.indexOf("Geeks");
lastIndexOf(String str)Returns the index of the last occurrence of the specified string.int idx = sb.lastIndexOf("Geeks");
toString()Converts the StringBuilder object to a String.String result = sb.toString();

StringBuilder vs String vs StringBuffer

The table below demonstrates the difference between String, StringBuilder and StringBuffer:

Features

String

StringBuilder

StringBuffer

Mutability

String are immutable(creates new objects on modification)

StringBuilder are mutable(modifies in place)

StringBuffer are mutable (modifies in place)

Thread-Safe

It is thread-safe

It is not thread-safe

It is thread-safe

Performance

It is slow because it creates an object each time

It is faster (no object creation)

It is slower due to synchronization overhead

Use Case

Fixed, unchanging strings

Single-threaded string manipulation

Multi-threaded string manipulation

Advantages of StringBuilder

  • Performs faster string manipulations in single-threaded environments.
  • Reduces memory overhead by modifying content in place.
  • Automatically increases capacity when needed.
  • Suitable for operations inside loops where strings are frequently changed.

Disadvantages of StringBuilder

  • Not synchronized; unsuitable for multi-threaded environments.
  • May allocate extra memory if the initial capacity is set too high.
  • Requires manual synchronization if used across multiple threads.

StringBuilder and StringBuffer
Visit Courseexplore course icon
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp