Wednesday, November 25, 2015

Java String, StringBuilder and StringBuffer


What is so different between String, StringBuffer, StringBuilder ?

Strings are simple, constant size and represents a series of characters.
Since they are constants, strings can not be changed and you can simply exchange them.
StringBuilders make them a bit flexible and changeable. While StringBuilder and StringBuffer provides some similar features, StringBuffer is better when it is multi-threaded usage as the methods are synchronized.

A simple example:

public class StringAndStringBuilder {
    public static void changeString(StringBuilder sb){
        sb.delete(0, sb.length());
        sb.append("changed");
    }
public static void changeString(String s){
s="changed";

    }


    public static void main(String[] args) {
        StringBuilder sb=new StringBuilder("nothing");
        changeString(sb);
        System.out.println("value after change via stringbuilder "+ sb);
String s = new String("nothing");
changeString(s);
System.out.println("value after change via string "+ s);

    }
}
output:
value after change via stringbuilder changed
value after change via string nothing

No comments:

Post a Comment