JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label Java String tutorial. Show all posts
Showing posts with label Java String tutorial. Show all posts

Difference between StringBuffer, StringBuilder and String in Java

4:11 AM
String vs StringBuffer in Java 1) First and foremost difference between String and StringBuffer is that former is Immutable while later is mutable. This means if you need to manipulate String data then wrap it inside a StringBuffer to avoid creating lots of small and temporary String objects and putting pressure on Garbage collector. 2) Even though both StringBuffer and String are thread-safe, String achieves its thread-safety by using Immutability while StringBuffer achieves it by synchronizing methods which change the state e.g. append(), delete() etc. By the way, apart from above differences, both String and StringBuffer also has some key similarities e.g. both represent text data, both are defined in java.lang package, both classes exists in JDK from the first release and both are thread-safe in Java. Here is also a nice diagram to highlight the mutable and immutable difference between String and StringBuffer in Java: Difference between StringBuffer, StringBuilder

.