-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathString, StringBuilder and StringBuffer
46 lines (33 loc) · 1.71 KB
/
String, StringBuilder and StringBuffer
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
36
37
38
39
40
41
42
43
44
45
String -> Immutable
StringBuilder -> Mutable(can be changed)
StringBuffer -> Mutable(can be changed)
The only difference between StringBuffer and StringBuilder is StringBuffer is thread-safe, that is StringBuffer is synchronized.
whereas StringBuilder is NOT thread-safe, that is StringBuilder is NOT synchronized.
Difference between StringBuilder and StringBuffer:
StringBuilder -> provides NO ThreadSafety(means all methods of StringBuilder are not synchronized)
hence no performance overhead
StringBuffer -> provides ThreadSafety(means all methods of StringBuffer are synchronized)
hence it has some performance overhead
When to use StringBuilder and StringBuffer:
In multithreaded system, where thread safety is required, we use StringBuffer
In normal programs, we use StringBuilder, since it has NO threadsafety overhead and hence it is fast.
Please go throughly through the following YouTube link, in the video it is explained very nicely.
http://www.youtube.com/watch?v=nQHVt-nOpxQ
Also go through the Java documentation for:
1) String -> http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
2) StringBuilder -> http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
3) StringBuffer -> http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
Example:
Question -> For a given string of some sentence, reverse words in that sentence.
Ex: I am Don , return Don am I
Solution:
public class ReverseArray {
public static void main(String[] args) {
String givenString = "Am I bad ? ";
StringBuilder reverse=new StringBuilder(givenString.length());
for(int i=givenString.length()-1;i>=0;i--){
reverse.append(givenString.charAt(i));
}
System.out.println(reverse.toString());
}
}