Good evening, i read these statement in a blog it's NOT safe to replace a StringBuffer object with a StringBuilder in java version earlier than 1.5
and it seems to be a fact, but there's no apparent reason for that !!, i know that StringBuffer is extending class java.lang.AbstractStringBuilder. StringBuilder also extends AbstractStringBuilder, so it inherits those methods as well.so from the compiler's point of view you can safely replace StringBuffer with StringBuilder. Of course StringBuilder is not synchronized, so if you care about synchronization you can't replace string buffer with string builder so in my point of view synchronization is the only factor that we could think of when replacing string buffer with string builder, but it seems that there's another factor JAVA Version
but i don't know how these effects the decision, please discuss these point to me.
Asked
Active
Viewed 989 times
0

Eslam Hamdy
- 7,126
- 27
- 105
- 165
-
Looking at StringBuilder javadoc, it says *Since 1.5*, so prior to Java 1.5 you can't use a class that didn't exist. Isn't that a fact? – Luiggi Mendoza Apr 05 '13 at 22:05
2 Answers
3
See http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
StringBuilder
didn't exist before Java 1.5, so earlier Java versions wouldn't be able to use it.

miorel
- 1,863
- 2
- 14
- 18
3
The reason it's not safe to use it in a VM before 1.5 is because StringBuilder
just didn't exist before 1.5. If you look at the JavaDoc for StringBuilder
you can see it has only exited since 1.5.
Regarding when to use it in 1.5+, you are mostly safe in just substituting StringBuffer
out in favor of StringBuilder
. The case when you wouldn't want to do this is if you have more than one thread writing to the buffer. However, in most cases when you just want to make a String
and return it, from a toString()
method, for instance, you should be safe.

Todd
- 30,472
- 11
- 81
- 89