-5

I don't understand use of StringWriter in place of StringBuffer. Please help me to understand.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
code chimp
  • 359
  • 2
  • 8
  • 21
  • 1
    Refer this http://stackoverflow.com/questions/27221292/when-should-i-use-javas-stringwriter – Nigam Patro Dec 18 '15 at 07:02
  • also http://www.coderanch.com/t/380184/java/java/wat-diff-stringbuffer-stringwriter – Roshan Dec 18 '15 at 07:02
  • 5
    What would you do if you have an API that you want to call which accepts a `Writer`, and you want to create a string in memory? – Jon Skeet Dec 18 '15 at 07:03
  • I think ```new PrintWriter(new StringWriter())``` is useful. It has ```println()``` and ```printf()```. –  Dec 18 '15 at 07:11

1 Answers1

4

It is largely a matter of the APIs.

  • StringWriter implements the Writer API; i.e. it can be used as a "sink" for capturing characters written to a character-based output stream.

  • StringBuilder implements the CharSequence API. This is more general than than Writer in that it also supports accessing characters that have already been written. In addition, StringBuilder has methods for insertion and deletion at arbitrary positions.

It should also be noted that both Writer and StringBuilder implement the Appendable API which means that for some use-cases you can write a single method that can accept either a StringWriter or a StringBuilder for capturing text.

So ... which would you use?

  • If you are calling an existing library method, you use which ever one is compatible with that method's API. If both are compatible, you can use either.

  • If you are designing an API method, you should probably use one of the respective superclasses / interfaces as the parameter (or result) type rather than hard-wiring StringWriter or StringBuilder. That will make your method more general / more reusable. Probably the most general is Appendable ... but is depends on what your method needs to do with the character sink, and predicted client requirements.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216