- Computers & Software»
- Computer Science & Programming»
- Programming Languages
What is difference between String and StringBuffer in Java - Interview question
String and StringBuffer in Java
Difference between String and StringBuffer in Java is most classic, old, frequently asked and popular Java interview question. I don't know how many times this question has asked to different Java programmers but on fresher level I have seen String and StringBuffer every now and then. Concept of String and StringBuffer is so important to understand not just from an interview perspective but also to use them properly. String and StringBuffer are used heavily in any Java application and can affect performance of Java program by frequent Garbage collection pause if not used carefully.
Here are list of differences between String and StringBuffer in Java.
1) String is immutable class in Java while StringBuffer is a mutable Class in Java. What this mean is that once you create an String you can not change its content and any change will result in new String while after creating StringBuffer instance you can change its content without creating any new instance. for example calling toUpperCase() method of string "abcd" will produce a new String ABCD .
2) StringBuffer is used where we need to concatenate several Strings like "abcd" + "defg" . here one can use StringBuffer.append() method which is also suggested by some IDE.
3) StringBuffer is synchronized, while a new introduced class StringBuilder is not synchronized, See String vs StringBuffer vs StringBuilder in Java for more details.
4) String literals are maintained in String Pool while there is no corresponding pool for StringBuffer instances.
5) You can not convert String to StringBuffer both classes are not related to each other on Type hierarchy, StringBuffer is just an Utility class to operate on String contents.
These were some of the differences between String and StringBuffer class in Java. next time if some one asked what are differences on String and StringBuffer you can say them all these points but don't forget to mention most important point about Immutability. String is immutable and StringBuffer is mutable in Java.