Java String concatenation: How to combine (merge) two Strings

Java String FAQ: How do I merge/combine two Java String fields?


NOTE: If performance is an important consideration, use the StringBuffer approach I show below.

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;

The string 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 strings in that last line of code.

Use StringBuffer when working with many strings

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. For more information, here’s a link to a StringBuffer example.

Java String concatenation: Summary

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.