Chapter 4 |
Methods of class StringBuilder
Have you paid attention to the fact that when we operated with String class instances and its methods, we did not change them? This is because Strings are immutable in Java. In the following example, we only change the reference, but not the content.
String s = "Finland"; s = "Estonia";
The first line creates an object with content Finland, and assigns it to the variable s. The second line creates an object with content Estonia and assigns it again to the variable s. As a result, the reference to the first object is lost.
To sum up, String class
treats strings as immutable objects. If there is a need to change a String object, we have to use StringBuilder class
.
Useful link: The full list of StringBuilder class fields, constructors, methods and their description can be found here. Pay attention to the signatures (the number of parameters and their data type) and the return type!
StringBuilder considers strings as a mutable sequence of characters. StringBuilder class has four constructors and numerous methods. We will list the most important ones for this chapter:
append
(appends strings to the end of the sequence; if needed, increases the size of the buffer)capacity
(returns the current capacity of the string buffer)charAt
(returns the character at the specified index)delete
(removes characters)insert
(inserts a string at the specified index of the sequence)length
(returns the length)setCharAt
(replaces the char at the specified index)setLength
(changes the length of the character sequence)indexOf
(returns the index within this string of the first occurrence of the specified substring)toString
(returns a string representing the data in this sequence)replace
(replaces the characters in a substring of this sequence with specified characters)reverse
(causes this character sequence to be replaced by the reverse of the sequence)
Here are a few examples of operations with the StringBuilder objects:
// Append new sequences to the existing one int[] numbers = { 3, 5, 7, 11 }; StringBuilder sb = new StringBuilder(50); // create StringBuilder class instance with capacity of 50 sb.append("The first integers are "); for (int num : numbers) { sb.append(num); sb.append(' '); } // "The first integers are 3 5 7 11" // replace spaces after the first integers with commas int i = sb.indexOf(" ", "The first integers are ".length()); // the space after "3" while (i != -1) { sb.replace(i, i + 1, ","); i = sb.indexOf(" ", i + 1); } System.out.println(sb); // “The first integers are 3,5,7,11”
Chapter 4 |