Difference between string class and string buffer class:

Posted By on September 16, 2014


Download PDF
Java Garbage Collections
Dynamic Method Dispatch or Run Time Polymorphism

1) First and most significant difference between String and StringBuffer in Java is that String is immutable in Java while StringBuffer is mutable. What this means is, performing any operation on String will create new String object while modifying StringBuffer object won’t create new object.

2) If you are usingĀ  + operator for concatenating multiple String than you should not be worried much becauseĀ  based upon Java implementation call to + operator is replaced with either StringBuffer or StringBuider based upon JVM implements Java 1.5 or lower version.

3) StringBuffer.append()method is used to perform String concatenation in Java.

4) Creating StringBuffer from String is easy, as StringBuffer accept an String input. Similarly converting Stringbuffer to String is also easy by using toString() method in Java.

5)Another significant difference between String and StringBuffer is that StringBuffer and String does not share same type hierarchy, means you can not cast String to StringBuffer in Java. any such attempt will result in ClassCastException in Java.

That’s all on Difference between String and StringBuffer in Java. Most important difference to remember between String and StringBuffer is mutability.

In Summary you should not create too much String garbage if you feel you need to modify a particular String more than often than create a StringBuffer instance and use that. Using + operator for String concatenation is also a good idea as it’s more clear, concise and gives same performance as using StringBuffer in Java. On last note, Consider using StringBuilder in Java 5 onwards.

Java Garbage Collections
Dynamic Method Dispatch or Run Time Polymorphism

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com