• Home
  • String Concatenation in Java

String Concatenation in Java

In Java, string concatenation refers to the process of joining two or more strings together to form a single string. This can be done using the + operator or the concat() method.

Here’s an example of using the + operator to concatenate two strings:

String str1 = "Hello";
String str2 = "World";
String str3 = str1 + " " + str2; // str3 will be "Hello World"

You can also use the concat() method to achieve the same result:

String str1 = "Hello";
String str2 = "World";
String str3 = str1.concat(" ").concat(str2); // str3 will be "Hello World"

It’s important to note that in Java, strings are immutable, meaning that once a string is created, it cannot be changed. Therefore, when you perform string concatenation, a new string is created and the original strings remain unchanged.

Additionally, you can use string concatenation with other data types by first converting them to strings using the toString() method. For example:

int num = 10;
String str = "The value of num is ".concat(Integer.toString(num)); // str will be "The value of num is 10"

String concatenation is a useful tool for creating dynamic strings, such as when building a message to display to the user or when constructing a SQL query.