The Java String concat() method concatenates one string to the end of another string. This method returns a string with the value of the string passed into the method, appended to the end of the string.
Syntax of Java String concat()
The syntax of String concat() method in Java is:
public String concat (String anostr);
Parameters
- A string to be concatenated at the end of the other string
Return Value
- Concatenated(combined) string
Illustration
Consider the below illustration
Input:
String 1 : ABC
String 2 : def
String n-1 : …
String n : xyzOutput:Â
abcdef…xyz
Examples of Java String concat()
The following examples demonstrates how to use the String concat() function in Java program
Example 1:
java
// Java program to Illustrate Working of concat() method // with Strings // By explicitly assigning result   // Main class class GFG {     // Main driver method     public static void main(String args[])     {         // Custom input string 1         String s = "Hello " ;           // Custom input string 2         s = s.concat( "World" );           // Explicitly assigning result by         // Combining(adding, concatenating strings)         // using concat() method           // Print and display combined string         System.out.println(s);     } } |
Hello World
Example 2:
java
// Java program to Illustrate Working of concat() method // in strings where we are sequentially // adding multiple strings as we need   // Main class public class GFG {       // Main driver method     public static void main(String args[])     {         // Custom string 1         String str1 = "Computer-" ;           // Custom string 2         String str2 = "-Science" ;           // Combining above strings by         // passing one string as an argument         String str3 = str1.concat(str2);           // Print and display temporary combined string         System.out.println(str3);           String str4 = "-Portal" ;         String str5 = str3.concat(str4);         System.out.println(str5);     } } |
Computer--Science Computer--Science-Portal
Note: As perceived from the code we can do as many times as we want to concatenate strings bypassing older strings with new strings to be contaminated as a parameter and storing the resultant string in String datatype.
Using ‘+’ for String Concatenation in Java
We can use the ‘+’ operator for strings in the same way we use for variables.
Below is the implementation of the above topic:
Java
// Java Program to concatenate // two Strings import java.io.*; Â Â class GFG { Â Â Â Â Â Â public static void main(String[] args) Â Â Â Â { Â Â Â Â Â Â Â Â // str 1 Â Â Â Â Â Â Â Â String str1 = "Hello" ; Â Â Â Â Â Â Â Â Â Â // + operator do concat here! Â Â Â Â Â Â Â Â String result = str1 + ", World!" ; Â Â Â Â Â Â Â Â Â Â // Output: Hello, World! Â Â Â Â Â Â Â Â System.out.println(result); Â Â Â Â } } |
Hello, World!