The StringBuffer
class in Java is used to create mutable strings. Unlike String
, which is immutable, StringBuffer
objects can be modified after they are created. This tutorial will cover all the methods of the StringBuffer
class with examples to demonstrate their usage.
Table of Contents
- Introduction
- Constructors
- Methods
append
capacity
charAt
chars
codePointAt
codePointBefore
codePointCount
codePoints
compareTo
delete
deleteCharAt
ensureCapacity
getChars
indexOf
insert
lastIndexOf
length
replace
reverse
setCharAt
setLength
subSequence
substring
toString
trimToSize
- Conclusion
Introduction
The StringBuffer
class is a part of the java.lang
package. It is used to create strings that can be modified after they are created, unlike String
objects which are immutable. StringBuffer
is thread-safe, meaning it is synchronized to avoid issues when multiple threads are accessing it.
Constructors
Example
public class StringBufferConstructorsExample {
public static void main(String[] args) {
// Default constructor
StringBuffer sb1 = new StringBuffer();
// Constructor with initial capacity
StringBuffer sb2 = new StringBuffer(50);
// Constructor with initial string
StringBuffer sb3 = new StringBuffer("Hello");
System.out.println(sb1);
System.out.println(sb2);
System.out.println(sb3);
}
}
Output:
Initial capacity for sb2: 50
Hello
Methods
append
Appends the specified data to this StringBuffer
.
public class StringBufferAppendExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(", World!");
sb.append(123);
System.out.println(sb.toString());
}
}
Output:
Hello, World!123
capacity
Returns the current capacity of the StringBuffer
.
public class StringBufferCapacityExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Capacity: " + sb.capacity());
}
}
Output:
Capacity: 21
charAt
Returns the character at the specified index.
public class StringBufferCharAtExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Character at index 1: " + sb.charAt(1));
}
}
Output:
Character at index 1: e
chars
Returns a stream of int
representing the characters in the StringBuffer
.
import java.util.stream.IntStream;
public class StringBufferCharsExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
IntStream charStream = sb.chars();
charStream.forEach(ch -> System.out.print((char) ch + " "));
}
}
Output:
H e l l o
codePointAt
Returns the Unicode code point at the specified index.
public class StringBufferCodePointAtExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Code point at index 1: " + sb.codePointAt(1));
}
}
Output:
Code point at index 1: 101
codePointBefore
Returns the Unicode code point before the specified index.
public class StringBufferCodePointBeforeExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Code point before index 1: " + sb.codePointBefore(1));
}
}
Output:
Code point before index 1: 72
codePointCount
Returns the number of Unicode code points in the specified text range.
public class StringBufferCodePointCountExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
System.out.println("Code point count from index 0 to 5: " + sb.codePointCount(0, 5));
}
}
Output:
Code point count from index 0 to 5: 5
codePoints
Returns a stream of Unicode code points in the StringBuffer
.
import java.util.stream.IntStream;
public class StringBufferCodePointsExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
IntStream codePoints = sb.codePoints();
codePoints.forEach(cp -> System.out.print((char) cp + " "));
}
}
Output:
H e l l o
compareTo
Compares this StringBuffer
to another StringBuffer
lexicographically.
public class StringBufferCompareToExample {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("World");
System.out.println("Comparison result: " + sb1.compareTo(sb2));
}
}
Output:
Comparison result: -15
delete
Removes the characters in a substring of this sequence.
public class StringBufferDeleteExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
sb.delete(5, 7);
System.out.println(sb.toString());
}
}
Output:
Hello World!
deleteCharAt
Removes the character at the specified position in this sequence.
public class StringBufferDeleteCharAtExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
sb.deleteCharAt(5);
System.out.println(sb.toString());
}
}
Output:
Hello World!
ensureCapacity
Ensures that the capacity is at least equal to the specified minimum.
public class StringBufferEnsureCapacityExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println("Initial capacity: " + sb.capacity());
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity(50): " + sb.capacity());
}
}
Output:
Initial capacity: 16
Capacity after ensureCapacity(50): 50
getChars
Copies characters from this sequence into the destination character array.
public class StringBufferGetCharsExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
char[] dst = new char[5];
sb.getChars(7, 12, dst, 0);
System.out.println(dst);
}
}
Output:
World
indexOf
Returns the index within this string of the first occurrence of the specified substring.
public class StringBufferIndexOfExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
int index = sb.indexOf("World");
System.out.println("Index of 'World': " + index);
}
}
Output:
Index of 'World': 7
insert
Inserts the string representation of various data types into this sequence.
public class StringBufferInsertExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, !");
sb.insert(7, "World");
System.out.println(sb.toString());
}
}
Output:
Hello, World!
lastIndexOf
Returns the index within this string of the last occurrence of the specified substring.
public class StringBufferLastIndexOfExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World! Hello, Universe!");
int index = sb.lastIndexOf("Hello");
System.out.println("Last index of 'Hello': " + index);
}
}
Output:
Last index of 'Hello': 14
length
Returns the length (character count) of this StringBuffer
.
public class StringBufferLengthExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
System.out.println("Length of the StringBuffer: " + sb.length());
}
}
Output:
Length of the StringBuffer: 13
replace
Replaces the characters in a
substring of this sequence with characters in the specified String
.
public class StringBufferReplaceExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
sb.replace(7, 12, "Java");
System.out.println(sb.toString());
}
}
Output:
Hello, Java!
reverse
Reverses the sequence of characters in this StringBuffer
.
public class StringBufferReverseExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
sb.reverse();
System.out.println(sb.toString());
}
}
Output:
!dlroW ,olleH
setCharAt
Sets the character at the specified index to the specified character.
public class StringBufferSetCharAtExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
sb.setCharAt(7, 'J');
System.out.println(sb.toString());
}
}
Output:
Hello, Jorld!
setLength
Sets the length of this StringBuffer
.
public class StringBufferSetLengthExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.setLength(10);
System.out.println("Content: '" + sb.toString() + "'");
for (int i = 0; i < sb.length(); i++) {
System.out.print((int) sb.charAt(i) + " ");
}
}
}
Output:
Content: 'Hello '
72 101 108 108 111 0 0 0 0 0
subSequence
Returns a new character sequence that is a subsequence of this sequence.
public class StringBufferSubSequenceExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
CharSequence subSeq = sb.subSequence(7, 12);
System.out.println("Subsequence: " + subSeq);
}
}
Output:
Subsequence: World
substring
Returns a new String
that contains a subsequence of characters currently contained in this sequence.
public class StringBufferSubstringExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
String subStr = sb.substring(7, 12);
System.out.println("Substring: " + subStr);
}
}
Output:
Substring: World
toString
Returns a string representing the data in this sequence.
public class StringBufferToStringExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
String str = sb.toString();
System.out.println("Converted String: " + str);
}
}
Output:
Converted String: Hello, World!
trimToSize
Attempts to reduce storage used for the character sequence.
public class StringBufferTrimToSizeExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(100);
sb.append("Hello, World!");
System.out.println("Capacity before trimming: " + sb.capacity());
sb.trimToSize();
System.out.println("Capacity after trimming: " + sb.capacity());
}
}
Output:
Capacity before trimming: 100
Capacity after trimming: 13
Conclusion
The StringBuffer
class in Java provides a powerful and flexible way to work with strings that need to be modified. By understanding and using the various methods available in the StringBuffer
class, you can perform a wide range of operations on strings efficiently and effectively. This tutorial has covered all the methods of the StringBuffer
class with examples to help you get started with using StringBuffer
in your Java programs.