String vs StringBuilder vs StringBuffer

FeatureString StringBuilderStringBuffer
IntroductionJDK 1JDK 5JDK 1
MutabilityImmutableMutableMutable
Thread SafetyThread safeNot Thread safe Thread safe
Memory EfficiencyHighEfficientLess Efficient
PerformanceHigh(No synchronisation)High (No synchronisation)Low(Due to synchronisation)
Usage It is used when we want immutability.This is used when thread safety is not required.This is used when thread safety is required.

StringBuilder:- If you are working in single thread environment and you want high performance in that case you can use StringBuilder class of java which was introduced in JDK1.5.

StringBuffer:- If you are working in MultiThreaded environment and need thread safety guarantee than StringBuffer would be more appropriate despite of slight thread overhead. StringBuffer was introduced in JDK1.1.

Author: Susheel kumar

Leave a Reply

Your email address will not be published. Required fields are marked *