Java String concat()

The concat() method concatenates (joins) two strings and returns it.

Example

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Programming";

    // concatenate str1 and str2
System.out.println(str1.concat(str2));
} } // Output: JavaProgramming

Syntax of concat()

The syntax of the string concat() method is:

string.concat(String str)

Here, string is an object of the String class.


concat() Parameters

The concat() method takes a single parameter.

  • str - string to be joined

concat() Return Value

  • returns a string which is the concatenation of string and str (argument string)

Example: Java concat()

class Main {
  public static void main(String[] args) {
    String str1 = "Learn ";
    String str2 = "Java";

    // concatenate str1 and str2
System.out.println(str1.concat(str2)); // "Learn Java"
// concatenate str2 and str11
System.out.println(str2.concat(str1)); // "JavaLearn "
} }

Using + Operator for Concatenation

In Java, you can also use the + operator to concatenate two strings. For example,

class Main {
  public static void main(String[] args) {
    String str1 = "Learn ";
    String str2 = "Java";

    // concatenate str1 and str2
System.out.println(str1 + str2); // "Learn Java"
// concatenate str2 and str11
System.out.println(str2 + str1); // "JavaLearn "
} }

concat() Vs the + Operator for Concatenation

concat() the + Operator
Suppose, str1 is null and str2 is "Java". Then, str1.concat(str2) throws NullPointerException. Suppose, str1 is null and str2 is "Java". Then, str1 + str2 gives "nullJava".
You can only pass a String to the concat() method. If one of the operands is a string and another is a non-string value. The non-string value is internally converted to a string before concatenation. For example, "Java" + 5 gives "Java5".