StringBuffer, StringBuilder and
StringTokenizer
StringBuffer
• The StringBuffer class in Java is part of the java.lang
package and is used to create objects that hold a
mutable sequence of characters.
• Unlike the String class, which is immutable, the
StringBuffer class allows modifications to the
string's content after it has been created.
• This makes it more efficient for situations where a
string will be modified frequently, as it avoids
creating new objects with each modification, unlike
String.
• Key Characteristics of StringBuffer:
• Mutable: The contents of a StringBuffer object
can be changed after it is created.
• Thread-safe: The methods of StringBuffer are
synchronized, meaning it is safe to use in
multi-threaded environments.
• Efficient for modifications: StringBuffer is
typically faster than using String for operations
that involve modifying the string, especially in
loops, since it doesn't create new objects on
each modification.
• Common Constructors of StringBuffer:
• StringBuffer(): Creates an empty StringBuffer with an initial
capacity of 16 characters.
• StringBuffer sb = new StringBuffer();
• StringBuffer(String str): Creates a StringBuffer initialized with
the specified string.
• StringBuffer sb = new StringBuffer("Hello");
• StringBuffer(int capacity): Creates an empty StringBuffer with
the specified initial capacity.
• StringBuffer sb = new StringBuffer(50);
• Important Methods of StringBuffer: All the methods of
StringBuffer are synchronized.
• capacity(): Returns the current capacity of the StringBuffer.
Capacity is the amount of space allocated for characters,
which may be larger than the string's current length.
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.capacity());
• length(): Returns the number of characters currently in the
buffer.
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.length()); // Output: 5
• append(): Adds the specified string (or other data
types) to the end of the current string buffer.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
• insert(): Inserts the specified string (or other data
types) at the specified position.
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, " Java");
System.out.println(sb); // Output: Hello Java World
• delete(): Deletes characters in the buffer from the
specified start index to the end index.
StringBuffer sb = new StringBuffer("Hello Java World");
sb.delete(5, 10);
System.out.println(sb); // Output: Hello World
• reverse(): Reverses the sequence of characters in
the buffer.
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
• toString(): Converts the StringBuffer object to a String.
• Exampel -
StringBuffer sb = new StringBuffer("Hello World");
String str = sb.toString();
System.out.println(str); // Output: Hello World
• replace() - replace() method is used to replace a portion of the sequence of characters with
a specified string.
• replace(int start, int end, String str)
• start: The starting index (inclusive) of the portion to replace.
• end: The ending index (exclusive) of the portion to replace.
• str: The string to replace the specified range with.
• Example –
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java
}
}
• Performance Considerations:
• StringBuffer is generally preferred when there
are many modifications to the string (like
appending, inserting, deleting).
• Since it is synchronized, it is thread-safe but
may have some performance overhead in
multi-threaded environments. If thread-safety
is not required, StringBuilder (which is similar
to StringBuffer but not synchronized) can be
used for better performance.
StringBuilder
• The StringBuilder class in Java is similar to the
StringBuffer class but is designed for single-
threaded environments where thread safety is not
a concern.
• It provides an efficient way to manipulate strings
when you need to modify their content frequently.
• The key difference between StringBuilder and
StringBuffer is that StringBuilder is not
synchronized, making it faster than StringBuffer in
scenarios where thread safety is not an issue.
• Key Characteristics of StringBuilder:
• Mutable: Like StringBuffer, the content of a StringBuilder
object can be changed after it is created.
• Not Thread-safe: Unlike StringBuffer, StringBuilder is not
synchronized, which means it is not thread-safe but is
faster for single-threaded applications because there is
no overhead from synchronization.
• Efficient for String Manipulation: StringBuilder is more
efficient than String for frequent modifications (like
appending, inserting, deleting characters) because it
does not create new objects on each modification.
• Default Capacity: The default initial capacity of a
StringBuilder is 16 characters, which can grow as needed.
• Constructors of StringBuilder:
• StringBuilder(): Creates an empty StringBuilder
with an initial capacity of 16 characters
• StringBuilder sb = new StringBuilder();
• StringBuilder(String str): Creates a
StringBuilder initialized with the specified
string.
• StringBuilder sb = new StringBuilder("Hello");
• StringBuilder(int capacity): Creates an empty
StringBuilder with the specified initial capacity.
• StringBuilder sb = new StringBuilder(50);
• Commonly Used Methods of StringBuilder:
• append(): Adds the specified string (or other data types)
to the end of the current string builder.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
• insert(): Inserts the specified string (or other data types)
at the specified position.
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, " Java");
System.out.println(sb); // Output: Hello Java World
• delete(): Deletes characters in the builder from the
specified start index to the end index.
StringBuilder sb = new StringBuilder("Hello Java
World");
sb.delete(5, 9);
System.out.println(sb); // Output: Hello World
• reverse(): Reverses the sequence of characters in
the builder.
StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
• capacity(): Returns the current capacity of the StringBuilder.
Capacity is the amount of space allocated for characters.
• StringBuilder sb = new StringBuilder("Hello");
System.out.println(sb.capacity()); // Output: 16 (default initial
capacity)
• length(): Returns the number of characters currently in the
builder.
• StringBuilder sb = new StringBuilder("Hello");
System.out.println(sb.length()); // Output: 5
• toString(): Converts the StringBuilder object to a String.
• StringBuilder sb = new StringBuilder("Hello World"); String str
= sb.toString(); System.out.println(str); // Output: Hello World
• replace() - replace() method is used to replace a portion of the
sequence of characters with a specified string.
• replace(int start, int end, String str)
• start: The starting index (inclusive) of the portion to replace.
• end: The ending index (exclusive) of the portion to replace.
• str: The string to replace the specified range with.
• Example –
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Welcome to
Programming");
sb.replace(11, 14, "Java");
System.out.println(sb); // Output: Welcome to Javaing
}
}
• Performance Considerations:
• Thread Safety: StringBuilder is not
synchronized, which means it is not thread-safe.
However, if you are working in a single-
threaded environment, StringBuilder is faster
than StringBuffer because it avoids the
synchronization overhead.
• Efficiency: StringBuilder is highly efficient when
manipulating strings due to its mutability. It is
ideal for operations like appending, inserting, or
modifying strings within loops, where
performance is crucial.
StringTokenizer
• StringTokenizer is a legacy class in the java.util
package that is used to split strings into tokens.
• It breaks a string into tokens (substrings) based
on a specified delimiter.
• Although StringTokenizer is still available for use,
the String.split() method and Scanner class are
preferred for most modern applications due to
their flexibility and ease of use.
• Key Features of StringTokenizer
• It is part of the java.util package.
• Breaks a string into smaller parts called
tokens.
• Delimiters can be specified to define where
the string should be split.
• Does not support regular expressions as
delimiters (unlike String.split()).
• The default delimiter is whitespace.
• Constructors of StringTokenizer
• 1. StringTokenizer(String str)
• Creates a StringTokenizer object that splits the input string str using default delimiters.
The default delimiters are whitespace characters (space, tab, newline, etc.).
• Example -
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java is fun to learn";
// Create StringTokenizer with default delimiter (whitespace)
StringTokenizer st = new StringTokenizer(text);
// Print tokens
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
• 2. StringTokenizer(String str, String delimiter)
• Creates a StringTokenizer object that splits the input string str using the specified delimiter(s).
Multiple delimiters can be specified, and each character in the delimiter string is treated as a
separate delimiter.
• Example –
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java,Python|C++:JavaScript";
// Create StringTokenizer with custom delimiters (comma, pipe, colon)
StringTokenizer st = new StringTokenizer(text, ",|:");
// Print tokens
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
• 3. StringTokenizer(String str, String delimiter, boolean returnDelims)
• Creates a StringTokenizer object that splits the input string str using the specified delimiter(s).
If the returnDelims parameter is true, the delimiters themselves are also treated as tokens
and returned in the output.
• Example –
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java:Python:C++:JavaScript";
// Create StringTokenizer with ":" as delimiter and returnDelims = true
StringTokenizer st = new StringTokenizer(text, ":", true);
// Print tokens (including delimiters)
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
• Important Methods in StringTokenizer-
• boolean hasMoreTokens() -
Checks if there are more tokens left in the StringTokenizer.
Returns true if there are tokens remaining; otherwise, returns false.
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java is fun to learn";
StringTokenizer st = new StringTokenizer(text);
// Check if there are more tokens
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
• 2. String nextToken()
• Returns the next token from the StringTokenizer.
If no more tokens are available, it throws a NoSuchElementException.
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java,Python,C++";
StringTokenizer st = new StringTokenizer(text, ",");
// Retrieve tokens one by one
System.out.println(st.nextToken()); // Java
System.out.println(st.nextToken()); // Python
System.out.println(st.nextToken()); // C++
}
}
• 3. String nextToken(String delimiter)
• Returns the next token using a specified delimiter.
The delimiter can be changed dynamically with this method.
If no more tokens are available, it throws a NoSuchElementException.
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java,Python|C++";
StringTokenizer st = new StringTokenizer(text, ",");
// Retrieve tokens with the initial delimiter
System.out.println(st.nextToken()); // Java
// Change delimiter dynamically
System.out.println(st.nextToken("|")); // Python
System.out.println(st.nextToken("|")); // C++
}
}
• 4. int countTokens()
• Returns the number of tokens left in the StringTokenizer.
This count excludes tokens that have already been retrieved.
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java Python C++";
StringTokenizer st = new StringTokenizer(text);
// Count tokens before processing
System.out.println("Total tokens: " + st.countTokens()); // 3
// Retrieve tokens one by one
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
System.out.println("Tokens left: " + st.countTokens());
}
}
}
• Advantages of StringTokenizer
• Simple to use for basic tokenization.
• Lightweight compared to more advanced
classes.
• Disadvantages of StringTokenizer
• It is a legacy class and has been largely
replaced by String.split() and Scanner.
• Does not support regular expressions for
complex tokenization.
• Less flexible compared to modern alternatives.
• Preferred Alternatives
• String.split()
Supports regular expressions and is more modern.
String text = "Java,Python,C++,JavaScript";
String[] tokens = text.split(",");
for (String token : tokens) {
System.out.println(token);
}
• Scanner Class
Offers a broader range of parsing options.
import java.util.Scanner;
Scanner scanner = new Scanner("Java Python C++ JavaScript");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
•
• When to Use StringTokenizer
• Use StringTokenizer if you need quick and simple tokenization in older codebases. For new
applications, prefer String.split() or the Scanner class for better performance and
functionality.
• Practice Questions –
• 1 - Write a program to reverse each word in the sentence "Java is fun" using StringTokenizer and StringBuilder.
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java is fun";
// Tokenize the string
StringTokenizer st = new StringTokenizer(text);
// Use StringBuilder to reverse each token
StringBuilder result = new StringBuilder();
while (st.hasMoreTokens()) {
String word = st.nextToken();
StringBuilder sb = new StringBuilder(word);
result.append(sb.reverse()).append(" ");
}
// Print the result
System.out.println("Reversed Words: " + result.toString().trim());
}
}
• 2 - Write a program to check if the string "madam" is a palindrome using StringBuffer.
public class Main {
public static void main(String[] args) {
String input = "madam";
// Create a StringBuffer
StringBuffer sb = new StringBuffer(input);
// Reverse the string
String reversed = sb.reverse().toString();
// Check if the string is a palindrome
if (input.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
• 3 - Write a program to remove all vowels from the string "Programming is fun" using
StringBuffer.
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Programming is fun");
// Remove vowels
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if ("AEIOUaeiou".indexOf(c) != -1) {
sb.deleteCharAt(i);
i--; // Adjust index after removal
}
}
// Print the result
System.out.println("String without vowels: " + sb.toString());
}
}