EMZETT.
Login

String Concatenation

In short: Joining several strings (strings) into a single one — e.g. to combine a name and a greeting into a complete output line.

In more detail: In many languages, the + operator can be used both for numbers (addition) and for strings (concatenation), which occasionally leads to surprising results when a number and a string are mixed in the same expression. For very many concatenations in a loop, repeated + is often inefficient, because for immutable strings a completely new string is created every time — there’s usually a dedicated, more efficient StringBuilder-like mechanism for this.

In Depth

"Hello, " + "World"          // "Hello, World"
"Result: " + 42            // "Result: 42" - number is automatically converted to a string
5 + "5"                      // "55" instead of 10 - a typical source of error!
5 + 5 + "5"                  // "105" - left to right: first 5+5=10, then +"5"
"5" + 5 + 5                  // "555" - now everything after the first "+" becomes a string

This automatic type conversion (“type coercion”) is a common source of error especially in dynamically typed languages like JavaScript — whether + is interpreted as addition or concatenation depends on the TYPE of the operands, and for mixed expressions, left-to-right order often matters. Statically typed languages (e.g. Java) behave more consistently here, but there too, + with a string operand automatically converts the other side into a string.

The efficiency pitfall shows up especially in loops:

# Inefficient for many iterations: every += creates a COMPLETELY NEW string
result = ""
for word in list_:
    result = result + word + " "
 
# More efficient: collect parts and concatenate only once at the end
parts = []
for word in list_:
    parts.append(word)
result = " ".join(parts)

Because strings in most modern languages are immutable, every apparent concatenation internally creates a completely new string in memory, instead of extending the existing one — for N concatenations in a loop, this can lead to quadratic instead of linear effort. For exactly this case, most languages offer a special, mutable “builder” type (e.g. StringBuilder in Java, lists followed by join() in Python), which efficiently collects intermediate results without recopying at every step.

See also: Strings, Numbers & Strings