Sunday, May 1, 2016

String vs StringBuffer vs StringBuilder

n Java, a String is a primitive data type and almost all developers use String for a character strings operation. Other than that, Sun provided StringBuffer, StringBuilder.

What are the differences between the String, Stringbuffer, and Stringbuilder?
1. String: A string is immutable, which means that once a String is created, its value cannot be changed.
?
1
2
3
4
5
String s = "Hello";
 
s = s + " World!";
 
System.out.println(s);
When executing this code, the string Hello World! will be printed. How?
Java created a new String object and stored "Hello World!" as its value. If this style of coding is used often in a program, the program will have performance problems due to the lack of memory.
2. StringBuffer: A StringBuffer is mutable, which means once a StringBuffer object is created, we just append the content to the value of the object instead of creating a new object. Their methods are synchronized when neccessary so that the StringBuffer will be used effectively in threads. The StringBuffer runs slow in a one-thread program.
?
1
2
3
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World!");
System.out.println(sb.toString()); //Hello World!
3. StringBuilder: The StringBuilder is essentially the same as StringBuffer but it is not thread-safe, that means that their methods are not synchronized. In comparison to the other Strings, the Stringbuilder runs the fastest.
?
1
2
3
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World!");
System.out.println(sb.toString()); //Hello World!

No comments:

Post a Comment