String
, StringBuffer
and StringBuilder
in Java
String
:
StringBuffer
:
StringBuilder
:
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");
|
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.