How To Append String In Java

Append operation of String in Java is the merging of one string at the end of the another String.

How To Append String In Java

Append operation of String in Java is the merging of one string at the end of the another String.

How To Append String In Java

How To Append String In Java

In this section we will read about how to append String in Java. Here we will see the solution of this question through a simple example.

There are various ways to append String in Java. Below, we will describe it one by one :

  • The first and easy way to append string in Java is the use of '+' operator. '+' operator concat the two Strings however, it is used for addition in arithmetic operation.
  • The second one process is to use concat() method of String class. Using this method one string can be appended at the end of the another string.
  • The third one process is to use append() method of either StringBuffer(prior to JDK 5) class or StringBuilder(later JDK 1.6) class. This method is overloaded in this class that helps in to append different types of values.

We will see all the ways of appending String using a simple example.

Example

Here an example is being given which will demonstrate you about how to concatenate/append string in Java. In this example we will create a simple Java class where we will use the above all processes for appending strings. We will use '+" operator, concat() method, and append() method to append string.

AppendStringExample.java

public class AppendStringExample {

	public static void main(String args[])
	{
		String str1 = "Rose";
		String str2 = "-";
		String str3 = "India";
		
		String concat = str1.concat(str2).concat(str3);
		String plus = str1+str2+str3;
		StringBuilder sb = new StringBuilder();
		sb.append(str1).append(str2).append(str3).toString();
		System.out.println("Append String Using concat() 

method : "+concat);
		System.out.println("Append String Using plus operator : 

"+plus);
		System.out.println("Append String Using append() 

method : "+sb);
	}
}

Output

When you will compile and execute the above example you will get the output as follows :

Download Source Code