Site Search:

Manipulate data using the StringBuilder class and its methods


Back OCAJP


In previous post Creating and manipulating Strings, we have studied immutable String class and how to use JVM string pool to cache String objects. When your program needs to use tons of short lived String objects -- for example adds friends' name to a guest list -- even with string pool, the cost is still high.



OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String... args) {
    int[][] matrix = new int[10][10];
    String raws = null;
    String columns = null;
    Random r = new Random();   
    for(int i = 0; i< matrix.length; i++) {
      for(int j=0; j < matrix[0].length; j++) {
        matrix[i][j] = r.nextInt();
        //in worst case need 301 strings to be added to string pool
        raws += matrix[i][j] + ","; 
      } 
    }

    for(int i = 0; i< matrix[0].length; i++) {
      for(int j=0; j< matrix.length; j++) {
        columns += matrix[j][i]+",";  //another 99 (no maxtrix[0][0]) strings
      } 
    }
    System.out.println(raws);
    System.out.println(columns);
  }
}
OCAJP>javac test.java
OCAJP>java test
null1589705920,-1884031169,757841953,1900362784,-1745910720,900648600,1056665642,-1986740297,-2086381277,2014059785,84736626,830727229,448731706,-653172760,-529000606,1929243861,1527123917,-1935804027,1858524018,97963462,1516535830,478502542,424852154,-1811041665,525686515,311702965,1997580744,-693936166,321131734,-707441265,-569878604,-1912736092,785987839,848661695,1878125938,-798500259,524720877,-621526957,2051358311,500154427,-1963235567,1925147757,44791358,1707879028,1563341508,858915622,-1233301509,-2075864131,-1507140741,-870046290,1812277839,1044958989,-474798791,781964215,-941781714,331374502,-1384100796,1387179283,221901982,672517461,445120027,-1500796517,1584461010,1944107255,915303846,-1601311917,-923006089,-2007780033,2076210863,1218973387,110277196,-1830541385,487064721,2022284743,1498121976,1889580548,-1699499986,-204044254,-603481065,1831519085,1730529574,1558365934,-400996459,1972093598,-1949417916,-589132320,1046020671,-882417752,989206844,715239147,-1175442281,-1650997685,-266698349,1725633578,-817181465,-665745288,1241545438,594768898,-1491166568,1153493264,
null1589705920,84736626,1516535830,-569878604,-1963235567,1812277839,445120027,110277196,1730529574,-1175442281,-1884031169,830727229,478502542,-1912736092,1925147757,1044958989,-1500796517,-1830541385,1558365934,-1650997685,757841953,448731706,424852154,785987839,44791358,-474798791,1584461010,487064721,-400996459,-266698349,1900362784,-653172760,-1811041665,848661695,1707879028,781964215,1944107255,2022284743,1972093598,1725633578,-1745910720,-529000606,525686515,1878125938,1563341508,-941781714,915303846,1498121976,-1949417916,-817181465,900648600,1929243861,311702965,-798500259,858915622,331374502,-1601311917,1889580548,-589132320,-665745288,1056665642,1527123917,1997580744,524720877,-1233301509,-1384100796,-923006089,-1699499986,1046020671,1241545438,-1986740297,-1935804027,-693936166,-621526957,-2075864131,1387179283,-2007780033,-204044254,-882417752,594768898,-2086381277,1858524018,321131734,2051358311,-1507140741,221901982,2076210863,-603481065,989206844,-1491166568,2014059785,97963462,-707441265,500154427,-870046290,672517461,1218973387,1831519085,715239147,1153493264,


Java have mutable class StringBuilder, each time new string is append at the end without creating a new interim String object each time.



/*
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.lang;


/**
 * A mutable sequence of characters.  This class provides an API compatible
 * with {@code StringBuffer}, but with no guarantee of synchronization.
 * This class is designed for use as a drop-in replacement for
 * {@code StringBuffer} in places where the string buffer was being
 * used by a single thread (as is generally the case).   Where possible,
 * it is recommended that this class be used in preference to
 * {@code StringBuffer} as it will be faster under most implementations.
 *
 * <p>The principal operations on a {@code StringBuilder} are the
 * {@code append} and {@code insert} methods, which are
 * overloaded so as to accept data of any type. Each effectively
 * converts a given datum to a string and then appends or inserts the
 * characters of that string to the string builder. The
 * {@code append} method always adds these characters at the end
 * of the builder; the {@code insert} method adds the characters at
 * a specified point.
 * <p>
 * For example, if {@code z} refers to a string builder object
 * whose current contents are "{@code start}", then
 * the method call {@code z.append("le")} would cause the string
 * builder to contain "{@code startle}", whereas
 * {@code z.insert(4, "le")} would alter the string builder to
 * contain "{@code starlet}".
 * <p>
 * In general, if sb refers to an instance of a {@code StringBuilder},
 * then {@code sb.append(x)} has the same effect as
 * {@code sb.insert(sb.length(), x)}.
 * <p>
 * Every string builder has a capacity. As long as the length of the
 * character sequence contained in the string builder does not exceed
 * the capacity, it is not necessary to allocate a new internal
 * buffer. If the internal buffer overflows, it is automatically made larger.
 *
 * <p>Instances of {@code StringBuilder} are not safe for
 * use by multiple threads. If such synchronization is required then it is
 * recommended that {@link java.lang.StringBuffer} be used.
 *
 * <p>Unless otherwise noted, passing a {@code null} argument to a constructor
 * or method in this class will cause a {@link NullPointerException} to be
 * thrown.
 *
 * @author      Michael McCloskey
 * @see         java.lang.StringBuffer
 * @see         java.lang.String
 * @since       1.5
 */
public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{

    /** use serialVersionUID for interoperability */
    static final long serialVersionUID = 4383685877147921099L;

    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity of 16 characters.
     */
    public StringBuilder() {
        super(16);
    }

    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity specified by the {@code capacity} argument.
     *
     * @param      capacity  the initial capacity.
     * @throws     NegativeArraySizeException  if the {@code capacity}
     *               argument is less than {@code 0}.
     */
    public StringBuilder(int capacity) {
        super(capacity);
    }

    /**
     * Constructs a string builder initialized to the contents of the
     * specified string. The initial capacity of the string builder is
     * {@code 16} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

    /**
     * Constructs a string builder that contains the same characters
     * as the specified {@code CharSequence}. The initial capacity of
     * the string builder is {@code 16} plus the length of the
     * {@code CharSequence} argument.
     *
     * @param      seq   the sequence to copy.
     */
    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }

    @Override
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

    @Override
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }
...


Enough source code reading (if you really did), let's take a look at some OCA oriented examples.


OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String... args) {
    StringBuffer sb = new StringBuffer();
    System.out.println(sb.length());
    StringBuffer sb1 = sb.append("12345");  //append returns the reference to original stringBuffer
    sb1.append("678");
    sb.insert(sb.length(), "9");  //same as sb.append("9");
    //sb.append('9');  //not compile
    System.out.println(sb.toString()); 
    System.out.println(sb); //toString() is called by default
    System.out.println(sb.equals(sb1));
    System.out.println(sb==sb1);  //true
    System.out.println("charAt");
    System.out.println(sb.charAt(0));
    System.out.println(sb.charAt(8));
    System.out.println("substring");
    System.out.println(sb.substring(0,8));
    System.out.println("indexOf");
    System.out.println(sb.indexOf("123"));
    System.out.println(sb.indexOf("9"));
    //System.out.println(sb.indexOf(9));  //char cannot be converted to String
    //System.out.println(sb.indexOf('9'));  //int cannot be converted to String
    System.out.println("delete, deleteCharAt, insert");
    sb.delete(2,5);  //3 character
    System.out.println(sb.toString());
    sb.insert(2,"345");
    System.out.println(sb.toString());
    System.out.println(sb.deleteCharAt(2));
    System.out.println(sb.insert(2,"3"));
    System.out.println("reverse");
    System.out.println(sb.reverse());
  }
}
OCAJP>javac test.java 
OCAJP>java test
0
123456789
123456789
true
true
charAt
1
9
substring
12345678
indexOf
0
8
delete, deleteCharAt, insert
126789
123456789
12456789
123456789
reverse
987654321


StringBuilder is not thread safe, the StringBuffer is the thread safe version of StringBuilder. They define the same public methods. Since StringBuffer have to synchronize for thread safe, it is slower than StringBuilder.
Back OCAJP