Tuesday, 16 May 2017

Difference between Stringbuffer and StringBuilder in java

Stringbuffer:
* Stringbuffer is synchronized.
* Its a thread safe.
* Single thread only can access the stringbuffer at a time.
* Stringbuffer less efficient than stringbuilder.

Example:
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 5; i++) {
    stringBuffer = stringBuffer.append("Hello world");
}

Stringbuilder:
* Stringbuilder is not a synchronized.
* Its not a thread safe.
* Multiple thread can access the stringbuilder at a time.
* Stringbuilder is highly efficient than stringbuffer.

Example:
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 50000; i++) {
    stringBuilder = stringBuilder.append("Hello world");
}

Download Stringbuffer and StringBuilder example code

No comments: