Introduction
Combining or joining two strings is a frequent operation performed by programmers for various applications. This can be carried out using many ways. In Java, strings can be joined or concatenated. Strings are joined using a specified delimiter, such as another substring or any special character. Strings are concatenated or combined to result in a new string. Concatenation can be achieved in two ways.
-
By using the + operator
-
By using the concat() method.
In this blog, we shall concentrate on the use of concat() function.
concat()
The concat() method of the Java Strings class combines or appends one string to the end of another.
Syntax:
str1.concat(str2)
Parameters:
str1, str2: The two Strings to be combined
Returns: String
str2 is attached to the end of str1, and the result is stored in another new string. The function returns a new string as String objects are immutable, i.e. they cannot be altered under the same name once initialised.
Concatenating two strings
The following example shows the use of the concat() function to join two separate strings.
class Main
{
public stattic void main(String[] args)
{
String str1 = "Hello";
String str2 = " world";
String result = str1.concat(str2);
System.out.println(result);
result = "Say ".concat(str1);
System.out.println(result);
}
}Output
Hello world
Say Hello
Concatenating multiple strings
The concat() function can be used to concatenate multiple strings in just a single statement as shown below.
class Main
{
public static void main(String[] args)
{
String str1 = "hello";
String str2 = " world";
String str3 = "\nLet's explore Strings";
String str4 = " in Java";
String result = str1.concat(str2).concat(str3).concat(str4);
System.out.println(result);
}
}Output
hello world
Let's explore Strings in Java




