Difference between a stringbuffer and a string class?, JAVA Programming


String is immutable in java: you can't change a string object but can replace it by creating a new object instance. Creating a new instance is rather expensive.


//Non efficient version using immutable String


String out = "Some text"


Int cou = 80;

for(int i =0; i

output += i;


return out;


The above code would build 79 new String objects, of which 78 would be thrown away

immediately. Creating new objects is not efficient.


StringBuffer is mutable in java: use StringBuilder or StringBuffer when you want to change the contents. StringBuilder was started in Java 5 and it is identical in all function respects to StringBuffer except that it is not synchronized, which gives it slightly faster at the cost of not being thread-safe.


// efficient version of using mutable StringBuffer

StringBuffer out = new StringBuffer(110);// set an stating size of 110

out.append(" text");

for(int i =0; i



return out.toString();


The above code builds only two new objects, the final String and the StringBuffer that is given. StringBuffer expands as needed, which is costly however, so it could be better to initialize the StringBuffer with the needed size from the start as shown.


Posted Date: 7/25/2012 2:03:12 AM | Location : United States

Related Discussions:- Difference between a stringbuffer and a string class?, Assignment Help, Ask Question on Difference between a stringbuffer and a string class?, Get Answer, Expert's Help, Difference between a stringbuffer and a string class? Discussions

Write discussion on Difference between a stringbuffer and a string class?
Your posts are moderated
Related Questions
For this assignment we will be solving the producer-consumer problem with a bounded buffer. You are required to implement this assignment in Java. There are three components in thi

Android App Project Description: I am seeking an experienced individual to prepare a small android application The only difference is that I would like movement to be done

A fictitious train company, 'Transrail', has commissioned you to write a program that manages a list of train tickets. The program should display a text menu that prompts the us


Need iOS native App Developer Project Description: I want someone to help me prepare a simple inventory system. I am not a programmer trying to learn as i go. Skills re


Assume all the obstacles are of height 4 units and the blocks are of heights 1 (bottom), 2 (top), 1 and 2 (top) units respectively.  Complete the control() method of the RobotContr


Explain System Colors in java 1.1? In Java 1.1, the java.awt.SystemColor class is a subclass of java.awt.Color that gives color constants in which match native component colors