Log in
updated 11:29 AM UTC, May 4, 2016

When to use StringBuffer ?

  • Written by Madhu V Rao
  • Published in Core Java

 

StringBuffer is powerful when there are string operations like concatenation/ deletion involved.
Here is a small example to demonstrate the power of StringBuffer.

This program joins the String array into a long String in two possible ways
1) using String + operator
2) using StringBuffer append method.


It also prints out time taken by the methods.

package com.example;

public class Words {

	public static String join(String[] array) {
		long start = System.currentTimeMillis();
		StringBuffer output = new StringBuffer();

		for (String word : array) {
			output.append(word);
		}

		long end = System.currentTimeMillis();
		System.out.println("Time taken = " + (end - start));
		return output.toString();
	}

	public static String join_old(String[] array) {
		long start = System.currentTimeMillis();
		String output = "";

		for (String word : array) {
			output += word;
		}
		long end = System.currentTimeMillis();
		System.out.println("Time taken while using string= " + (end - start));
		return output;
	}

	public static void main(String[] args) {
		String[] test = { "1", "2", "3" };
		System.out.println("Run using Strings");

		join_old(test);
		System.out.println("Run using StringBuffer");

		join(test);
	}
}

Output :

Run using Strings
Time taken while using string= 2
Run using StringBuffer
Time taken = 0

Create a very long test string array to check the differences yourself.

 


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest