Saturday, October 4, 2014

StringBuilder example in java

The Java StringBuilder class represents string objects that can be changed. It contains methods such as append and insert that modify the string object. For example, the append method adds a string to the end of the StringBuilder object. The object is changed; no new object is created or returned. Generally use the StringBuilder class for string objects that will change.

There is mainly two way to append string.

Way – 1:

    String s = “Example”;
    s = s + ”  varemads”;
    system.out.println(s);

Output give you “Hello World”, let’s be different from the rest and think about making the code more efficient.

Way - 2:



    StringBuilder sb = new StringBuilder(“Example”);
    sb.append(” varemads”);
    system.out.println(sb);

well… thats it!! You’ll get your “Hello World” but in a more efficient way.

It is recommended to use StringBuilder whenever possible because
it is faster than StringBuffer. However if thread safety is

necessary the best option is StringBuffer objects.


http://www.varemads.com/java-2/java-use-stringbuilder/

Difference between Stringbuffer and Stringbuilder

Hope this post is helpful for you...