How do I concatenate two strings in Java?

Solution 1:

You can concatenate Strings using the + operator:

System.out.println("Your number is " + theNumber + "!");

theNumber is implicitly converted to the String "42".

Solution 2:

The concatenation operator in java is +, not .

Read this (including all subsections) before you start. Try to stop thinking the php way ;)

To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:

new StringBuilder().append("firstString").append("secondString").toString()

Solution 3:

There are two basic answers to this question:

  1. [simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
  2. [less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");

value.toString();

I recommend against stacking operations like this:

new StringBuilder().append("I").append("like to write").append("confusing code");

Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.

Note: Spaceisavaluablecommodity,asthissentancedemonstrates.

Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below

Example 1

String Blam = one + two;
Blam += three + four;
Blam += five + six;

Example 2

String Blam = one + two + three + four + five + six;

Solution 4:

Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:

1. The simplest way

You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and

  1. In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
  2. In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).

Example with a non null object:

Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

Output:

Your number is 42!

Example with a null object:

Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");

Output:

Your number is null!

Example with a primitive type:

int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

Output:

Your number is 42!

2. The explicit way and potentially the most efficient one

You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.

Example:

int theNumber = 42;
StringBuilder buffer = new StringBuilder()
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)

Output:

Your number is 42!

Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.

Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.

So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:

Example optimized :

int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)

Output:

Your number is 42!

3. The most readable way

You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.

Example:

int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);

Output:

Your number is 42!
Your number is still 42 with printf!

The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.