Session 4 |
Methods of class StringBuilder
Have you paid attention to the fact that when we operate with String class instances and its methods, we do 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 whose content is Finland, and assigns it to variable s. The second line creates an object whose content is Estonia and assigns it again to 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 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 session:
append
(appends strings to the end of the sequence; if needed, increases the size of the buffer)capacity
(current capacity)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)
A few examples:
// 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β
Session 4 |