Java String concatenation - How to combine two Strings

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;

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. Just search this site for "Java StringBuffer" to find more string concatenation examples.

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.