Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java StringBuffer Vs StringBuilder

StringBuffer

Methods are synchronized.
At a time only one thread is allow to operate on StringBuffer object.Hence StringBuffer object is thread safe.
Performance is low.
Introduced in 1.0 version

Example

package com.java8s.com;
public class StringBufferExample {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("Hello");
		int sbLength = sb.length();
		int sbCapacity = sb.capacity();
		System.out.println("String Length of " + sb + " is " + sbLength);
		System.out.println("Capacity of " + sb + " is " + sbCapacity);
	}
}

StringBuilder

Methods are not synchronized.

At a time multiple threads are allowed to operate on StringBuilder Object.Hence StringBuilder Object is not thread safe.

Performance is high.

Introduced in 1.5 version.

package com.java8s.com;
public class StringBufferExample {
	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder();
		System.out.println(sb.capacity()); // default value 16
		sb.append("Java");
		System.out.println(sb.capacity()); // still 16
		sb.append("Hello StringBuilder Class!");
		System.out.println(sb.capacity()); // (16*2)+2
	}
}

Example

Output produced by above StringBuffer example program:
String Length of Hello is 5
Capacity of Hello is 21.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext