Skip to content

[java] InsufficientStringBufferDeclaration false positive for initial calculated StringBuilder size #1438

@vbrandl

Description

@vbrandl

Affects PMD Version:

  • 6.9.0
  • 5.8.1

Rule:

InsufficientStringBufferDeclaration

Description:

When calculating the size of a StringBuilder at runtime, e.g. by adding the lengths of strings to be appended or by adding constant values e.g. for the output of Date/DecimalFormat will result in a InsufficientStringBufferDeclaration even if the calculated value will be larger than the length of the constant strings alone.

Code Sample demonstrating the issue:

public String foo(final String x, final String y, final double z, final Date d, final double v) {
	final StringBuilder sb = new StringBuilder(20 + 9*2 + 16 + 2 * x.length() + y.length());
	final DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
	df.applyPattern("#,##0.000");
	final SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm");
	sb.append("foobar")
		.append(df.format(z))
		.append(' ')
		.append(x)
		.append(y)
		.append("foobar")
		.append(sdf.format(d))
		.append("foobar")
		.append(df.format(v))
		.append(' ')
		.append(x);
	return sb.toString();
}

Running PMD through: Gradle

Metadata

Metadata

Assignees

Labels

a:false-positivePMD flags a piece of code that is not problematic

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions