0

Because String and StringBuilder (or StringBuffer) are designed for different purposes, I can understand the reasons for half of the difference (such as String does not have append and delete). However, there are a few points still confusing me.

To name a few:

  • String has both getBytes and getChars but StringBuilder has only getChars.
  • String and StringBuilder have replace of different functionality respectively.
  • String has toLowerCase and toUpperCase, whereas StringBuilder does not.
  • String has trim, whereas StringBuilder does not.

I know they are by design, but why?

5
  • Because, e.g., uppercasing a StringBuilder without first rendering it as a string does not make sense. Commented Jul 9, 2012 at 14:39
  • @JustinSatyr, why? If I uppercase a StringBuilder before converting it to a String, I can save a String object. Commented Jul 9, 2012 at 14:41
  • @JustinSatyr True, but this does not explain all differences (like the lack of getBytes in the StringBuilder). Commented Jul 9, 2012 at 14:41
  • StringBuilder.replace() does not fit this picture. Apart from that, Strings are immutable, the other two classes are used to build strings efficiently by appending various stuff. Commented Jul 9, 2012 at 14:42
  • StringBuilder's purpose is to avoid immutability. If you used regular concatenation such as "a" + "b" +"c", you would create a great deal of String objects for nothing. So, StringBuilder is not designed to handle actions like toUpperCase and toLowerCase..basically, he's mostly used to create String objects which are composed of more other String objects Commented Jul 9, 2012 at 14:44

2 Answers 2

2

String and StringBuilder were designed and implements more than a decade apart. What was a good idea in Java 1.0 wasn't considered a good idea in Java 5.0.

e.g. trim() trims characters <= space. This include graphical characters, but not all whitespace e.g. (char) 160 is a whitespace, but not trimmed.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I have considered the "age" problem, but StringBuilder is just a unsynchronized version of StringBuffer, the latter of which was introduced in 1.0.
True, but there was a few redesignes done. e.g. both implement Appendable which was added in Java 5.0
-1

As of release JDK 5, StringBuffer has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

1 Comment

Doesn't answer@Dante's question!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.