4.2. Mutable strings: StringBuilder

[9.1] Manipulate data using the StringBuilder class and its methods

The class StringBuilder is defined in the package java.lang, and it has a mutable sequence of characters. You should use the class StringBuilder when you’re dealing with larger strings or modifying the contents of a string often. Doing so will improve the performance of your code. Unlike StringBuilder, the String class has an immutable sequence of characters. Every time you modify a string that’s represented by the String class, your code creates new String objects instead of modifying the existing one.

Exam Tip

You can expect questions on the need for the StringBuilder class and its comparison with the String class.

Let’s work with the methods of the class StringBuilder. Because StringBuilder represents a mutable sequence of characters, the main operations on StringBuilder are related to the modification of its value by adding another value at the end or at a particular position, deleting characters, or changing characters at a particular position.

4.2.1. The StringBuilder class is mutable

In contrast to the class String, the class StringBuilder uses a non–final char array to store its value. Following is a partial definition of the class AbstractStringBuilder (the superclass of the class StringBuilder). It includes the declaration of the variables value and count, which are used to store the value of StringBuilder and its length, respectively (the relevant code is in bold):

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char value[];
    /**
     * The count is the number of characters used.
     */
    int count;
//.. rest of the code
}

This information will come in handy when we discuss the methods of class StringBuilder in the following sections.

4.2.2. Creating StringBuilder objects

You can create objects of the class StringBuilder using multiple overloaded constructors, as follows:

constructs a StringBuilder object with no characters in it and an initial capacity of 16 characters. constructs a StringBuilder object that contains the same set of characters as contained by the StringBuilder object passed to it. constructs a StringBuilder object with no characters and an initial capacity of 50 characters. constructs a StringBuilder object with an initial value as contained by the String object. Figure 4.13 illustrates StringBuilder object sb4 with the value Shreya Gupta.

Figure 4.13. The StringBuilder object with character values and their corresponding storage positions

When you create a StringBuilder object using its default constructor, the following code executes behind the scenes to initialize the array value defined in the class StringBuilder itself:

When you create a StringBuilder object by passing it a String, the following code executes behind the scenes to initialize the array value:

The creation of objects for the class StringBuilder is the basis for the next Twist in the Tale exercise. Your task in this exercise is to look up the Java API documentation or the Java source code to answer the question. You can access the Java API documentation in a couple of ways:

The answer to the following Twist in the Tale exercise is given in the appendix.

Twist in the Tale 4.2

Take a look at the Java API documentation or the Java source code files and answer the following question:

Which of the following options (there’s just one correct answer) correctly creates an object of the class StringBuilder with a default capacity of 16 characters?

  1. StringBuilder name = StringBuilder.getInstance();
  2. StringBuilder name = StringBuilder.createInstance();
  3. StringBuilder name = StringBuilder.buildInstance();
  4. None of the above

4.2.3. Methods of class StringBuilder

You’ll be pleased to learn that many of the methods defined in the class StringBuilder work exactly like the versions in the class String—for example, methods such as charAt, indexOf, substring, and length. We won’t discuss these again for the class StringBuilder. In this section, we’ll discuss the other main methods of the class StringBuilder: append, insert, and delete.

Figure 4.14 shows the categorization of this class’s methods.

Figure 4.14. Categorization of StringBuilder methods

append()

The append method adds the specified value at the end of the existing value of a StringBuilder object. Because you may want to add data from multiple data types to a StringBuilder object, this method has been overloaded so that it can accept data of any type.

This method accepts all the primitives, String, char array, and Object, as method parameters, as shown in the following example:

You can append a complete char array, StringBuilder, or String or its subset as follows:

Because the method append also accepts a method parameter of type Object, you can pass it any object from the Java API or your own user-defined object:

The output of the previous code is

JavaPerson@126b249

In this output, the hex value (126b249) that follows the @ sign may differ on your system.

When you append an object’s value to a StringBuilder, the method append calls the static String.valueOf() method. The version taking an Object parameter returns the four-letter string “null” if the parameter is null; otherwise, it calls its toString method. If the toString method has been overridden by the class, then the method append adds the String value returned by it to the target StringBuilder object. In the absence of the overridden toString method, the toString method defined in the class Object executes. For your information, the default implementation of the method toString in the class Object returns the name of the class followed by the @ char and unsigned hexadecimal representation of the hash code of the object (the value returned by the object’s hashCode method).

Exam Tip

For classes that haven’t overridden the toString method, the append method results in appending the output from the default implementation of method toString defined in the class Object (if the parameter isn’t null).

It’s interesting to take a quick look at how the append method works for the class StringBuilder. Following is a partial code listing of the method append that accepts a boolean parameter (as explained in the comments):

and determine whether the array value can accommodate four additional characters corresponding to the boolean literal value true. At , the call to expand-Capacity() increases the capacity of the array value (used to store the characters of a StringBuilder object) if it isn’t big enough. adds individual characters of the boolean value true to the array value.

insert()

The insert method is as powerful as the append method. It also exists in multiple flavors (read: overloaded methods) that accept any data type. The main difference between the append and insert methods is that the insert method enables you to insert the requested data at a particular position, but the append method allows you to add the requested data only at the end of the StringBuilder object:

Figure 4.15 illustrates the previous code.

Figure 4.15. Inserting a char using the method insert in StringBuilder

As with String objects, the first character of StringBuilder is stored at position 0. Hence, the previous code inserts the letter r at position 2, which is occupied by the letter n. You can also insert a complete char array, StringBuffer, or String or its subset, as follows:

Figure 4.16 illustrates the previous code.

Figure 4.16. Inserting a substring of String in StringBuilder

Exam Tip

Take note of the start and end positions when inserting a value in a StringBuilder. Multiple flavors of the insert method defined in StringBuilder may confuse you because they can be used to insert either single or multiple characters.

delete() and deleteCharAt()

The method delete removes the characters in a substring of the specified StringBuilder. The method deleteCharAt removes the char at the specified position. Here’s an example showing the method delete:

removes characters at positions 2 and 3. The delete method doesn’t remove the letter at position 4. Figure 4.17 illustrates the previous code.

Figure 4.17. The method delete(2,4) doesn’t delete the character at position 4.

The method deleteCharAt is simple. It removes a single character, as follows:

Exam Tip

Combinations of the deleteCharAt and insert methods can be quite confusing.

trim()

Unlike the class String, the class StringBuilder doesn’t define the method trim. An attempt to use it with this class will prevent your code from compiling. The only reason I’m describing a nonexistent method here is to ward off any confusion.

reverse()

As the name suggests, the reverse method reverses the sequence of characters of a StringBuilder:

Exam Tip

You can’t use the method reverse to reverse a substring of String-Builder.

replace()

Unlike the replace method defined in the class String, the replace method in the class StringBuilder replaces a sequence of characters, identified by their positions, with another String, as in the following example:

Figure 4.18 shows a comparison of the replace methods defined in the classes String and StringBuilder.

Figure 4.18. Comparing the replace methods in String (left) and StringBuilder (right). The method replace in String accepts the characters to be replaced. The method replace in StringBuilder accepts a position to be replaced.

subSequence()

Apart from using the method substring, you can also use the method subSequence to retrieve a subsequence of a StringBuilder object. This method returns objects of type CharSequence:

The method subsequence doesn’t modify the existing value of a StringBuilder object.

4.2.4. A quick note on the class StringBuffer

Although the OCA Java SE 8 Programmer I exam objectives don’t mention the class StringBuffer, you may see it in the list of (incorrect) answers in the OCA exam.

The classes StringBuffer and StringBuilder offer the same functionality, with one difference: the methods of the class StringBuffer are synchronized where necessary, whereas the methods of the class StringBuilder aren’t. What does this mean? When you work with the class StringBuffer, only one thread out of multiple threads can execute your method. This arrangement prevents any inconsistencies in the values of the instance variables that are modified by these (synchronized) methods. But it introduces additional overhead, so working with synchronized methods and the StringBuffer class affects the performance of your code.

The class StringBuilder offers the same functionality as offered by StringBuffer, minus the additional feature of synchronized methods. Often your code won’t be accessed by multiple threads, so it won’t need the overhead of thread synchronization. If you need to access your code from multiple threads, use StringBuffer; otherwise use StringBuilder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119