liveBook · Manning

Concatenation

As explained in 100 Java Mistakes and How to Avoid Them

Concatenation is the operation of joining ordered sequences end to end to form a single sequence.

Concatenation joins string fragments from left to right. In Java, the binary + operator also performs numeric addition, so the first string operand can change how later operands are interpreted. section 2.3

Treat these patterns as concrete failure modes:

  • Parenthesize arithmetic inside a concatenation: use "Entry#" + (index + 1), not "Entry#" + index + 1, which produces Entry#41 for index 4. section 2.3
  • Separate conditional logic from concatenation. Without parentheses, "Value: " + value != null ? value : "(unknown)" tests the already-concatenated string, so the null check is always true. section 2.2.3
  • Qualify method calls with the complete result. Applying replace() to the final literal fragment of a multiline concatenation leaves placeholders unchanged without causing a compilation or runtime error. section 2.4
  • Avoid unary plus and character literals in concatenations. An accidental unary plus can widen a quote character to its numeric code, producing incorrect user-facing text. section 2.5

Make evaluation order explicit

Prefer: int adjustedIndex = index + 1; String entryName = "Entry#" + adjustedIndex; For nullable values, compute the branch first: String displayedValue = value != null ? value : "(unknown)"; return "Value: " + displayedValue; Formatting calls can also separate substitution from arithmetic, though modern JVMs may make them slower than concatenation. section 2.3 section 2.2.3

String greetingPage = 
  "<html>\n" + 
  "  <head><title>Welcome</title></head>\n" + 
  "  <body>\n" + 
  "    <h1>Hello, $user$!</h1>\n" + 
  "    <hr>\n" + 
  "    <p>Welcome to our web-site</p>\n" + 
  "  </body>\n" + 
  "</html>\n".replace("$user$", userName);

Inspect how a method call accidentally binds only to the final fragment, then compare the corrected whole-string operation or a Java 15 text block. section 2.4

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Traces precedence and left-to-right evaluation through focused failures, then stops at prevention and static-analysis guidance.
Examples
Uses index labels, nullable values, list capacity, HTML templates, replacement calls, and diagnostic messages.
What you can do after
Diagnose/debug concatenation bugs and prevent them with parentheses, intermediate variables, formatting, text blocks, and static analysis.
How it connects
Connects concatenation to operator precedence, numeric addition, conditional expressions, method calls, character widening, formatting, and text blocks.

Also explained in

Compare how 10 books explain concatenation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.