Inspectopedia Help

String.repeat() can be used

Reports loops that can be replaced with a single String.repeat() method (available since Java 11).

Example:

void append(StringBuilder sb, int count, Object obj) { for (int i = 0; i < count; i++) { sb.append(obj); } }

After the quick-fix is applied:

void append(StringBuilder sb, int count, Object obj) { sb.append(String.valueOf(obj).repeat(Math.max(0, count))); }

By default, the inspection may wrap count with Math.max(0, count) if it cannot prove statically that count is not negative. This is done to prevent possible semantics change, as String.repeat() rejects negative numbers. Use the Add Math.max(0,count) to avoid possible semantics change option to disable this behavior if required.

Similarly, a string you want to repeat can be wrapped in String.valueOf to prevent possible NullPointerException if it's unknown whether it can be null.

This inspection only reports if the language level of the project or module is 11 or higher.

New in 2019.1

Inspection options

Option

Type

Default

Add Math.max(0, count) to avoid possible semantics change

Checkbox

true

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023