Rajinder Menu

3. Using append() method of StringBuilder or StringBuffer class



The append()method of StringBuilder and StringBuffer classes can also be used to concatenate strings.

Example:

StringBuilder sb= new StringBuilder(“Hello”);
sb.append(“World!”);
System.out.println(sb);

Output: HelloWorld!

You can also chain append() together like this:

StringBuilder sb= new StringBuilder("The police ");
sb.append(" called off ").append(“ the search”).append(" for the missing boy.");
System.out.println(sb);

Output: The police called off the search for the missing boy.

The StringBuffer and StringBuilder classes have many overloaded append() methods - for all the built-in types, for objects etc. You can refer JavaDocs for their details.

Note: StringBuilder class was introduced in java 5.

If the argument of append() is non string then it is converted to String first by String.valueOf() method.

For Example,

StringBuilder sb= new StringBuilder("There were ");
int i=5;
sb.append(i).append(" thieves.");
System.out.println(sb);

Output: There were 5 thieves.

In above example you have appended an int value 5. Before appending, 5 will be converted to its string representation by String.valueOf(5).

 « Using concat() method



I would like to know your comments and if you liked the article then please share it on social networking buttons.


2 comments:

  1. String is an immutable class while StringBuilder & StringBuffer are mutable classes. StringBuffer is synchronized while StringBuilder is not.

    Below link can be useful to find more differences between String, StringBuffer & StringBuilder

    Difference between String, StringBuffer and StringBuilder

    http://newtechnobuzzz.blogspot.com/2014/07/difference-between-string-stringbuffer.html

    ReplyDelete