Java Reference
In-Depth Information
// Append " Java" to the StringBuilder's content
sb.append(" Java"); // Now, sb contains "Hello Java"
// Get a String from the StringBuilder
String s2 = sb.toString(); // s2 contains "Hello Java"
Unlike String , StringBuilder has a setLength() method, which takes its new length as an argument. If the new
length is greater than the old length, the extra positions are filled with null characters (a null character is \u0000 ).
If the new length is less than the old length, its content is truncated to fit in the new length.
// Length is 5
StringBuilder sb = new StringBuilder("Hello");
// Now the length is 7 with last two characters as null character '\u0000'
sb.setLength(7);
// Now the length is 2 and the content is "He"
sb.setLength(2);
The StringBuilder class has a reverse() method, which replaces its contents with the same sequence
of characters, but in reverse order.
Listing 11-5 illustrates the use of some of the methods of the StringBuilder class.
Listing 11-5. Using a StringBuilder Object
// StringBuilderTest.java
package com.jdojo.string;
public class StringBuilderTest {
public static void main(String[] args) {
// Create an empty StringNuffer
StringBuilder sb = new StringBuilder();
printDetails(sb);
// Append "blessings"
sb.append("blessings");
printDetails(sb);
// Insert "Good " in the beginning
sb.insert(0, "Good ");
printDetails(sb);
// Delete the first o
sb.deleteCharAt(1);
printDetails(sb);
// Append " be with you"
sb.append(" be with you");
printDetails(sb);
// Set the length to 3
sb.setLength(3);
printDetails(sb);
 
Search WWH ::




Custom Search