In this tutorial, we will cover all the methods available in the StringBuilder
class in Java. We will start with an introduction to StringBuilder
and then provide examples for each method along with comments and output.
Table of Contents
- Introduction to StringBuilder
- Methods and Examples
- append()
- capacity()
- charAt()
- codePointAt()
- codePointBefore()
- codePointCount()
- delete()
- deleteCharAt()
- ensureCapacity()
- getChars()
- indexOf()
- insert()
- lastIndexOf()
- length()
- replace()
- reverse()
- setLength()
- subSequence()
- substring()
- toString()
- trimToSize()
- Conclusion
1. Introduction to StringBuilder
The StringBuilder
class in Java is used to create mutable (modifiable) sequences of characters. Unlike the String
class, which creates immutable objects, StringBuilder
allows for in-place modifications, making it more efficient for certain operations like string concatenation, insertion, deletion, and replacement.
Key Points:
- Mutability:
StringBuilder
objects can be modified after creation. - Efficiency: More efficient than
String
for concatenation and modification. - Not Thread-Safe:
StringBuilder
is not synchronized, making it unsuitable for multi-threaded environments.
2. Methods and Examples
append()
The append
method is used to add data to the end of the StringBuilder
object.
Example
public class StringBuilderAppendExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
// Append different types of data
sb.append(", World!");
sb.append(123);
sb.append(true);
// Print the result
System.out.println("StringBuilder after append: " + sb.toString());
}
}
Output:
StringBuilder after append: Hello, World!123true
capacity()
The capacity
method returns the current capacity of the StringBuilder
object.
Example
public class StringBuilderCapacityExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
// Print the capacity of the StringBuilder
System.out.println("Initial capacity: " + sb.capacity());
// Append data to increase the size
sb.append(", World! This is a test.");
// Print the new capacity
System.out.println("Capacity after append: " + sb.capacity());
}
}
Output:
Initial capacity: 21
Capacity after append: 42
charAt()
The charAt
method returns the character at a specified index.
Example
public class StringBuilderCharAtExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get characters at specific indices
char firstChar = sb.charAt(0);
char seventhChar = sb.charAt(6);
char lastChar = sb.charAt(sb.length() - 1);
// Print the characters
System.out.println("First character: " + firstChar);
System.out.println("Seventh character: " + seventhChar);
System.out.println("Last character: " + lastChar);
}
}
Output:
First character: H
Seventh character: ,
Last character: !
codePointAt()
The codePointAt
method returns the Unicode code point at the specified index.
Example
public class StringBuilderCodePointAtExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get code points at specific indices
int codePointFirst = sb.codePointAt(0);
int codePointSeventh = sb.codePointAt(6);
// Print the code points
System.out.println("Code point of first character: " + codePointFirst);
System.out.println("Code point of seventh character: " + codePointSeventh);
}
}
Output:
Code point of first character: 72
Code point of seventh character: 44
codePointBefore()
The codePointBefore
method returns the Unicode code point before the specified index.
Example
public class StringBuilderCodePointBeforeExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get code points before specific indices
int codePointBeforeFirst = sb.codePointBefore(1);
int codePointBeforeSeventh = sb.codePointBefore(7);
// Print the code points
System.out.println("Code point before first character: " + codePointBeforeFirst);
System.out.println("Code point before seventh character: " + codePointBeforeSeventh);
}
}
Output:
Code point before first character: 72
Code point before seventh character: 111
codePointCount()
The codePointCount
method returns the number of Unicode code points in the specified text range.
Example
public class StringBuilderCodePointCountExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get the number of code points in the specified range
int codePointCount = sb.codePointCount(0, sb.length());
// Print the code point count
System.out.println("Number of code points: " + codePointCount);
}
}
Output:
Number of code points: 13
delete()
The delete
method removes a sequence of characters from the StringBuilder
.
Example
public class StringBuilderDeleteExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Delete a portion of the string
sb.delete(5, 7);
// Print the result
System.out.println("StringBuilder after delete: " + sb.toString());
}
}
Output:
StringBuilder after delete: HelloWorld!
deleteCharAt()
The deleteCharAt
method removes the character at the specified index.
Example
public class StringBuilderDeleteCharAtExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Delete the character at index 5
sb.deleteCharAt(5);
// Print the result
System.out.println("StringBuilder after deleteCharAt: " + sb.toString());
}
}
Output:
StringBuilder after deleteCharAt: Hello World!
ensureCapacity()
The ensureCapacity
method ensures that the capacity is at least equal to the specified minimum.
Example
public class StringBuilderEnsureCapacityExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// Ensure capacity of at least 50
sb.ensureCapacity(50);
// Print the capacity
System.out.println("Capacity after ensureCapacity: " + sb.capacity());
}
}
Output:
Capacity after ensureCapacity: 50
getChars()
The getChars
method copies characters from the StringBuilder
into a destination character array.
Example
public class StringBuilderGetCharsExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
char[] destArray = new char[5];
// Copy characters into the destination array
sb.getChars(7, 12, destArray, 0);
// Print the destination array
System.out.println("Destination array: " + new String(destArray));
}
}
Output:
Destination array: World
indexOf()
The indexOf
method returns the index within the StringBuilder
of the first occurrence of the specified substring.
Example
public class StringBuilderIndexOfExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Find the index of the substring "World"
int index = sb.indexOf("World");
// Print the index
System.out.println("Index of 'World': " + index);
}
}
Output:
Index of 'World': 7
insert()
The insert
method inserts the specified data at the specified index.
Example
public class StringBuilderInsertExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World!");
// Insert a string at index 5
sb.insert(5, ", Beautiful");
// Print the result
System.out.println("StringBuilder after insert: " + sb.toString());
}
}
Output:
StringBuilder after insert: Hello, Beautiful World!
lastIndexOf()
The lastIndexOf
method returns the index within the StringBuilder
of the last occurrence of the specified substring.
Example
public class StringBuilderLastIndex
OfExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World! Hello, World!");
// Find the last index of the substring "World"
int lastIndex = sb.lastIndexOf("World");
// Print the index
System.out.println("Last index of 'World': " + lastIndex);
}
}
Output:
Last index of 'World': 20
length()
The length
method returns the number of characters in the StringBuilder
.
Example
public class StringBuilderLengthExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get the length of the StringBuilder
int length = sb.length();
// Print the length
System.out.println("Length of StringBuilder: " + length);
}
}
Output:
Length of StringBuilder: 13
replace()
The replace
method replaces the characters in a substring of the StringBuilder
with characters in the specified string.
Example
public class StringBuilderReplaceExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Replace a portion of the string
sb.replace(7, 12, "Java");
// Print the result
System.out.println("StringBuilder after replace: " + sb.toString());
}
}
Output:
StringBuilder after replace: Hello, Java!
reverse()
The reverse
method reverses the sequence of characters in the StringBuilder
.
Example
public class StringBuilderReverseExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Reverse the string
sb.reverse();
// Print the result
System.out.println("StringBuilder after reverse: " + sb.toString());
}
}
Output:
StringBuilder after reverse: !dlroW ,olleH
setLength()
The setLength
method sets the length of the StringBuilder
. If the new length is greater than the current length, null characters are added. If the new length is less than the current length, the sequence is truncated.
Example
public class StringBuilderSetLengthExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Set a new length
sb.setLength(5);
// Print the result
System.out.println("StringBuilder after setLength: " + sb.toString());
System.out.println("New length: " + sb.length());
}
}
Output:
StringBuilder after setLength: Hello
New length: 5
subSequence()
The subSequence
method returns a new character sequence that is a subsequence of the current sequence.
Example
public class StringBuilderSubSequenceExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get a subsequence
CharSequence subSeq = sb.subSequence(7, 12);
// Print the subsequence
System.out.println("Subsequence: " + subSeq);
}
}
Output:
Subsequence: World
substring()
The substring
method returns a new string that is a substring of the current sequence.
Example
public class StringBuilderSubstringExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Get a substring
String subStr = sb.substring(7, 12);
// Print the substring
System.out.println("Substring: " + subStr);
}
}
Output:
Substring: World
toString()
The toString
method converts the StringBuilder
to a String
.
Example
public class StringBuilderToStringExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// Convert to String
String str = sb.toString();
// Print the string
System.out.println("Converted String: " + str);
}
}
Output:
Converted String: Hello, World!
trimToSize()
The trimToSize
method trims the capacity of the StringBuilder
to the current length.
Example
public class StringBuilderTrimToSizeExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(50); // Initial capacity of 50
sb.append("Hello, World!");
// Print initial capacity and length
System.out.println("Initial capacity: " + sb.capacity());
System.out.println("Initial length: " + sb.length());
// Trim to size
sb.trimToSize();
// Print capacity and length after trimming
System.out.println("Capacity after trimToSize: " + sb.capacity());
System.out.println("Length after trimToSize: " + sb.length());
}
}
Output:
Initial capacity: 50
Initial length: 13
Capacity after trimToSize: 13
Length after trimToSize: 13
3. Conclusion
In this tutorial, we covered the various methods provided by the StringBuilder
class in Java. Each method has its own use case and helps in efficiently manipulating strings. Understanding these methods allows you to perform various string operations efficiently, making StringBuilder
a powerful tool in Java programming.