Disadvantages of String:
- Immutability leads to memory usage
- Slower performance in modifications
- High Garbage Collection (GC) load
- Less efficient for dynamic text
- Concatenation using + inside loops is costly
Notes:
- Good for constant and read-only text.
- Bad for frequent modifications → use StringBuilder / StringBuffer instead.
What is StringBuilder?
- StringBuilder is a mutable (changeable) sequence of characters.
- Unlike String (which is immutable), when you modify a StringBuilder object, it does not create a new object in memory — it updates the same object.
- It was introduced in Java 1.5 to provide a faster, non-synchronized alternative to StringBuffer.
- Faster than StringBuffer because it is not synchronized (not thread-safe).
- Efficient for concatenation, insertion, deletion inside loops or large text operations.
- Found in the package: java.lang.StringBuilder.
What is StringBuffer in Java?
- StringBuffer is a mutable sequence of characters (like StringBuilder).
- The main difference: StringBuffer is synchronized → which means thread-safe (can be safely used by multiple threads).
- It was introduced in Java 1.0, before StringBuilder.
- Because of synchronization, it is slower than StringBuilder, but safer in multithreaded programs.
- Found in the package: java.lang.StringBuffer.
Common Methods in StringBuilder and StringBuffer:
- append()->Adds text at the end
- insert()->Inserts text at given index
- replace()->Replaces characters in range
- delete()->Deletes characters in range
- reverse()->Reverses the string
- capacity()->Returns current capacity
- length()->Returns current length
- charAt()->Returns char at index
How StrinBuilder Difference from StringBuffer?
- StringBuffer is synchronized (thread-safe, but slower,Multithreaded program).
- StringBuilder is not synchronized (faster, but not thread-safe,single threaded program).
Top comments (0)