In this answer, We have shared about String vs StringBuilder vs StringBuffer in Java. A list of differences between StringBuffer and StringBuilder are given below:
No. | StringBuffer | StringBuilder |
---|---|---|
1) | StringBuffer is synchronized i.e. thread safe. It means two threads can’t call the methods of StringBuffer simultaneously. | StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. |
2) | StringBuffer is less efficient than StringBuilder. | StringBuilder is more efficient than StringBuffer. |
Consider below code with three concatenation functions with three different types of parameters, String, StringBuffer and StringBuilder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class StringStringBuilderProgram { // Concatenates to String public static void concat1(String s1) { s1 = s1 + "forgeeks"; } // Concatenates to StringBuilder public static void concat2(StringBuilder s2) { s2.append("forgeeks"); } // Concatenates to StringBuffer public static void concat3(StringBuffer s3) { s3.append("forgeeks"); } public static void main(String[] args) { String s1 = "Geeks"; concat1(s1); // s1 is not changed System.out.println("String: " + s1); StringBuilder s2 = new StringBuilder("Geeks"); concat2(s2); // s2 is changed System.out.println("StringBuilder: " + s2); StringBuffer s3 = new StringBuffer("Geeks"); concat3(s3); // s3 is changed System.out.println("StringBuffer: " + s3); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.