English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java String concat() usage and example

Java String (String) Methods

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

The syntax of the string concat() method is:

str.concat(String str1)

The concat() parameter

  • str1 - The strings to be concatenated

The return value of concat()

  • Returns a string that is the concatenation of str and str1The concatenated string (parameter string)

Example: Java concat()

class Main {}}
  public static void main(String[] args) {
    String str1 = "Learn";
    String str2 = "Java";
    //concat str1and str2
    System.out.println(str1.concat(str2)) // "Learn Java"
    // concat str2and str11
    System.out.println(str2.concat(str1)) // "JavaLearn "
  }
}

Use + operator for string concatenation

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

class Main {}}
  public static void main(String[] args) {
    String str1 = "Learn";
    String str2 = "Java";
    //concat str1and str2
    System.out.println(str1 + str2); // "Learn Java"
    //concat str2and str11
    System.out.println(str2 + str1); // "JavaLearn "
  }
}

concat() with+ operator performs concatenation

concat()+operator

Assume str1is null, str2is "Java".

Then, str1.concat(str2) throwsNullPointerException.

Assumestr1is null,str2is "Java".
Then, str1 + str2Provide"nullJava".

You can only pass a String to the concat() method.

If one of the operands is a string and the other is not a string value.

Before the connection, non-string values will be internally converted to strings.

For example, "Java" + 5Provide "Java5".

Java String (String) Methods