Java StringBuffer Vs StringBuilder

 

StringBuffer StringBuilder
Methods are synchronized. Methods are not synchronized.
At a time only one thread is allow to operate on StringBuffer object.Hence StringBuffer object is thread safe. At a time multiple threads are allowed to operate on StringBuilder Object.Hence StringBuilder Object is not thread safe.
Performance is low. Performance is high.
Introduced in 1.0 version Introduced in 1.5 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);
    }
}

Output produced by above StringBuffer example program:

String Length of Hello is 5
Capacity of Hello is 21
Example
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
    }
}

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment