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”;

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”);

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.

Difference between Stringbuffer and Stringbuilder

Hope this post is helpful for you...