In this post, you will learn to:

  • Explain StringBuilder class and its methods.
  • Explain StringTokenizer class and its methods.

‘StringBuilder’ Class

The StringBuilder class provides various methods to manipulate the string object. Objects of StringBuilder class are growable and flexible. Characters or strings can be inserted in the StringBuilder object and they can also be appended at the end.

The StringBuilder objects can be constructed in various ways. The different forms are as follows:

  • StringBuilder(): default constructor reserves room for 16 characters.
  • StringBuilder(int capacity): constructs an object with no characters in it but reserves room for characters specified in the capacity argument.
  • StringBuilder(String str): constructs an object that is initialized to the contents of the specified string, str

‘StringBuilder’ Methods

The StringBuilder class provides various methods for appending, inserting, deleting, and reversing strings.

append()

The append() method appends values to the end of the StringBuilder object. This method can take different arguments, including boolean, char, double, int, float, double, and others,but the most common one will be the String argument.

Syntax:

StringBuilder append(String str)
StringBuilder append(int num)
StringBuilder append(Object obj)

For each append method, String.valueOf() method is called to convert the parameter into the corresponding string representation value and then the new string is appended to the StringBuilder object.

The following code snippet demonstrates the append() method of StringBuilder class.

Code Snippet:

StringBuilder str = new StringBuilder("Java ");
str.append("Programming ");   //appends string "Programming"
System.out.println(str);
str.append(5.0);   //appends float value "5.0"
System.out.println(str);

Output:

Java Programming 
Java Programming 5.0

insert()

The insert() method inserts one string into another. Like append(), it calls the String.valueOf() method to get the string representation of the value. The new string is inserted into the invoking StringBuilder object.

Syntax:

StringBuilder insert(int insertPosition, String str)
StringBuilder insert(int insertPosition, char ch)
StringBuilder insert(int insertPosition, float f)

Here, insertPosition indicates the position at which the new string is to be inserted to the invoking StringBuilder object. The following code snippet inserts 5.0 between Java and Programming.

Code Snippet:

StringBuilder str = new StringBuilder("Java Programming");
str.insert(5,"5.0 „);
System.out.println(str);

Output:

delete()

The delete() method deletes characters from the invoking StringBuilder object.

Syntax:

StringBuilder delete(int start, int end)

Here, start specifies the index of the first character to remove and end specifies an index one character before the last character to remove. The statement, StringBuilder delete(9, 12) will delete characters at index 9, 10, and 11, but not 12. The following code snippet demonstrates the delete() method of StringBuilder class.

Code Snippet:

StringBuilder str = new StringBuilder("Java Programming Language 5.0");
System.out.println("Before Deletion : "+ str);
str.delete(12,16); //deletes "ming"
System.out.println("After Deletion: "+str);

Output:

Before Deletion : Java Programming Language 5.0
After Deletion: Java Program Language 5.0

reverse()

The reverse() method is used to reverse the characters within a StringBuilder object.

Syntax:

The following code demonstrates the use of reverse() method.

Code Snippet:

StringBuilder str = new StringBuilder("Java Programming Language  5.0");
System.out.println("Original String : "+ str);
str.reverse(); //reversing the string
System.out.println("String after reverse: "+ str);

Output:

Original String : Java Programming Language 5.0
String after reverse: 0.5 egaugnaL gnimmargorP avaJ

charAt()

The charAt() method returns the character value at the specified index.

Syntax:

The following code snippet demonstrates the use of charAt() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Tec Geeks");
System.out.println(sb.charAt(7));

Output:

deleteCharAt()

The deleteCharAt() method deletes a character at the specified position.

Syntax:

StringBuilder deleteCharAt(int index);

The following code snippet demonstrates the use of deleteCharAt() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Tec Geeks");
System.out.println(sb.deleteCharAt(5)); //deletes the char at index 5

Output:

getChars()

The getChars() method copies specified number of character into an array.

Syntax:

void getChars(int begin, int end, char[] destArray, int destArraybegin);

The following code snippet demonstrates the use of getChars() method.

Code Snippet:

char[] array = new char[6];
StringBuilder sb = new StringBuilder("Tec Geeks Blog");
sb.getChars(0,6,array,0); 
System.out.println(array);

The code copies characters from the StringBuilder object, sb, starting from index zero to index five. The copied characters are placed in the character array named array starting from index zero.

Output:

length()

The length() method returns the total number of characters from the StringBuilder object.

Syntax:

The following code snippet demonstrates the use of length() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Tec Geeks Blog");
System.out.println(sb.length());

Output:

replace()

The replace() method replaces characters from the StringBuilder object with new characters.

Syntax:

StringBuilder replace(int begin, int end, String str);

The following code snippet demonstrates the use of replace() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Tec Geeks Blog");
System.out.println(sb.replace(15,18,"Posts"));

Output:

setCharAt()

The setCharAt() method replaces a character from the StringBuilder object with a new character at the specified index.

Syntax:

void setCharAt(int index, char ch);

The following code snippet demonstrates the use of setCharAt() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Tec Geeks Blog");
sb.setCharAt(4,'g'); //replaces upper case 'G' with lower case 'g'
System.out.println(sb);

Output:

setLength()

The setLength() method sets the length of the StringBuilder to a new value.

Syntax:

void setLength(int newLength);

If the new length is greater than the current length, all the new characters are set to null characters (‘u0000’). If the new length is less than the current length, the first newLength characters of the old array will be preserved, and the remaining characters will be truncated. The following code snippet demonstrates the use of setLength() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Martin Global Learning Solutions"); 
sb.setLength(35); // original length = 32, New Length = 35;
System.out.println(sb);
sb.setLength(13); //New Length = 13
System.out.println(sb);

Output:

Martin Global Learning Solutions
Martin Global.

appendCodePoint()

The appendCodePoint() method appends a Unicode code point to the StringBuilder object.

Syntax:

StringBuilder appendCodePoint(int codePoint);

The following code snippet demonstrates the use of appendCodePoint() method.

Code Snippet:

StringBuilder sb = new StringBuilder("Martin Global Learning Solutions"); 
System.out.println(sb.appendCodePoint(123)); // Inserts the character 
'{'

Output:

Martin Global Learning Solutions{

capacity()

The capacity() method returns the current capacity of the StringBuilder object. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

Syntax:

The following code snippet demonstrates the use of capacity() method.

Code Snippet:

StringBuilder sb = new StringBuilder();   // default capacity
System.out.println(sb.capacity());   //returns 16
sb = new StringBuilder("Aptech Global Learning Solutions"); 
System.out.println(sb.length());   // returns 32 
// default capacity + newly inserted character length
System.out.println(sb.capacity());   //returns 48

Output:

substring()

The substring() method creates a new string from the StringBuilder object.

Syntax:

String substring(int startIndex);
String substring(int startIndex, int endIndex);

The second method returns a substring from the StringBuilder object. The substring begins at the specified startIndex and extends to the character at index endIndex – 1.

The following code snippet demonstrates the use of subString() method.

Code Snippet:

String str;
StringBuilder sb = new StringBuilder("Martin Global Learning Solutions"); 
str = sb.substring(7); // returns the substring starting at index 7
System.out.println(str);
// returns the substring starting at index 7 and ends at index 21
str = sb.substring(7, 22);
System.out.println(str);

Output:

Global Learning Solutions
Global Learning

‘StringTokenizer’ Class

Many text manipulation utilities require a tokenizer function which breaks up lines of text into subunits called tokens based on a specific delimiter. The most common delimiter is whitespace which yields words as the tokens. The StringTokenizer class in Java performs this type of task.

The StringTokenizer object can be created in the following ways:

  • StringTokenizer(String str): creates a string tokenizer for the specified string.
  • StringTokenizer(String str, String delim): creates a string tokenizer for the specified string based on delimiters specified by delim argument.
  • StringTokenizer(String str, String delim, boolean returnDelims): creates a string tokenizer for the specified string based on delimiters specified by delim argument. The delimiter characters are returned as tokens, if the returnDelims flag is true, otherwise the delimiter characters are skipped.

‘StringTokenizer’ Methods

The StringTokenizer class provides methods to count the number of tokens, the next element in a string, and so on.

countTokens()

The countTokens() method returns the number of tokens remaining in the specified string tokenizer object.

Syntax:

The following code snippet uses the countTokens() method to print the number of tokens in the StringTokenizer object.

Code Snippet:

String str = "Java Programming Language Fundamentals";

//creates a StringTokenizer object
StringTokenizer strToken = new StringTokenizer(str); 

int count = strToken.countTokens(); //count the tokens
System.out.println("Number of Tokens: "+count);

Output:

hasMoreElements()

The hasMoreElements() method determines if there are any elements left to be read or tokenized.

Syntax:

boolean hasMoreElements();

The method returns a boolean value. A return value of true indicates that the string tokenizer object has more elements; a return value of false indicates that there are zero elements left to be read. The following code snippet demonstrates the hasMoreElements() method in the StringTokenizer object.

Code Snippet:

String str = "Java Programming Language Fundamentals";

//creates a StringTokenizer object
StringTokenizer strToken = new StringTokenizer(str); 

//Checks whether the string tokenizer object has elements
if(strToken.hasMoreElements()) { 
   System.out.println("Has more elements");
}
else {
   System.out.println("No elements");
}

Output:

hasMoreTokens()

The hasMoreTokens() method tests whether the specified tokenizer’s string has more than one tokens.

Syntax:

The method returns true, if there is at least one token in the string after the current position, otherwise it returns false. The following code snippet demonstrates the hasMoreTokens() method in the StringTokenizer object.

Code Snippet:

String str = "Java Programming Language Fundamentals";

//creates a StringTokenizer object
StringTokenizer strToken = new StringTokenizer(str); 

//Checks whether the string tokenizer object has tokens
if(strToken.hasMoreTokens()) { 
   System.out.println("Has more tokens");
}
else {
   System.out.println("No tokens");
}

Output:

nextElement()

The nextElement() method returns the next element of the specified StringTokenizer object.

Syntax:

The following code snippet prints the elements one by one from a StringTokenizer object.

Code Snippet:

String str = "Java Programming Language Fundamentals";

//creates a StringTokenizer object
StringTokenizer strToken = new StringTokenizer(str); 

//prints the elements one by one
while(strToken.hasMoreTokens()) { 
    System.out.println(strToken.nextElement());
}

Output:

Java
Programming
Language
Fundamentals.

nextToken()

The nextToken() method returns the next token from the tokenizer object.

Syntax:

The following code snippet prints the tokens one by one from a StringTokenizer object.

Code Snippet:

String str = "Java Programming Language Fundamentals";
 
//creates a StringTokenizer object
StringTokenizer strToken = new StringTokenizer(str); 
//prints the tokens one by one
while(strToken.hasMoreTokens()){
   System.out.println(strToken.nextToken());
}

Output:

Java
Programming
Language
Fundamentals