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
A string S is said to be "Super ASCII", if it contains the character frequency equal to their ascii values. String will contain only lower case alphabets (''''a''''-''''z'''') and

Public class ConversionProgram {  public void start() {    String userChoice = askConversionCategory();   while (userChoice.equals("1") || userChoice.equals("2") || Page 2

Java has two kinds of exceptions: 1. Checked exception: handled from java.lang.Exception but not java.lang.RuntimeException. 2. Unchecked exception: handled from java.lang.Ru

Talent agencies like ICM, CAA and Paradigm represent writers, directors and actors (among other talent).  These agencies take in hundreds of millions of dollars a year collecting 1

Describe Invoking Methods in java? class Car { String licensePlate = ""; // e.g. "New York 543 A23" double speed = 0.0; // in kilometers per hour double maxS

what is function

Define enumeration? Enumeration is explained as values type that having of a set of named values. These values are constants and are called enumerators. An enumeration type is

Create problem that solves cryptoarithmatic problem that uses from user using java