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









