• Home
  • How do you concatenate two strings str1 and str2 in Java?

How do you concatenate two strings str1 and str2 in Java?

To concatenate two strings str1 and str2 in Java, you can use the + operator or the concat() method.

Here is an example using the + operator:

String str1 = "Hello";
String str2 = "World";
String concatenated = str1 + str2; // "HelloWorld"

Here is an example using the concat() method:

String str1 = "Hello";
String str2 = "World";
String concatenated = str1.concat(str2); // "HelloWorld"

Note that you can also use the += operator to concatenate strings. For example:

String str1 = "Hello";
String str2 = "World";
str1 += str2; // str1 is now "HelloWorld"

You can also use the StringBuilder class to concatenate strings. This is a mutable class that allows you to append strings to the end of a string in a more efficient way than using the + operator or the concat() method. Here is an example:

String str1 = "Hello";
String str2 = "World";
StringBuilder sb = new StringBuilder();
sb.append(str1).append(str2);
String concatenated = sb.toString(); // "HelloWorld"

Finally, you can also use the String.format() method to create a formatted string that includes the concatenation of multiple strings. This method takes a format string as its first argument, which can contain placeholders for the strings you want to concatenate. The placeholders are represented by %s and are replaced by the corresponding arguments passed to the format() method. Here is an example:

String str1 = "Hello";
String str2 = "World";
String concatenated = String.format("%s %s", str1, str2); // "Hello World"