This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes StringBuilder and String Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "StringBuilder and String" Watch "StringBuilder and String" New topic
Author

StringBuilder and String

Cory Max
Ranch Hand

Joined: Jul 20, 2005
Posts: 83
I understand the difference between the two but I have always used Strings in my code instead of StringBuilders. I am wondering how to set a stringbuilder object = a new string, not to append, not to insert, but to set it to a new string without the overhead of creating another object. for example, with strings I would have done:

String s = "";
for (int i = 0 ; i < 10 ; i ++) {
s = "" + i;
System.out.println(s);
}

Append, appends the string, insert, inserts at a specified index. How do I clear the contents of my stringbuilder and set it equal to a new value?

Thanks folks,

Yeuker


There are only 10 types of people in this world... Those who understand binary and those who don't.
Mark Dexter
Ranch Hand

Joined: Jun 03, 2007
Posts: 34
Since strings are immutable, you are creating a new String object with each iteration. So the StringBuilder will execute faster, since you are only creating one new object at the start of the loop instead a new object with each iteration. If you have "Thinking in Java", see page 506. Hope this helps. Mark Dexter
Cory Max
Ranch Hand

Joined: Jul 20, 2005
Posts: 83
I understand what the differences are. I want to know how to clear the contents of the stringbuffer, then insert a new string.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3011
    
    9
Will the replace method do what you want ?


Joanne
Cory Max
Ranch Hand

Joined: Jul 20, 2005
Posts: 83
Yup. Just what I needed. Just didnt look through the api as far as I should have:

 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: StringBuilder and String
 
Similar Threads
Doubt in String class
Reading Elements from an ArrayList, 3 at a time
String Builder Class
Number of object created here
Value of using StringBuffer for this example