Ambiguous String-Plus-Number Concatenation
ID |
java.ambiguous_plus_numeric_string |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
code-style, reliability |
Description
Reports expressions where + concatenates a string literal with two or more consecutive numeric operands, producing ambiguous results.
Rationale
Java evaluates + left-to-right. When a string literal appears before numeric operands, all subsequent + operations become string concatenation rather than arithmetic addition. This is a frequent source of confusing output.
// Bad - prints "2+9 = 29" instead of "2+9 = 11"
System.out.println("2+9 = " + 2 + 9);
Remediation
Wrap the arithmetic expression in parentheses so the addition is evaluated before concatenation:
// Good - parentheses force arithmetic first
System.out.println("2+9 = " + (2 + 9));