The Java String concat Method is one of the String Method which is used to join the user specified string to the end of the existing string.
In this article we will show you, How to use String concat method in Java Programming language with example.
Java String concat Method syntax
The basic syntax of the string.concat in Java Programming language is as shown below.
public String concat(String str); // It will return String //In order to use in program String_Object.concat(String str)
- String_Object: Please specify the valid String Object.
- str: Please specify the String that you want to join to the end of the String_Object.
Return Value
The string.concat Function will join one or more strings and return new string.
Java String concat Method Example
The Java string concat method is used to join one or more strings. This Java program will help you to understand the string.concat method and its alternative approach.
JAVA CODE
package StringFunctions; public class ConcatMethod { public static void main(String[] args) { String str1 = "Learn"; String str2 = " Java Programming"; String str3 = " at tutorialgateway.org"; String str4 = str1.concat(" JAVA"); String str5 = str1.concat(str2); String str6 = str1.concat(str2).concat(str3); String str7 = str1 + str2; System.out.println(str4); System.out.println(str5); System.out.println(str6); System.out.println(str7); } }
OUTPUT
ANALYSIS
First we declared three String variables str1, str2, str3 and assigned some random data using following statement
String str1 = "Learn"; String str2 = " Java Programming"; String str3 = " at tutorialgateway.org";
From the above statements you can observe that, we are using extra white spaces before the string data to provide nice and clean spaces while displaying the data.
Next, we used the String data directly inside the Java string.Concat() function.
String str4 = str1.concat(" JAVA");
The following statement will concat str1 and str2. It means str2 will be added to the end of str1
String str5 = str1.concat(str2);
Following statement will concat str1, str2 and str3. It means, first str2 will be added to the end of str1 and then str3 will be added to the end of str2
String str6 = str1.concat(str2).concat(str3);
In Java Programming Language, We can achieve the same (concatenation of strings) using Arithmetic Operator ‘+’. The following statement will show you the same.
String str7 = str1 + str2;
Following System.out.println statements will print the output
System.out.println(str4); System.out.println(str5); System.out.println(str6); System.out.println(str7);
Thank You for Visiting Our Blog