Java String FAQ: How do I merge/combine two Java String fields?
You can merge/concatenate/combine two Java String fields using the
+ operator, as shown in this example code:
// define two strings String firstName = "Fred"; String lastName = "Flinstone"; // concatenate the strings String fullName = firstName + lastName;
fullName now contains "FredFlinstone". Note that there is no space between "Fred" and "Flinstone" because I didn’t put a space in there.
One way to add a space to the new string is to put one in there, as shown in this example:
String firstName = "Fred"; String lastName = "Flinstone"; String fullName = firstName + " " + lastName;
In that example, I’m combining/merging three Java Strings in that last line of code.
I hope these Java String concatenation examples have been helpful. As you can see, for simple string concatenation operations you can just add Java Strings together using the
+ operator. But as an important note, if you’re going to be adding a lot of Java String objects together, it’s much more efficient to use the Java
StringBuffer class. Just search this site for "Java StringBuffer" to find more String concatenation examples.