Files
Marcin Mikosikandintellij-monorepo-bot a523332df0 [java] IDEA-379317 Add StringBuilderRepeatCanBeUsedFix
This is the first part of IDEA-379317 ticket.
Second part - Suggestion to convert sb.append("*".repeat(10)); to sb.repeat("*", 10); - will be provided in separate merge request.

Merge-request: IJ-MR-179573
Merged-by: Marcin Mikosik <marcin.mikosik@jetbrains.com>

GitOrigin-RevId: c52077e6659b3d0108dc6145456fe98da681cfb4
2025-10-29 16:38:38 +00:00

30 lines
1.3 KiB
HTML

<html>
<body>
Reports loops that can be replaced with a single <code>StringBuilder.repeat()</code> method (available since Java 21) or
<code>String.repeat()</code> method (available since Java 11).
<p><b>Example (Java 11):</b></p>
<pre><code>
void append(StringBuilder sb, int count, Object obj) {
for (int i = 0; i &lt; count; i++) {
sb.append(obj);
}
}
</code></pre>
<p>After the quick-fix is applied:</p>
<pre><code>
void append(StringBuilder sb, int count, Object obj) {
sb.append(String.valueOf(obj).repeat(Math.max(0, count)));
}
</code></pre>
<!-- tooltip end -->
<p>
By default, the inspection may wrap <code>count</code> with <code>Math.max(0, count)</code> if it cannot prove statically that <code>count</code> is
not negative. This is done to prevent possible semantics change, as <code>String.repeat()</code> rejects negative numbers.
Use the <b>Add Math.max(0,count) to avoid possible semantics change</b> option to disable this behavior if required.</p>
<p>Similarly, a string you want to repeat can be wrapped in
<code>String.valueOf</code> to prevent possible <code>NullPointerException</code> if it's unknown whether it can be <code>null</code>.
</p>
<p>This inspection only reports if the language level of the project or module is 11 or higher.</p>
<p><small>New in 2019.1</small></p>
</body>
</html>