Reversing Characters in a String Builder – Selected API Classes

Reversing Characters in a String Builder

The following method in the class StringBuilder reverses the contents of a string builder:

StringBuilder reverse()

Examples of using methods that modify string builders:

Click here to view code image

StringBuilder builder = new StringBuilder(“banana split”);   // “banana split”
builder.delete(4,12);                                        // “bana”
builder.append(42);                                          // “bana42”
builder.insert(4,”na”);                                      // “banana42”
builder.reverse();                                           // “24ananab”
builder.deleteCharAt(builder.length()-1);                    // “24anana”
builder.replace(0, 2, “b”);                                  // “banana”
builder.append(‘s’);                                         // “bananas”

All of the previously mentioned methods modify the contents of the string builder and return a reference value denoting the current string builder. This allows chaining of method calls. The method calls invoked on the string builder denoted by the reference builder can be chained as follows, giving the same result:

Click here to view code image

builder.delete(4,12).append(42).insert(4,”na”).reverse()
       .deleteCharAt(builder.length()-1).replace(0, 2, “b”)
       .append(‘s’);                                          // “bananas”

The method calls in the chain are evaluated from left to right, so the previous chain of calls is interpreted as follows:

Click here to view code image

((((((builder.delete(4,12)).append(42)).insert(4,”na”)).reverse())
      .deleteCharAt(builder.length()-1)).replace(0, 2, “b”))
      .append(‘s’);                                           // “bananas”

Each method call returns the reference value of the modified string builder, which is then used to invoke the next method. The string builder remains denoted by the reference builder.

The compiler uses string builders to implement string concatenation with the + operator in String-valued non-constant expressions. The following code illustrates this optimization:

Click here to view code image

String theChosen = “U”;
String str1 = 4 + theChosen + “Only”;           // (1) Non-constant expression.

The assignment statement at (1) is equivalent to the following code using a string builder:

Click here to view code image

String str2 = new StringBuilder().
                  append(4).append(theChosen).append(“Only”).toString(); // (2)

The code at (2) does not create any temporary String objects when concatenating several strings, since a single StringBuilder object is modified and finally converted to a String object having the string content “4UOnly”.

Leave a Reply

Your email address will not be published. Required fields are marked *