Session 4 |
StringBuilder class methods
Have you paid attention to the fact that when we operate with String class instances and their methods, we do not change the instances themselves? 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 instance whose content is Finland, and assigns to variable s the reference to the instance. The second line creates an instance whose content is Estonia and assigns to variable s the reference to the instance. The first instance stays immutable, but we have lost the reference to it.
To sum up, String class
treats Strings as an immutable objects. If there is a need to change Strings, 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 |