Pages

Difference between StringBuffer and StringBuilder

Difference between StringBuffer and StringBuilder ?

The main difference between StringBuffer & stringBuilder:

StringBuffer is synchronized i.e., thread safe.It means multiple threads can't access stringbuffer methods simultaneously.

StringBuffer is slower than StringBuilder but it is thread safety.
StringBuilder is non-synchronized i.e., not thread safe.It means multiple threads can access stringbuilder methods simultaneously.

StringBuilder is faster than StringBuffer but it is not thread safe.
Program on stringBuffer and StringBuilder:
public class StringDemo {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        StringBuffer sbuffer = new StringBuffer("sbufferstring");
        for (int i = 0; i < 1000; i++) {
            sbuffer.append("StringBuffer");
        }
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
        startTime = System.currentTimeMillis();
        StringBuilder sbuild = new StringBuilder("sbuilderString");
        for (int i = 0; i < 1000; i++) {
            sbuild.append("sbuilder");
        }
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
    }
}
Output:
Time taken by StringBuffer: 4ms
Time taken by StringBuilder: 0ms
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.