Appending String in java

This tutorial will help you how to append a strings in java.

Appending String in java

This tutorial will help you how to append a strings in java.

Appending String in java

Appending String in java

In this tutorial we are going to discuss about appending string in java. Java provide a method called append() in java.lang.StringBuilder class, which appends the specified string to the character. StringBuilder are in replacement for StringBuffer where synchronization is applied  that is used by single thread. StringBuilder principal operation is insert and append which take any type of data whether it is int, char, boolean etc. Methods summary for StringBuilder append() method which take any data type are as follows :

  • append(boolean b) : Appends the boolean argument to the sequence.
  • append(char ch) : Appends the string representation of the char to the sequence.
  • append(char[] str) : Appends the string representation of char array to the sequence.
  • append(char[] str, int offset, int len) : Appends the string representation of sub array of the char array of the sequence.
  • append( float f) : Appends the string representation of float to the sequence.
  • append(int i) : Appends the string representation of integer to the sequence.
  • append(long l)  : Appends the string representation of long to the sequence.

 Syntax :

public StringBuilder append(String str)

The str is a string and this method returns a reference to this object. For example, if str refers to a string builder object whose current contents are "Rose", then the method call str.append("India") would cause the string builder to contain "RoseIndia", Now here is a simple example to illustrate the use of append() in java.

import java.lang.*;
public class AppendString {

	  public static void main(String[] args) {
	  
	    StringBuilder str = new StringBuilder("Rose ");
	    System.out.println("string = " + str);
	    
	    // appends the string 
	    str.append("India");
	    //  after appending prints the string 
	    System.out.println("After appending  = " + str);
	    
	    str = new StringBuilder("0289");
	    System.out.println("string = " + str);
	    // appends the string argument to the StringBuilder 
	    str.append(" hi ");
	    // print the StringBuilder after appending
	    System.out.println("After append = " + str);
	  }
	} 

In the above code creating a instance of StringBuilder class and initialize the content with "Rose ",  by append() method which take string as argument to append the specified string to the content of str,  like that we can add integer, float, character etc to the string sequence.

Output of the program :

Appending String in java

Download Source Code