Java StringBuffer Example

In this post we present to you Java StringBuffer class usage example. When you need to do a lot of modifications on a String object, like concatenating it with another String, removing it’s fragment and so on, the best choice is to use Java StringBuffer class.

ITCuties - Java StringBuffer

ITCuties – Java StringBuffer

Remember that + operator that modifies the String object creates another String object as a result of the join operation. This doesn’t happen when you use the StringBuffer’s append method, so as the result your program uses less memory. StringBuffer class can be used not only for joining strings. Here is the example:

Java StringBuffer – example


package com.itcuties.java;

/**
* Java StringBuffer example.
*
* @author itcuties
*
*/
public class StringBufferExample {

   public static void main(String[] args) {
       
       StringBuffer sb = new StringBuffer("Sample StringBuffer's value");
       
       // sb.toString() is called here
       System.out.println("original: " + sb);
       
       // length() method call returns the actual length of the string held in the StringBuffer
       // capacity() method call returns StringBuffer object's capacity. This is number of characters that StringBuffer object can currently hold.
       // Capacity of the StringBuffer object is managed automatically.
       System.out.println("length(): " + sb.length() + ", capacity(): " + sb.capacity());
       
       // charAt() method call returns the character that is hold at the given index of the StringBuffer object
       System.out.println("charAt(): " + sb.charAt(5)); //'e' character - [0]S [1]a [2]m [3]p [4]l [5]e [6] [7]S [8] [9]t [10]r [11]i [12]n [13]g...
       
       // codePointAt() method call returns the code point value (unicode code) of the character at the given index
       System.out.println("codePointAt(): " + sb.codePointAt(5)); // 'e' sign unicode code
       
       // append() method call joins StringBuffer value with the String value passed as the argument
       System.out.println("append(): " + sb.append(" by itcuties"));
       
       // insert() method call inserts the string representation of the object passed as the argument at the given index
       System.out.println("insert(): " + sb.insert(7, "[INSERT THIS] "));
       
       // indexOf() method call returns the index within this string of the first occurrence of the String passed as the argument.
       System.out.println("indexOf():" + sb.indexOf("[INSERT THIS]"));
       
       // delete() method call removes the characters from the index 7 up to index 20
       System.out.println("delete(): " + sb.delete(7, 7+ "[INSERT THIS] ".length()));
       
       // substring() method call returns a new String that contains a subsequence of characters currently contained in this sequence.
       // In this example the code returns the substring from the index 31 up to index 38
       System.out.println("substing(): " + sb.substring(31,39));

       // reverse() method call results in reversing the characters order of the string held in the StringBuffer object
       System.out.println("reverse(): " + sb.reverse());
       
   }
}

Output:


original: Sample StringBuffer's value

length(): 27, capacity(): 43

charAt(): e

codePointAt(): 101

append(): Sample StringBuffer's value by itcuties

insert(): Sample [INSERT THIS] StringBuffer's value by itcuties

indexOf():7

delete(): Sample StringBuffer's value by itcuties

substing(): itcuties

reverse(): seitucti yb eulav s'reffuBgnirtS elpmaS

Download this sample code here.

This code is available on our GitHub repository as well.

2 Responses to "Java StringBuffer Example"

  1. itcuties says:

    We have found interesting and valuable comment on reddit about this article. It was written by user zzyzzyxx. Here it is:

    “When you need to do a lot of modifications on a String object, like concatenating it with another String, removing it’s fragment and so on, the best choice is to use Java StringBuffer class.”
    First, it’s not the “best choice”; you should prefer a StringBuilder unless you specifically require the synchronization that StringBuffer provides, and you usually don’t. Second, simple concatenation is pretty much the time that you don’t need a StringBuilder explicitly. Using the built-in concatenation via the + operator is easier to read and generally compiles to the exact same byte code as using a StringBuilder would.
    Their example shows how you might use the class but gives no true indication as to when to use it, and in fact shows improper usage of the class. They say you should use the builder/buffer classes when you need a lot of modifications, which is correct, yet don’t give an example actually demonstrating that use case. Even a simple building up a string in a loop would have sufficed as that is the typical use case. As is their code is going to call toString() a bunch of times, which creates all those intermediate strings you’re trying to avoid by using a StringBuilder!

    Reference: http://www.reddit.com/r/learnprogramming/comments/1fjcdr/video_lessons_on_programming_given_by_cute_girls/

    We are looking forward to comments since we want to give you Guys valuabel content. Thanks zzyzzyxx!!

    Reply
  2. Pardeep says:

    Since String is immutable, so whenever you try to change String content it create another String. In case of + operation, when you do like this

    String str = "Java"+"Latte";
    

    Here there are two String object, “Java”, “Latte”. After concatenation, it create another String which is reference by str.

    For instance,

    String s1 = "java ";
    String s2 = s1 + "latte ";
    s1.concat("blogspot ");
    s2.concat(s1);
    s1 += ".com ";
    System.out.println(s1 + " " + s2);
    

    s1 = "java"; 1 object, s1 reference

    String s2 = s1 + "latte "; “latte ” object which is lost , second one is “java latte” and s2 reference

    s1.concat("blogspot "); “blogspot ” object which is lost and “java blogspot” object which is also lost

    s2.concat(s1); “java latte java” object lost

    s1 += ".com "; “.com” object lost, “java.com” object

    Object: “java”, “latte “, “java latte”, “blogspot “, “java blogspot”, “java latte java”, “.com”, “java.com”
    Reference : s1,s2

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>