Sitemap
Mayank Pant

Mayank Pant

My notes for future me

StringBuffer, StringBuilder & StringTokenizer in Java

8 min readNov 29, 2025

--

StringBuffer

Why StringBuffer is needed? And what are the drawbacks of String?

When we have fixed content then we can use String, but when we have changing content then it is never recommended to use String. Because every modification will result into creation of a new object which will increase the memory utilization. To prevent this, we should use StringBuffer, as only one object will be created and we can modify the same object as many time as we want to. All required changes will be performed in the same object only. For such type of requirement we should go for StringBuffer.

StringBuffer constructors

In case of StringBuffer there comes the concept of length and capacity. With String, we only have a fixed amount of chars that we can store and cannot change it, so there is only length. But StringBuffer can grow in size, so length gives us the actual size currently and capacity gives us the amount of characters that the object can hold.

By default StringBuffer has 16 capacity

StringBuffer sb = new StringBuffer(“durga”);

When the current capacity is filled, then a new StringBuffer object with capacity = (current capacity + 1) x 2 will be created and contents will be copied to it.

StringBuffer sb = new StringBuffer(int initialCapacity);
When we know that we want to store a large string then we can also explicitly pass the capacity.

StringBuffer sb = new StringBuffer(String s);
Internally the capacity in this case is calculated as: capacity = s.length() + 16. Had they not done this, then a string with length greater than 16 would require additional operations to be stored correctly.
Had they not added 16 then there would not be space for the sb to grow, it needed further resize which would be expensive.

StringBuffer methods

  • public int length()
  • public int capacity()
  • public char charAt(int index): Gives StringIndexOutofBoundException in case of index out of bound, and not StringBufferIndexOutofBoundException as there is no such exception.
  • public void setCharAt(int index, char newChar): Replaces character at given index
  • public StringBuffer append(String s): Many overloaded methods for this for each data type. Adds data at last
  • public StringBuffer insert(int index, String s): Here also we can insert any data type to insert.
  • public StringBuffer delete(int index, int end): Deletes from start index to end — 1 index. Range deletion
  • public StringBuffer deleteCharAt(int index):
  • public StringBuffer reverse()
  • public void setLength(int length): Remove additional characters and only takes those which fall in the specified length. If current length is less than passed length then empty spaces will be added.
  • public void ensureCapacity(int capacity): Sets the capacity for sb object
  • public void trimToSize(): To deallocate extra memory given to a sb. Maybe you initialized with greater capacity and don’t need that now. Extra memory will be deallocated.

StringBuilder

StringBuffer had a problem. Every method in StringBuffer is synchronized, meaning it is thread safe. This meant that it is slower in a multi-threaded environment. To overcome this, StringBuilder was introduced in 1.5v of Java.

Everything is similar to StringBuffer, only difference being that no method are synchronized. Else all the constructors and methods are same.

Press enter or click to view image in full size

String vs StringBuffer vs StringBuilder

When content is fixed and won’t change frequently, go for String.
When content is not fixed, keeps on changing, but thread safety is required, then go for StringBuffer.
When content is not fixed, keeps on changing, but we don’t want thread safety, then go for StringBuilder.

Press enter or click to view image in full size

Is String thread-safe?

Not only String, but all immutable objects in Java are by-default thread safe because no one is allowed to do any modification on the object.

Method Chaining

In almost all methods of String, StringBuffer, and StringBuilder the return type is of the same type. So we can chain additional methods to the output of the previous operation, hence forming a method chain.

StringTokenizer

What is String tokenization and how it is possible to perform String Tokenization in Java Applications?

The process of dividing a string into tokens is called as String Tokenization.

To perform String Tokenization Java has provided a predefined class in the form of java.util.StringTokenizer class.

To perform String Tokenization in java applications we have to use the following steps:

  • Create StringTokenizer Class Object: To create StringTokenizer class object we have to use the following constructor: public StringTokenizer(String data)
  • Ex: StringTokenizer st = new StringTokenizer(“Durga Software Solutions”);
  • When JVM encounter the above instruction, it will take the provided String and divide the provided String into no of tokens and JVM will store the generated tokens by creating object for StringTokenizer class.

NOTE: When StringTokenizer class object is created with the no of tokens then a pointer or cursor will be created before the first token.

To get no of tokens in StringTokenizer class object we have to use the following method: public int countTokens()

Get Mayank Pant’s stories in your inbox

Join Medium for free to get updates from this writer.

To retrieve Tokens from StringTokenizer Object:

  • Check whether more tokens are available or not from the current cursor position by using the following method: `public boolean hasMoreTokens()`
  • It will return true value if at-least next token exists
  • It will return false value if no more tokens are there
  • If at-least next token is available then it reads next token and moves cursor to next position by using the following method: public String nextToken()
import java.util.*;
class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Durga Software Solutions");
System.out.println("No Of Tokens:"+st.countTokens());
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Press enter or click to view image in full size

Interview Questions

Q:: What is the difference between `String` and `StringBuffer`?
Ans:: String class objects are immutable objects, and immutable objects do not allow modifications over their content. If we are trying to perform modifications over immutable object then operations are allowed, but, the resultant data will not be stored back in original object, it will be stored by creating new object.
StringBuffer objects are mutable objects, they allow modifications on their content.

Q:: What are the differences between StringBuffer and StringBuilder?
Ans::

  • StringBuffer class was introduced in JDK1.0 version. StringBuilder class was introduced in JDK5.0 version.
  • StringBuffer is synchronized. StringBuilder is not synchronized.
  • Almost all the methods are synchronized in StringBuffer. No method is synchronized in StringBuilder.
  • StringBuffer is able to allow only one thread to access data. StringBuilder is able to allow more than one thread to access data.
  • StringBuffer is following sequential execution. StringBuilder is following parallel execution.
  • StringBuffer will increase execution time. StringBuilder will reduce execution time.
  • StringBuffer will reduce application performance. StringBuilder will increase application performance.
  • StringBuffer is able to give guarantee for Data Consistency. StringBuilder is unable to give guarantee for data consistency.
  • StringBuffer is thread safe. StringBuilder is not thread safe.

Q:: What is the difference between the following 2 Statements
a) String str = new String(“Durga Software Solutions”);
b) String str = “Durga Software Solutions”;

Ans:: To create String class object if we use first statement then one String object will be created at heap memory as per new keyword and another String object will be created at String Constant Pool Area inside heap memory as per string literal.
To create String object, if we use second statement, then String object will be created at String Constant Pool Area only.

Note: The objects which are created in String Constant Pool Area are not eligible for Garbage Collection. The objects which are created in Heap memory are eligible for Garbage Collection.

Press enter or click to view image in full size

Q:: What is the difference between == Operator and `equals()`Method?

Ans:: == is basically a comparison operator, it will check whether the provided operand values are same or not, where operands may be normal primitive variables or object reference variables.
equals() method is defined in java.lang.Object class, it is implemented in such a way that it provides comparison between two object reference values.
String class has overridden Object class equals() method in such a way such that it provides comparison between two String objects content.

class A {}

class Test {
public static void main(String[] args) {
A a1=new A();
A a2=new A();

int i=10;
int j=10;

String str1=new String("abc");
String str2=new String("abc");

System.out.println(i == j);// true: as primitive, so checks value
System.out.println(a1 == a2);// false
System.out.println(str1 == str2);// false
System.out.println(a1.equals(a2));// false
System.out.println(str1.equals(str2));//true
}
}

How String Interning Works

Java provides the intern() method to manually add strings to the pool:

String fifth = new String("hello").intern(); 
String sixth = "hello";

System.out.println(fifth == sixth); // true

Here, fifth is initially created as a separate object, but calling intern()checks the string pool for an existing ”hello”. Since it is already present, fifth is redirected to the pooled instance instead of keeping its separate allocation.

Interning is useful when working with dynamically created strings that should match pooled literals. For example, strings loaded from a database or generated at runtime won’t automatically be part of the pool unless explicitly interned.

How the String Pool Is Managed

The string pool is part of the JVM’s method area (also known as the runtime constant pool). In older Java versions (before Java 7), it was stored in the permanent generation (PermGen) space. Starting with Java 7, it was moved to the heap, allowing it to grow as needed.

Because the pool stores only one copy of each literal, it helps reduce redundant objects in memory. However, excessive interning of non-repeating strings can lead to increased memory usage. Interned strings are never garbage-collected unless they have no remaining references in the program. Too many unique interned strings can put pressure on the heap.

String Pool Size and Java Versions

The string pool has changed over different Java versions. As mentioned earlier, before Java 7, the string pool was in the fixed-size PermGen space, which could cause OutOfMemoryError. Java 7 moved it to the heap for dynamic growth.

From Java 7 onward, the pool was moved to the heap, allowing it to grow dynamically based on application needs. This change made interning safer, but it also means that excessive interning of unique strings can still lead to higher heap consumption.

Handling Empty and Null Strings

In Java, it’s crucial to differentiate between an empty string and a null reference. An empty string (””) is a valid string object with a length of zero, whereas a null string doesn’t refer to any object. Checking for both conditions is a common practice to avoid `NullPointerException`:

String emptyString = ""; 
String nullString = null;

// Check for empty string
if (emptyString.isEmpty()) {
System.out.println("String is empty");
}

// Check for null string
if (nullString == null) {
System.out.println("String is null");
}

Regular Expressions

Java supports regular expressions through the `java.util.regex` package, which includes the Pattern and Matcher classes. Regular expressions provide a powerful way to search, edit, and manipulate text based on pattern matching.

String text = "Java 123 JavaScript"; 
Pattern pattern = Pattern.compile("\\d+"); // Pattern to match one or more digits
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
System.out.println("Found a number: " + matcher.group()); // Outputs "123"
}

String Formatting

Java also offers the String.format() method and the java.text.MessageFormat class for formatting strings, which is particularly useful for creating strings with variable data in a readable manner.

String formattedString = String.format("My favorite language is %s!", "Java"); 
System.out.println(formattedString); // Outputs "My favorite language is Java!"

--

--

Mayank Pant
Mayank Pant

Written by Mayank Pant

0 followers

My notes for future me