How to Concatenate Two Strings in Java

Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate two strings in Java are mentioned below.

By Using + Operator

The + operator can be used to concatenate the strings. Let’s understand it with the help of the following example.

FileName: StringConcatenationExample.java

Output:


Explanation: By looking at the output, it is evident that the + operator concatenates the strings “Tutorial & Example” and “– A Good Site To Learn Java.”

By Using the concat() Method

The concat() method can also be used to do the concatenation work.

Syntax:

String anotherStr: represents the string that is being concatenated with the current string.

A String is returned, which is the concatenation of the current string and anotherStr.

The following program illustrates the same.

FileName: StringConcatenationExample1.java

Output:


Explanation: In the above program, the + operator is replaced by the concat() method to accomplish the concatenation work. Everything else remains the same. Hence, the output also remains the same.

By Using the append() Method

Another approach is to use the append() method to do the concatenation of the given strings. However, the append() method is not present in the Java String class. Therefore, to apply the append() method, one needs the object of either StringBuilder or StringBuffer class. Observe the following program.

FileName: StringConcatenationExample2.java

Output:


Explanation: The above program shows that either StringBuilder or StringBuffer class can be used to do the concatenation of string. The concatenation of strings is achieved by invoking the append() method on the objects of the classes StringBuilder or StringBuffer. The toString() method then used to extract the concatenated string from those objects, which is displayed in the output.

Pin It on Pinterest

Share This