In Java, you can use the +
operator to concatenate (combine) two strings. Here's an example:
String s1 = "Hello"; String s2 = "World"; String s3 = s1 + " " + s2; // s3 is "Hello World"
You can also use the concat
method of the String
class to concatenate two strings. This method returns a new string that is the result of concatenating the two input strings. Here's an example:
String s1 = "Hello"; String s2 = "World"; String s3 = s1.concat(" ").concat(s2); // s3 is "Hello World"
Note that the +
operator and the concat
method are both overloaded for other types such as integers, so you can use them to concatenate strings with other types as well. For example:
String s = "The number is: " + 42; // s is "The number is: 42"
It's generally recommended to use the +
operator for concatenating strings, as it is more efficient than the concat
method. However, the concat
method can be useful if you want to chain multiple concatenation operations together, as in the second example above.