Exams Knowledge Hub

MCQs for Competitive Exams, School & College Exams

Module: | Classes, Objects, OOPs & Inheritance

Q40: Consider the following statements regarding StringBuffer and StringBuilder:

1. Both StringBuffer and StringBuilder are highly mutable classes specifically designed to solve the massive memory consumption penalty caused by repetitively concatenating immutable String objects inside loops.
2. The StringBuffer class is inherently thread-safe because its core modification methods (like append and insert) are strictly declared with the 'synchronized' keyword to prevent concurrent data corruption.
3. The StringBuilder class was introduced in Java 5 as a heavily locked, synchronized alternative specifically built for high-security, multi-threaded enterprise environments.

Which of the above statements is/are correct?
A
Only 1 and 2
B
Only 1 and 3
C
Only 2 and 3
D
1, 2, and 3
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because StringBuilder was intentionally designed as a non-synchronized, lock-free alternative to StringBuffer, drastically improving execution speed in single-threaded environments by stripping away all thread-safety overhead.
Concept Definition: StringBuffer and StringBuilder serve as mutable text containers.
Instead of forging a new memory object for every modification, they maintain a flexible internal character array that physically expands as new text is appended.
Structural Breakdown: When a developer executes a loop concatenating 10,000 strings using the '+' operator, the JVM creates 10,000 dead, orphaned String objects in the Heap.
Using a StringBuilder simply appends the characters into one continuous, expanding array buffer, resulting in exactly one final object.
Historical/Related Context: StringBuffer has existed since Java 1.0. However, Java architects realized that 95% of text manipulation occurs sequentially on a single thread inside isolated methods.
Forcing every minor text append to acquire a heavy synchronization lock severely throttled application speed, leading to the creation of the lock-free StringBuilder in Java 1.5. Causal Reasoning: The 'synchronized' keyword on StringBuffer methods acts as a traffic light, forcing parallel threads to wait in line to append data.
While this prevents data scrambling, it destroys parallel processing efficiency, which is precisely why modern enterprise standards strictly mandate using StringBuilder unless multi-threading is definitively involved.