StringIndexOutOfBoundsException is thrown from String.concat
Alan Bateman
alan.bateman at oracle.com
Mon May 5 08:06:34 UTC 2025
Can you create a bug in JBS to track this?
-Alan
On 05/05/2025 08:54, Andrey Turbanov wrote:
> Hello.
> I noticed that String.concat can throw StringIndexOutOfBoundsException:
>
> String r1 = "-".repeat(Integer.MAX_VALUE - 10);
> String r2 = "ы".repeat((Integer.MAX_VALUE - 10) / 2);
> System.out.println(r1.concat(r2));
>
> On JDK 24 it gives:
> Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
> Range [0, 0 + 2147483637) out of bounds for length 1073741807
> at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
> at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
> at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
> at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
> at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
> at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:118)
> at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:397)
> at java.base/java.lang.String.checkBoundsOffCount(String.java:4938)
> at java.base/java.lang.StringUTF16.checkBoundsOffCount(StringUTF16.java:1789)
> at java.base/java.lang.StringUTF16.inflate(StringUTF16.java:1616)
> at java.base/java.lang.StringLatin1.inflate(StringLatin1.java:875)
> at java.base/java.lang.String.getBytes(String.java:4812)
> at java.base/java.lang.StringConcatHelper.doConcat(StringConcatHelper.java:434)
> at java.base/java.lang.String.concat(String.java:2977)
>
> On JDK 23 it results in expected OOM:
>
> Exception in thread "main" java.lang.OutOfMemoryError: Overflow:
> String length out of range
> at java.base/java.lang.StringConcatHelper.checkOverflow(StringConcatHelper.java:66)
> at java.base/java.lang.StringConcatHelper.mix(StringConcatHelper.java:125)
> at java.base/java.lang.StringConcatHelper.simpleConcat(StringConcatHelper.java:374)
> at java.base/java.lang.String.concat(String.java:2990)
>
> Andrey Turbanov
More information about the core-libs-dev
mailing list