Java Strings: Joining Strings
Joining or Combining Strings in Java
You can JOIN strings together using two techniques:
- The concat() method
- The concatenation or + operator
The concat() method joins one string to another. It combines two strings by placing one after the other. This order is determined by which string is placed to the left of the method and which is placed in the argument space, or the (), of the method. The general syntax is:
firstString.concat(secondString)
Consider the following strings:
String str1 = "Learning"; String str2 = " Glue";
If we wanted to concatenate these two strings to read “Learning Glue” we could use the concat() method like so:
String str1 = "Learning"; String str2 = " Glue";
Alternatively you can use the concatenation operator, +, to perform the same task, we do this by placing the + operator between the strings that we want to concatenate:
System.out.println("Learning" + " Glue");
You can use the concatenation operator to combine any number of strings, and you can use it to combine strings with variables of other datatypes like integers or doubles, for example:
int myAge = 20; String myName = "Andrew"; System.out.println("Hello, my name is " + myName + " and I am " + myAge + " years old.");
This code with output “Hello, my name is Andrew and I am 20 years old.” As you can see the concatenation operator is very useful for constructing simple of complex messages and you will use this technique a lot.