๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

String vs StringBuffer vs StringBuilder  


Difference between String, StringBuffer and StringBuilder in Java
  • String:
    • Immutable sequence of characters; best for fixed or constant text that does not change.
  • StringBuffer:
    • Mutable and thread-safe; suitable for strings that are frequently modified in multi-threaded applications.
  • StringBuilder:
    • Mutable and faster but not thread-safe; ideal for strings that are frequently modified in single-threaded environments.
  • The following table highlights the key differences between String, StringBuffer and StringBuilder in Java:
Feature String StringBuffer StringBuilder
  Mutability The String class creates immutable objects, meaning once a string is created, it cannot be modified. Any modification results in the creation of a new object. The StringBuffer class creates mutable objects, meaning the content can be modified without creating a new object. The StringBuilder class also creates mutable objects, allowing changes to be made directly without creating new objects.
  Thread-Safety The String class is inherently thread-safe because it is immutable, so multiple threads can share it without any issues. The StringBuffer class is synchronized, which means it is thread-safe and can be used safely in multi-threaded environments. The StringBuilder class is not synchronized, meaning it is not thread-safe and should only be used in single-threaded environments.
  Performance The String class is slower for repeated modifications because each modification creates a new object in memory. The StringBuffer class is slower than StringBuilder because synchronization adds extra overhead. The StringBuilder class is faster than StringBuffer because it does not have synchronization overhead.
  Package The String class is present in the java.lang package. The StringBuffer class is present in the java.lang package. The StringBuilder class is present in the java.lang package.
  Introduced In The String class was introduced in JDK 1.0. The StringBuffer class was introduced in JDK 1.0. The StringBuilder class was introduced in JDK 1.5.
  Usage The String class is used when the string content will remain constant and no modifications are required. The StringBuffer class is used when strings need to be modified frequently in a multi-threaded environment. The StringBuilder class is used when strings need to be modified frequently in a single-threaded environment for better performance.
  Example String s = "Hello"; StringBuffer sb = new StringBuffer("Hello"); StringBuilder sb = new StringBuilder("Hello");