"We just have to cover StringBuilder, and then I think we're done."
"As you already know, StringBuilder is like the String class, except it is mutable."
"And I also remember that the compiler generates code that uses StringBuilder when we simply add Strings together."
"Yes, you are right. What a remarkable memory you have. Then again, every robot does. I always forget that."
"Let's examine what you can do using the StringBuilder class:"
1) I have an ordinary String, and I want to make it mutable. How do I do that?
String s = "Bender";
StringBuilder s2 = new StringBuilder(s);
2) I want to add a character to an existing mutable string?
String s = "Bender";
StringBuilder s2 = new StringBuilder(s);
s2.append("!");
3) And how to do I convert a StringBuilder back to a String?
String s = "Bender";
StringBuilder s2 = new StringBuilder(s);
s2.append("!");
s = s2.toString();
4) And if I need to delete a character?
String s = "Bender";
StringBuilder s2 = new StringBuilder(s);
s2.deleteCharAt(2); //Becomes "Beder"
5) How do I replace part of a String with another?
String s = "Bender";
StringBuilder s2 = new StringBuilder(s);
s2.replace (3, 5, "_DE_"); //Becomes "Ben_DE_r"
6) What if I need to reverse a String?
String s = "Bender";
StringBuilder s2 = new StringBuilder(s);
s2.reverse(); //Becomes "redneB";
"Cool. Thanks, Ellie, everything makes sense."
"I'm glad you liked it."
"I would also like to remind you about something Bilaabo should have told you."
"There's another class called StringBuffer. It's like StringBuilder, but its methods are declared as synchronized. This means that before any call to one of its methods the Java machine checks whether the object is busy; if it isn't, the JVM marks it as busy. After exiting the method, the object is released. As a result, these calls are slower. You shouldn't use StringBuffer unless you have to."
"But if you need a mutable String that will be used across multiple threads, then you won't find anything better than StringBuffer ."
"Thanks for the info. I think that might come in handy someday."
GO TO FULL VERSION