How do I concatenate two strings in Java?
You can concatenate Strings using the +
operator:
System.out.println("Your number is " + theNumber + "!");
theNumber
is implicitly converted to the String "42"
.
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()
There are two basic answers to this question:
- [simple] Use the
+
operator (string concatenation)."your number is" + theNumber + "!"
(as noted elsewhere) - [less simple]: Use
StringBuilder
(orStringBuffer
).
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;