0 votes
in JAVA by
How would you differentiate between a String, StringBuffer, and a StringBuilder?

1 Answer

0 votes
by

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:

// String

String first = "InterviewBit";

String second = new String("InterviewBit");

// StringBuffer

StringBuffer third = new StringBuffer("InterviewBit");

// StringBuilder

StringBuilder fourth = new StringBuilder("InterviewBit");

Related questions

0 votes
asked Feb 12, 2020 in JAVA by rahuljain1
+1 vote
asked Oct 16, 2020 in JAVA by SakshiSharma
...