Bright Java Tutorial

is brought to you by DoITBright LLC

Java

StringBuffer And StringBuilder

Aside from the String class, there are two other alternatives. These are the java.lang.StringBuilder and java.lang.StringBuffer. Each of the above mentioned classes will be discussed through the example found below.

  package com.example.core;

  /**
   * This is to demonstrate the use of StringBuffer and 
   * StringBuilder. These are good alternatives to 
   * String objects.
   * 
   * @author Rolan Liwanag
   *
   */
  public class StringBufferAndStringBuilder {

	public static void main(String[] args) {
	  /*
	   * StringBuffer methods are synchronized. This means, 
	   * StringBuffer is thread safe. synchronized  
	   * definition according to Java is, it is a keyword 
	   * that is placed along the method definition which 
	   * makes the method not to be executed by more than 
	   * 1 thread. We will talk about threads and methods 
	   * at some other time. Let us leave it as it is 
	   * for now.
	   */
	  StringBuffer strBuf = new StringBuffer();
	  System.out.println("A newly created StringBuffer " 
	    + "named strBuf has a value of '" + strBuf + "'.");
	  //Another way of creating a StringBuffer object
	  StringBuffer anotherStrBuf 
	    = new StringBuffer("Just a value");
	  System.out.println("The newly created anotherStrBuf" 
	    + " has a value of '" + anotherStrBuf + "'.");
	  //to concatenate the string value of a StringBuffer
	  strBuf.append("Is Java cool [true or false]?" 
	    + " Answer is ");
	  strBuf.append(true);
	  System.out.println("The new value of strBuf is " 
	    + strBuf);
	  /*
	   * StringBuilder is very similar to StringBuffer. 
	   * The main difference is, the StringBuilder
	   * methods are not synchronized which makes it not 
	   * thread safe. However, it also makes the
	   * StringBuilder faster than StringBuffer.
	   */
	  StringBuilder strBuild = new StringBuilder();
	  System.out.println("A newly created StringBuilder " 
	    + "named strBuild has a value of '" + strBuild 
	    + "'.");
	  //Another way of creating a StringBuilder object
	  StringBuilder anotherStrBuild 
	    = new StringBuilder("Just a value");
	  System.out.println("The newly created anotherStrBuild" 
	    + " has a value of '" + anotherStrBuild + "'.");
	  // to concatenate the string value of a StringBuilder
	  strBuild.append("Is Java cool [true or false]? " 
	    + "Answer is ");
	  strBuild.append(true);
	  System.out.println("The new value of strBuild is '" 
	    + strBuild + "'.");
	  //if you decide to do this for some reason, 
	  //it will also work...
	  String ex = strBuild + " some string value";
	  System.out.println(ex);
	  /*
	   * Both StringBuffer and StringBuilder are mutable 
	   * objects. The object instance is stored
	   * in the heap and can be modified.
	   */
	}
  }
                            



Back    Next