This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Help in Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help in Strings" Watch "Help in Strings" New topic
Author

Help in Strings

rajanidhi rajasekeran
Greenhorn

Joined: Aug 28, 2003
Posts: 4
What is the difference b/w String and Stringbuffer,if u say String is immutable,i can do modification in the string itself.I refered many books,in all i didn't get a clear answer,in some it is given that if u try to append a string using concatination it will use more resources ,i dont understand this .PLZ Help
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

Hi,
Welcome to JavaRanch!
Strings are indeed immutable. There are no methods that allow you to change the value of a String object. All the methods like toLowerCase() and concat() that might appear to change the string they're called on, do not actually change it; they create a new String instead. So for instance, the concat() method returns a new string equal to the original string with the argument added on.
StringBuffer is really a specialized, extensible array of characters. The main purpose of StringBuffer is to allow you to concatenate many small pieces together to make a large string efficiently.
If you write

Then each call to concat creates a new String object. If on the other hand, you write

Then only the last call creates a String object. If you're assembling a lot of pieces together, this can be a lot more efficient that using concat() directly.
Note that if you write

The Java compiler will actually emit code using a StringBuffer, much like my second example -- so using the "+" operator isn't as bad as many people will lead you to believe. On the other hand, if you wrote this last example using a separate line of code for each "+" operation, the emitted code would look more like the first example using concat().
Finally, note that despite what many people will tell you, none of this really matters except in an inner loop, or other code that must be highly optimized. In general, don't worry about writing the most efficient code; write the clearest, easiest to understand code. If something turns out to be slow, you can always go back and optimize it later.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help in Strings
 
Similar Threads
main() method????
Problem on JTree in JRE1.5
how to declare functions in jsp
genrating Random String
How can I get the URL of request?