StringBuffer and StringTokenizer in Java

The string concept has various topics to dig deep into. A couple of such main topics are the StringBuffer and StringTokenizer classes in java. This article will make you understand the significance of these two classes.

StringBuffer Class in Java

The StringBuffer class lets us create a mutable string object which can be altered even after its creation. We can represent the growable and writable character sequence using this class.

StringBuffer in Java is thread-safe; therefore, multiple threads cannot access it simultaneously. Any number of characters and substrings can be inserted or appended to the existing one with StringBuffer.

Constructors in Java StringBuffer Class:

Constructor Description
StringBuffer() We can create an empty StringBuffer with 16 as the initial capacity.
StringBuffer(String str) This lets us create a StringBuffer with a particular string.
StringBuffer(int capacity) We can create an empty StringBuffer with the desired capacity length.

Important methods of Java StringBuffer class:

Modifier and Type Method Description
public synchronized StringBuffer append(String s) It appends the given String with the existing String. We can append this method as append(char), append(boolean), append(int), append(float), append(double)etc.
public synchronized StringBuffer insert(int offset, String s) It inserts the given String at the desired position. We can overload this method using insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String str)0 It replaces the String from the mentioned start and end index.
public synchronized StringBuffer delete(int startIndex, int endIndex) It deletes the String from the mentioned start and end index.
public synchronized StringBuffer reverse() It reverses the string.
public int capacity() It returns the current capacity.
public void ensureCapacity(int minimumCapacity) It ensures that the capacity is at least equal to the minimum.
public char charAt(int index) It returns the character from the mentioned position.
public int length() It returns the length of the string.
public String substring(int beginIndex) It returns the substring from the given beginIndex.
Public String substring(int beginIndex, int endIndex) It returns the substring from the given beginIndex and endIndex.

String mutability:

Any strings that are mutable or can be modified are mutable strings. To create these mutable strings, we can make use of the StringBuffer class.

1. StringBuffer append() method:

It concatenates the given argument with the String.

Sample program using StringBuffer class append():

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer(“Learn Java”);
buff.append(“with FirstCode”);
System.out.println(buff);
}
}

Output:

Learn Java with FirstCode

2. StringBuffer insert() method:

This method inserts the mentioned String with the existing String from the given position.

Sample program using StringBuffer insert() method:

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer(“Java”);
buff.insert(2, “FirstCode”);
System.out.println(buff);
}
}

Output:

JaFirstCodeva

3. StringBuffer replace() method:

This method replaces the given String from the mentioned beginIndex and endIndex.

Sample program using StringBuffer replace() method:

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer(“FirstCode”);
buff.replace(2,5, “Java”);
System.out.println(buff);
}
}

Output:

FiJavaode

4. StringBuffer delete() Method:

This method deletes the String from the mentioned beginIndex and endIndex.

Sample program using StrinBuffer delete() method:

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer(“FirstCode”);
buff.delete (2,5,);
System.out.println(buff);
}
}

Output:

Fiode

5. StringBuffer reverse() Method:

This method reverses the current String.

Sample program for StringBuffer reverse() method:

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer(“FirstCode”);
buff.reverse();
System.out.println(buff);
}
}

Output:

edoCtsriF

6. StringBuffer capacity() method:

This method returns the capacity of the particular buffer. The value of it is 16. When the number of characters, the operation performed is: (oldcapacity*2)+2. For example, if the value of your current capacity is 16, it would turn out to be (16*2)+2 =34.

Sample program using StringBuffer capacity() method:

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer();
System.out.println(buff.capacity()); // default value 16
buff.append(“FirstCode”);
System.out.println(buff.capacity); // allotted value 16
buff.append(“Learn Java with FirstCode”);
System.out.println(buff.capacity()); //(16*2)+2=34
}
}

Output:

16
16
34

7. StringBuffer ensureCapacity() method:

This method ensures that the given minimum capacity is minimum to the current capacity. If it is encountered to be more than that of the current capacity, the capacity is increased by (oldcapacity*2)+2. For example, if the value of your current capacity is 16, it would turn out to be (16*2)+2 =34.

Sample program using Java StringBuffer ensureCapcity() method:

class FirstCode{
public static void main(String args[]){
StringBuffer buff = new StringBuffer();
System.out.println(buff.capacity()); // default value 16
buff.append(“FirstCode”);
System.out.println(buff.capacity); // allotted value 16
buff.append(“Learn Java with FirstCode”);
System.out.println(buff.capacity()); //(16*2)+2=34
buff.ensureCapacity(15); // no changes occur
System.out.println(buff.capacity()); // it is 34
buff.ensureCapacity(40); // (34*2)+2
System.out.println(buff.capacity()); // the current value is 70
}
}

Output:

16
16
34
34
70

Java StringTokenizer Class

The StringTokenizer class in Java breaks a string into multiple tokens. This class is present in the Java.util package. It is a legacy class that makes breaking a string easier in Java.

For example: Let us assume that the given input string is: “Learn Java with FirstCode.” This can be split into various tokens using StringTokenizer. Therefore, the output becomes: “Learn, Java, with, FirstCode” as separate words.

class diagram of stringtokenizer in java

Constructor Destructor
StringTokenizer(String str) It creates a StringTokenizer with the mentioned String.
StringTokenizer(String str, String delim) It creates a StringTokenizer with the mentioned String and delimiter.
StringTokenizer(String str, String delim, boolean returnValue) It creates a StringTokenizer with the mentioned String, delimiter, and returnValue. If ‘true’ is the return value, the delimiter characters are considered tokens. When false, the delimiter character serves to separate tokens.

Methods of Java StringTokenizer class:

Methods Description
boolean hasMoreTokens() Checks the availability of tokens.
String nextToken() Returns the following token from the StringTokenizer object.
String nextToken(Stringdelim) Returns the following token on the basis of delimiter.
boolen hasMoreElements() Similar to the hasMoreTokens()
Object nextElement() Similar to nextToken(). But the return type here is Object.
int countTokens() Returns the total number of tokens.

Sample program using StringTokenizer class in java:

import java.util.StringTokenizer;
public class FirstCode{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(“Learn Java with FirstCode”,””);
while (st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}

Output:

Learn
Java
with
FirstCode

Sample program for java nextToken(String delim) method:

import java.util.StringTokenizer;
public class FirstCode{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(“Learn,Java,with,FirstCode”,””);
System.out.println(“The Next Token is: ” + st.nextToken(“,”));
}
}

Output:

The Next Token is: Learn

Sample program for java hasMoreTokens() method:

import java.util.StringTokenizer;
public class FirstCode{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(“Learn Java with FirstCode”,””);
while (st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}

Output:

Learn
Java
with
FirstCode

Sample program for java hasMoreElements():

The method hasMoreElements() is similar to that of the hasMoreTokens() method of the StringTokenizer class. The only slight change is that this class can implement the Enumeration interface.

import java.util.StringTokenizer;
public class FirstCode{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(“Learning is easy with FirstCode”,””);
while (st.hasMoreElements()){
System.out.println(st.nextToken());
}
}
}

Output:

Learning
is
easy
with
FirstCode

Sample program for java nextElement() method:

import java.util.StringTokenizer;
public class FirstCode{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(“Learn Java with FirstCode”,””);
while (st.hasMoreTokens()){
System.out.println(st.nextElement());
}
}
}

Output:

Learn
Java
with
FirstCode

Sample program using java countTokens() method:

import java.util.StringTokenizer;
public class FirstCode{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer(“Learn Java with FirstCode”,””);
System.out.println(“The count of tokens is: ” + st.countTokens());
}
}

Output:

The count of tokens is: 4

Conclusion

Now you might be clear about the StringBuffer and StringTokenizer concepts in the Java String class. In short, the StringBuffer is used when there are numerous modifications to be done in the String. It is mutable. The StringTokenizer allows us to break a String into various tokens.

Leave a Reply

Your email address will not be published. Required fields are marked *