Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8313809

String template fails with java.lang.StringIndexOutOfBoundsException if last fragment is UTF16

    XMLWordPrintable

Details

    Backports

      Description

        The following code compiles successfully but fails at runtime with a StringIndexOutOfBoundsException:


        import java.math.*;
        import static java.util.FormatProcessor.*;

        public class Foo {
            public static void main(final String[] args) throws Exception {
                final BigDecimal sum = new BigDecimal("12.34");

                final String stringFomat = String.format("Using String.format() - The sum is: %s €", sum); // this works
                System.out.println(stringFomat);

                final String message = FMT."The sum is: %f\{sum} €"; // this fails
                System.out.println(message);
            }
        }

        javac --enable-preview --source 21 Foo.java
        java --enable-preview Foo

        Using String.format() - The sum is: 12.34 €
        Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [21, 21 + 4) out of bounds for length 11
            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:4849)
            at java.base/java.lang.StringUTF16.checkBoundsOffCount(StringUTF16.java:1625)
            at java.base/java.lang.StringUTF16.inflate(StringUTF16.java:1459)
            at java.base/java.lang.StringLatin1.inflate(StringLatin1.java:771)
            at java.base/java.lang.String.getBytes(String.java:4724)
            at java.base/java.lang.StringConcatHelper.newArrayWithSuffix(StringConcatHelper.java:491)
            at Foo.main(Foo.java:11)


        Attachments

          Issue Links

            Activity

              People

                jlaskey Jim Laskey
                jpai Jaikiran Pai
                Votes:
                0 Vote for this issue
                Watchers:
                5 Start watching this issue

                Dates

                  Created:
                  Updated:
                  Resolved: