The Artima Developer Community
Sponsored Link

Java Answers Forum
String vs StringBuffer

2 replies on 1 page. Most recent reply: Nov 15, 2002 6:10 AM by greg

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
greg

Posts: 6
Nickname: sputnik
Registered: Sep, 2002

String vs StringBuffer Posted: Nov 14, 2002 1:59 PM
Reply to this message Reply
Advertisement
A while ago I was chatting with a Java coder friend of mine who was telling me the difference between using Strings and StringBuffers and why StringBuffers were a more efficient use of resources (when concatenating Strings).

As a self-taught and purely part-time coder his explanation seemed pretty cool... Trouble is I've forgotten quite what the difference was! (and lost touch with him...)

So just wondering if any Java guru out there knows what it is and if they could just refresh my memory?!

Cheers!


Daniel Ray

Posts: 53
Nickname: budoray
Registered: Oct, 2002

Re: String vs StringBuffer Posted: Nov 14, 2002 3:34 PM
Reply to this message Reply
It's inefficient because everytime you modify a String you're creating a new String. The String class is immutable and the JVM stores those strings separatly if it doesn't already exist in the "internal list". In case the String does exist .. then a reference is used instead. So, if the "internal list" has two strings in it called String one = "Hello" and String two = "World" and you concat those with String three = one + two then you end up with a new string in the list.

StringBuffer uses append() and is mutable so you can add on to the end of StringBuffer without creating a new String. You're dealing with the same reference and not a new object everytime your new String doesn't already exist.

Here's a site that has code samples for testing the efficiency of using Strings and StringBuffers.

http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm

Ray

greg

Posts: 6
Nickname: sputnik
Registered: Sep, 2002

Re: String vs StringBuffer Posted: Nov 15, 2002 6:10 AM
Reply to this message Reply
cheers!

i knew it was something simple like that...

Flat View: This topic has 2 replies on 1 page
Topic: Threading and JVM Previous Topic   Next Topic Topic: writing to a file

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use