String Builder and String Buffer

String

String objects are immutable ( once created can not be changed ) and it will stored in the  Constant String Pool , so if you chose to do a lot of manipulations with String objects, you will end up with a lot of abandoned String objects in the String pool. To avoiding this memory loss we can use StringBuilder or StringBuffer and can be modified over and over again without causing memory loss

StringBuilder example

StringBuffers are thread-safe, they have synchronized methods to control access so that only one thread can access a StringBuffer object’s synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.

 

StringBuffer example

StringBuilder’s access is not synchronized so that it is not thread-safe. The performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance.

 

 

ref:
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

https://docs.oracle.com/javase/tutorial/java/data/buffers.html

https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html

  Like
Author: bm on July 26, 2016
Category: Android, Java
Tags: , , ,

Your comment:

Your Name

Comment:




Last articles