0% found this document useful (0 votes)
14 views13 pages

StringBuilder Class

stringbuilder class

Uploaded by

msoren07322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views13 pages

StringBuilder Class

stringbuilder class

Uploaded by

msoren07322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java

StringBuilder Class in Java with Examples


StringBuilder in Java represents a mutable sequence of characters.
Since the String Class in Java creates an immutable sequence of
characters, the StringBuilder class provides an alternative to String
Class, as it creates a mutable sequence of characters. The function of
StringBuilder is very much similar to the StringBuffer class, as both of
them provide an alternative to String Class by making a mutable
sequence of characters. However, the StringBuilder class differs from
the StringBuffer class on the basis of synchronization. The
StringBuilder class provides no guarantee of synchronization whereas
the StringBuffer class does. Therefore this class is designed for use as
a drop-in replacement for StringBuffer in places where the
StringBuffer was being used by a single thread (as is generally the
case). Where possible, it is recommended that this class be used in
preference to StringBuffer as it will be faster under most
implementations. Instances of StringBuilder are not safe for use by
multiple threads. If such synchronization is required then it is
recommended that StringBuffer be used. String Builder is not thread-
safe and high in performance compared to String buffer.

The class hierarchy is as follows:

java.lang.Object
↳ java.lang
↳ Class StringBuilder

WeSyntax:
use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Got It !
public final class StringBuilder
extends Object
implements Serializable, CharSequence

Constructors in Java StringBuilder Class

StringBuilder(): Constructs a string builder with no characters in it


and an initial capacity of 16 characters.
StringBuilder(int capacity): Constructs a string builder with no
characters in it and an initial capacity specified by the capacity
argument.
StringBuilder(CharSequence seq): Constructs a string builder that
contains the same characters as the specified CharSequence.
StringBuilder(String str): Constructs a string builder initialized to
the contents of the specified string.

Below is a sample program to illustrate StringBuilder in Java.

Online or
On-campus
Java

// Java Code to illustrate StringBuilder

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

public class GFG1 {


public static void main(String[] argv) throws Exception
{
// Create a StringBuilder object
// using StringBuilder() constructor
StringBuilder str = new StringBuilder();

str.append("GFG");

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

// create a StringBuilder object


// using StringBuilder(CharSequence) constructor
StringBuilder str1
= new StringBuilder("AAAABBBCCCC");

// print string
System.out.println("String1 = " + str1.toString());

// create a StringBuilder object


// using StringBuilder(capacity) constructor
StringBuilder str2 = new StringBuilder(10);

// print string
System.out.println("String2 capacity = "
+ str2.capacity());

// create a StringBuilder object


// using StringBuilder(String) constructor
StringBuilder str3
= new StringBuilder(str1.toString());

// print string
System.out.println("String3 = " + str3.toString());
}
}
Output

String = GFG
String1 = AAAABBBCCCC
String2 capacity = 10
String3 = AAAABBBCCCC

Methods in Java StringBuilder

StringBuilder append(X x): This method appends the string representation of


the X type argument to the sequence.
1. StringBuilder appendCodePoint(int codePoint): This method
appends the string representation of the codePoint argument to this
sequence.
2. int capacity(): This method returns the current capacity.
3. char charAt(int index): This method returns the char value in this
sequence at the specified index.
4. IntStream chars(): This method returns a stream of int zero-
extending the char values from this sequence.
5. int codePointAt(int index): This method returns the character
(Unicode code point) at the specified index.
6. int codePointBefore(int index): This method returns the character
(Unicode code point) before the specified index.
7. int codePointCount(int beginIndex, int endIndex): This method
returns the number of Unicode code points in the specified text
range of this sequence.
8. IntStream codePoints(): This method returns a stream of code
point values from this sequence.
9. StringBuilder delete(int start, int end): This method removes the
characters in a substring of this sequence.
10. StringBuilder deleteCharAt(int index): This method removes the
char at the specified position in this sequence.
11. void ensureCapacity(int minimumCapacity): This method ensures
that the capacity is at least equal to the specified minimum.
12. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin):
This method characters are copied from this sequence into the
destination character array dst.
13. int indexOf(): This method returns the index within this string of
the first occurrence of the specified substring.
14. StringBuilder insert(int offset, boolean b): This method inserts the
string representation of the boolean alternate argument into this
sequence.
15. StringBuilder insert(): This method inserts the string
representation of the char argument into this sequence.
16. int lastIndexOf(): This method returns the index within this string
of the last occurrence of the specified substring.
17. int length(): This method returns the length (character count).
18. int offsetByCodePoints(int index, int codePointOffset): This
method returns the index within this sequence that is offset from
the given index by codePointOffset code points.
19. StringBuilder replace(int start, int end, String str): This method
replaces the characters in a substring of this sequence with
characters in the specified String.
20. StringBuilder reverse(): This method causes this character
sequence to be replaced by the reverse of the sequence.
21. void setCharAt(int index, char ch): In this method, the character at
the specified index is set to ch.
22. void setLength(int newLength): This method sets the length of the
character sequence.
23. CharSequence subSequence(int start, int end): This method
returns a new character sequence that is a subsequence of this
sequence.
24. String substring(): This method returns a new String that contains
a subsequence of characters currently contained in this character
sequence.
25. String toString(): This method returns a string representing the
data in this sequence.
26. void trimToSize(): This method attempts to reduce storage used for
the character sequence.
Example:

Java

// Java code to illustrate


// methods of StringBuilder

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

public class GFG1 {


public static void main(String[] argv)
throws Exception
{

// create a StringBuilder object


// with a String pass as parameter
StringBuilder str
= new StringBuilder("AAAABBBCCCC");

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

// reverse the string


StringBuilder reverseStr = str.reverse();

// print string
System.out.println("Reverse String = "
+ reverseStr.toString());

// Append ', '(44) to the String


str.appendCodePoint(44);

// Print the modified String


System.out.println("Modified StringBuilder = "
+ str);

// get capacity
int capacity = str.capacity();

// print the result


System.out.println("StringBuilder = " + str);
System.out.println("Capacity of StringBuilder = "
+ capacity);
}
}
Output

String = AAAABBBCCCC
Reverse String = CCCCBBBAAAA
Modified StringBuilder = CCCCBBBAAAA,
StringBuilder = CCCCBBBAAAA,
Capacity of StringBuilder = 27

StringBuilder is another class in Java that is used to manipulate


strings. Like StringBuffer, it is a mutable class that allows you to
modify the contents of the string it represents. However, StringBuilder
is not thread-safe, so it should not be used in a multi-threaded
environment.

Here are some examples of how to use StringBuilder in Java:

Java

public class StringBuilderExample {


public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world!");
System.out.println(sb.toString()); // Output: "Hello world!"

sb.insert(6, "beautiful ");


System.out.println(sb.toString()); // Output: "Hello beautiful wo

sb.reverse();
System.out.println(sb.toString()); // Output: "!dlrow lufituaeb o
}
}

Output

Hello world!
Hello beautiful world!
!dlrow lufituaeb olleH
Feeling lost in the vast world of Backend Development? It's time for a
change! Join our Java Backend Development - Live Course and embark
on an exciting journey to master backend development efficiently and
on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks

Last Updated : 14 Mar, 2023 172

Previous Next

StringBuffer class in Java String vs StringBuilder vs


StringBuffer in Java

Share your thoughts in the comments Add Your Comment

Similar Reads
StringBuilder charAt() in Java with Examples

StringBuilder codePointAt() in Java with Examples

StringBuilder append() Method in Java With Examples


StringBuilder delete() in Java with Examples

StringBuilder codePointCount() in Java with Examples

StringBuilder capacity() in Java with Examples

StringBuilder codePointBefore() in Java with Examples

StringBuilder deleteCharAt() in Java with Examples

StringBuilder ensureCapacity() in Java with Examples

StringBuilder getChars() in Java with Examples

R RishabhP…

Article Tags : Java-Class and Object , Java-lang package , Java-StringBuilder , Java


Practice Tags : Java, Java-Class and Object
Trending in News View More

10 Best Tools to Convert DOC to DOCX


How To Summarize PDF Documents Using Google Bard for Free
Best free Android apps for Meditation and Mindfulness
TikTok Is Paying Creators To Up Its Search Game
30 OOPs Interview Questions and Answers (2024)
A-143, 9th Floor, Sovereign Corporate
Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Hack-A-Thons
Legal GfG Weekly Contest
Careers DSA in JAVA/C++
In Media Master System Design
Contact Us Master CP
Advertise with us GeeksforGeeks Videos
GFG Corporate Solution Geeks Community
Placement Training Program

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial Web Templates
ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design
Django Tutorial

Python Tutorial Computer Science


Python Programming Examples Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
AWS Top 50 Tree
Docker Top 50 Graph
Kubernetes Top 50 Array
Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

System Design JavaScript


High Level Design JavaScript Examples
Low Level Design TypeScript
UML Diagrams ReactJS
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

Preparation Corner School Subjects


Company-Wise Recruitment Process Mathematics
Resume Templates Physics
Aptitude Preparation Chemistry
Puzzles Biology
Company-Wise Preparation Social Science
English Grammar
World GK

Management & Finance Free Online Tools


Management Typing Test
HR Management Image Editor
Finance Code Formatters
Income Tax Code Converters
Organisational Behaviour Currency Converter
Marketing Random Number Generator
Random Password Generator

More Tutorials GeeksforGeeks Videos


Software Development DSA
Software Testing Python
Product Management Java
SAP C++
SEO - Search Engine Optimization Data Science
Linux CS Subjects
Excel

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy