Java String concat()

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

Example


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()


Using + Operator for Concatenation

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


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".