String Utils Methods Flashcards
Declaring String Buffer
StringBuffer stringbuffer = new StringBuffer();
Convert a String to StringBuffer
StringBuffer stringbuffer = new StringBuffer(str);
Convert a StringBuffer to String
String str = stringbuffer.toString();
Character at a particular place of String Buffer
stringbuffer.charAt(nth);
Adding String
stringbuffer.append(string1);
Reverse a String
stringbuffer.reverse();
Insert a String
stringbuffer.insert(Start Index,string);
Delete a part of the string
stringbuffer.delete(Start Index,End Index);
Delete char at the nth place
stringbuffer.deleteCharAt(nth);
Replace a part of the String
stringbuffer.replace(Start Index,End Index,string);
Substring
stringbuffer. substring(Start Index);
stringbuffer. substring(Start Index,End Index);
Length of the string
stringbuffer.length()
Difference between String and StringBuffer
1) Mutability: String is immutable (Once created, cannot be modified) while StringBuffer is mutable (can be modified).
2) Performance: While performing concatenations you should prefer StringBuffer over String because it is faster. The reason is: When you concatenate strings using String, you are actually creating new object every time since String is immutable
Difference between StringBuffer and StringBuilder
Lets summarize the differences in detail:
1) Synchronization: StringBuffer methods are synchronized while StringBuilder methods are non-synchronized, it means that for thread-safe operations you must choose StringBuffer class instead of StringBuilder.
2) Performance: In a synchronized environment a single thread can perform a certain operation rather than distributing the work among multiple threads, which makes StringBuffer low performer as it is synchronized. StringBuilder performance is better than StringBuffer because it is not synchronized.
3) Which one to use: Operations (without considering the performance) are almost same in both the classes which means there is nothing in StringBuffer which cannot be done using StringBuilder. As discussed above the main thing which you need to consider while making a choice is thread-safety, if you think that the operation should be thread-safe then use StringBuffer, in all other cases StringBuilder is a better choice as it offers you the same functionality with better performance.
Similarities: Unlike String, both StringBuffer and StringBuilder are mutable (can be modified).