The
String class includes a method for concatenating two strings:string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the
concat() method with string literals, as in:"My name is ".concat("Rumplestiltskin");
Strings are more commonly concatenated with the
+ operator, as in"Hello," + " world" + "!"
which results in
"Hello, world!"
The
+ operator is widely used in print statements. For example:String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
which prints
Dot saw I was Tod
Such a concatenation can be a mixture of any objects. For each object that is not a
String, its toString() method is called to convert it to a String.Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the
+ concatenation operator at the end of each line in a multi-line string. For example,String quote =
"Now is the time for all good " +
"men to come to the aid of their country.";
+ concatenation operator is, once again, very common in print statements.