How would you differentiate between a String, StringBuffer, and a StringBuilder?
Answer»
STORAGE area: In string, the String pool serves as the storage area. For StringBuilder and STRINGBUFFER, heap memory is the storage area.
Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
Efficiency: It is quite SLOW to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and LESS than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:
// StringString first = "InterviewBit";String SECOND = new String("InterviewBit");// StringBufferStringBuffer third = new StringBuffer("InterviewBit");// StringBuilderStringBuilder fourth = new StringBuilder("InterviewBit");