String Builder and String Buffer


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.

        String from = "From : ";
        String to = " To : ";

        StringBuilder builder = new StringBuilder();

        Log.i("Result : ", builder.toString());


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.

        String from = "From : ";
        String to = " To : ";

        String str = new StringBuffer()

        Log.i("Result : ",str);




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

Your comment:

Your Name


Last articles