StringBuffer Archives - wiki

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.

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

        StringBuilder builder = new StringBuilder();
        builder.append(from);
        builder.append("Manager");
        builder.append(to);
        builder.append("Developer");

        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()
                .append(from)
                .append("Manager")
                .append(to)
                .append("Developer")
                .toString();


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

 

 

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

By bm on July 26, 2016 | Android, Java | A comment?
Tags: , , ,