Concatenation is the process of combining two or more strings to form a new string by subsequently appending the next string to the end of the previous strings.
In Java, two strings can be concatenated by using the +
or +=
operator, or through the concat()
method, defined in the java.lang.String
class.
This shot will discuss how to perform string concatenation using both of these methods.
The program below demonstrates how to concatenate two strings using the +
operator in Java.
class HelloWorld { public static void main( String args[] ) { String first = "Hello"; String second = "World"; String third = first + second; System.out.println(third); // yet another way to concatenate strings first += second; System.out.println(first); } }
concat()
methodThe signature of the concat()
method is shown below:
String concat(String stringToConcat)
stringToConcat
is the string to be concatenated. It will be appended at the end of the string object calling this method.
The concat()
method returns the concatenated string.
The program below demonstrates the concatenation using the String.concat()
method with two strings in Java:
class HelloWorld { public static void main( String args[] ) { String first = "Hello"; String second = "World"; String third = first.concat(second); System.out.println(third); } }
Note: You can also directly concatenate the strings within the
println
method itself asSystem.out.println(first + second);
orSystem.out.println(first.concat(second));
.
RELATED TAGS
CONTRIBUTOR
View all Courses