1.

State the difference between StringBuffer and StringBuilder in Java.

Answer»

StringBuffer and StringBuilder are two Java classes for manipulating strings. These are mutable OBJECTS, i.e., they can be modified, and provide various methods such as insert(), substring(), delete(), and append(), for String manipulation.

  • StringBuffer: The StringBuffer class was created by the Java Team when they REALIZED the need for an EDITABLE string object. Nevertheless, StringBuffer has all methods synchronized, MEANING they are thread-safe. Therefore, StringBuffer allows only one thread to access a method at once, so it is not possible to call StringBuffer methods from two THREADS simultaneously, which means it takes more time to access. The StringBuffer class has synchronized methods, making it thread-safe, slower, and less efficient than StringBuilder. The StringBuffer class was introduced in Java 1.0.
    • Syntax:
StringBuffer var = new StringBuffer(str);
  • StringBuilder: It was at that point that the Java Team realized that making all methods of StringBuffer synchronized wasn't the best idea, which led them to introduce StringBuilder. The StringBuilder class has no synchronized methods. Unlike StringBuffer, StringBuilder does not offer synchronized methods, which makes it less thread-safe, faster, and more efficient. StringBuilder was introduced in Java 1.5 in response to StringBuffer's shortcomings.
    • Syntax: 
StringBuilder var = new StringBuilder(str);


Discussion

No Comment Found