       1 /*
       2  * Copyright (c) 1994, 2020, Oracle and/or its affiliates. All rights reserved.
       3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       4  *
       5  * This code is free software; you can redistribute it and/or modify it
       6  * under the terms of the GNU General Public License version 2 only, as
       7  * published by the Free Software Foundation.  Oracle designates this
       8  * particular file as subject to the "Classpath" exception as provided
       9  * by Oracle in the LICENSE file that accompanied this code.
      10  *
      11  * This code is distributed in the hope that it will be useful, but WITHOUT
      12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      14  * version 2 for more details (a copy is included in the LICENSE file that
      15  * accompanied this code).
      16  *
      17  * You should have received a copy of the GNU General Public License version
      18  * 2 along with this work; if not, write to the Free Software Foundation,
      19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
      20  *
      21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
      22  * or visit www.oracle.com if you need additional information or have any
      23  * questions.
      24  */
      25
      26 package java.lang;
      27
      28 import java.io.ObjectStreamField;
      29 import java.io.UnsupportedEncodingException;
      30 import java.lang.annotation.Native;
      31 import java.lang.invoke.MethodHandles;
      32 import java.lang.constant.Constable;
      33 import java.lang.constant.ConstantDesc;
      34 import java.nio.charset.Charset;
      35 import java.util.ArrayList;
      36 import java.util.Arrays;
      37 import java.util.Comparator;
      38 import java.util.Formatter;
      39 import java.util.List;
      40 import java.util.Locale;
      41 import java.util.Objects;
      42 import java.util.Optional;
      43 import java.util.Spliterator;
      44 import java.util.StringJoiner;
      45 import java.util.function.Function;
      46 import java.util.regex.Pattern;
      47 import java.util.regex.PatternSyntaxException;
      48 import java.util.stream.Collectors;
      49 import java.util.stream.IntStream;
      50 import java.util.stream.Stream;
      51 import java.util.stream.StreamSupport;
      52 import jdk.internal.HotSpotIntrinsicCandidate;
      53 import jdk.internal.vm.annotation.Stable;
      54
      55 import static java.util.function.Predicate.not;
      56
      57 /**
      58  * The {@code String} class represents character strings. All
      59  * string literals in Java programs, such as {@code "abc"}, are
      60  * implemented as instances of this class.
      61  * <p>
      62  * Strings are constant; their values cannot be changed after they
      63  * are created. String buffers support mutable strings.
      64  * Because String objects are immutable they can be shared. For example:
      65  * <blockquote><pre>
      66  *     String str = "abc";
      67  * </pre></blockquote><p>
      68  * is equivalent to:
      69  * <blockquote><pre>
      70  *     char data[] = {'a', 'b', 'c'};
      71  *     String str = new String(data);
      72  * </pre></blockquote><p>
      73  * Here are some more examples of how strings can be used:
      74  * <blockquote><pre>
      75  *     System.out.println("abc");
      76  *     String cde = "cde";
      77  *     System.out.println("abc" + cde);
      78  *     String c = "abc".substring(2, 3);
      79  *     String d = cde.substring(1, 2);
      80  * </pre></blockquote>
      81  * <p>
      82  * The class {@code String} includes methods for examining
      83  * individual characters of the sequence, for comparing strings, for
      84  * searching strings, for extracting substrings, and for creating a
      85  * copy of a string with all characters translated to uppercase or to
      86  * lowercase. Case mapping is based on the Unicode Standard version
      87  * specified by the {@link java.lang.Character Character} class.
      88  * <p>
      89  * The Java language provides special support for the string
      90  * concatenation operator (&nbsp;+&nbsp;), and for conversion of
      91  * other objects to strings. For additional information on string
      92  * concatenation and conversion, see <i>The Java Language Specification</i>.
      93  *
      94  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
      95  * or method in this class will cause a {@link NullPointerException} to be
      96  * thrown.
      97  *
      98  * <p>A {@code String} represents a string in the UTF-16 format
      99  * in which <em>supplementary characters</em> are represented by <em>surrogate
     100  * pairs</em> (see the section <a href="Character.html#unicode">Unicode
     101  * Character Representations</a> in the {@code Character} class for
     102  * more information).
     103  * Index values refer to {@code char} code units, so a supplementary
     104  * character uses two positions in a {@code String}.
     105  * <p>The {@code String} class provides methods for dealing with
     106  * Unicode code points (i.e., characters), in addition to those for
     107  * dealing with Unicode code units (i.e., {@code char} values).
     108  *
     109  * <p>Unless otherwise noted, methods for comparing Strings do not take locale
     110  * into account.  The {@link java.text.Collator} class provides methods for
     111  * finer-grain, locale-sensitive String comparison.
     112  *
     113  * @implNote The implementation of the string concatenation operator is left to
     114  * the discretion of a Java compiler, as long as the compiler ultimately conforms
     115  * to <i>The Java Language Specification</i>. For example, the {@code javac} compiler
     116  * may implement the operator with {@code StringBuffer}, {@code StringBuilder},
     117  * or {@code java.lang.invoke.StringConcatFactory} depending on the JDK version. The
     118  * implementation of string conversion is typically through the method {@code toString},
     119  * defined by {@code Object} and inherited by all classes in Java.
     120  *
     121  * @author  Lee Boynton
     122  * @author  Arthur van Hoff
     123  * @author  Martin Buchholz
     124  * @author  Ulf Zibis
     125  * @see     java.lang.Object#toString()
     126  * @see     java.lang.StringBuffer
     127  * @see     java.lang.StringBuilder
     128  * @see     java.nio.charset.Charset
     129  * @since   1.0
     130  * @jls     15.18.1 String Concatenation Operator +
     131  */
     132
     133 public final class String
     134     implements java.io.Serializable, Comparable<String>, CharSequence,
     135                Constable, ConstantDesc {
     136
     137     /**
     138      * The value is used for character storage.
     139      *
     140      * @implNote This field is trusted by the VM, and is a subject to
     141      * constant folding if String instance is constant. Overwriting this
     142      * field after construction will cause problems.
     143      *
     144      * Additionally, it is marked with {@link Stable} to trust the contents
     145      * of the array. No other facility in JDK provides this functionality (yet).
     146      * {@link Stable} is safe here, because value is never null.
     147      */
     148     @Stable
     149     private final byte[] value;
     150
     151     /**
     152      * The identifier of the encoding used to encode the bytes in
     153      * {@code value}. The supported values in this implementation are
     154      *
     155      * LATIN1
     156      * UTF16
     157      *
     158      * @implNote This field is trusted by the VM, and is a subject to
     159      * constant folding if String instance is constant. Overwriting this
     160      * field after construction will cause problems.
     161      */
     162     private final byte coder;
     163
     164     /** Cache the hash code for the string */
     165     private int hash; // Default to 0
     166
     167     /**
     168      * Cache if the hash has been calculated as actually being zero, enabling
     169      * us to avoid recalculating this.
     170      */
     171     private boolean hashIsZero; // Default to false;
     172
     173     /** use serialVersionUID from JDK 1.0.2 for interoperability */
     174     @java.io.Serial
     175     private static final long serialVersionUID = -6849794470754667710L;
     176
     177     /**
     178      * If String compaction is disabled, the bytes in {@code value} are
     179      * always encoded in UTF16.
     180      *
     181      * For methods with several possible implementation paths, when String
     182      * compaction is disabled, only one code path is taken.
     183      *
     184      * The instance field value is generally opaque to optimizing JIT
     185      * compilers. Therefore, in performance-sensitive place, an explicit
     186      * check of the static boolean {@code COMPACT_STRINGS} is done first
     187      * before checking the {@code coder} field since the static boolean
     188      * {@code COMPACT_STRINGS} would be constant folded away by an
     189      * optimizing JIT compiler. The idioms for these cases are as follows.
     190      *
     191      * For code such as:
     192      *
     193      *    if (coder == LATIN1) { ... }
     194      *
     195      * can be written more optimally as
     196      *
     197      *    if (coder() == LATIN1) { ... }
     198      *
     199      * or:
     200      *
     201      *    if (COMPACT_STRINGS && coder == LATIN1) { ... }
     202      *
     203      * An optimizing JIT compiler can fold the above conditional as:
     204      *
     205      *    COMPACT_STRINGS == true  => if (coder == LATIN1) { ... }
     206      *    COMPACT_STRINGS == false => if (false)           { ... }
     207      *
     208      * @implNote
     209      * The actual value for this field is injected by JVM. The static
     210      * initialization block is used to set the value here to communicate
     211      * that this static final field is not statically foldable, and to
     212      * avoid any possible circular dependency during vm initialization.
     213      */
     214     static final boolean COMPACT_STRINGS;
     215
     216     static {
     217         COMPACT_STRINGS = true;
     218     }
     219
     220     /**
     221      * Class String is special cased within the Serialization Stream Protocol.
     222      *
     223      * A String instance is written into an ObjectOutputStream according to
     224      * <a href="{@docRoot}/../specs/serialization/protocol.html#stream-elements">
     225      * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
     226      */
     227     @java.io.Serial
     228     private static final ObjectStreamField[] serialPersistentFields =
     229         new ObjectStreamField[0];
     230
     231     /**
     232      * Initializes a newly created {@code String} object so that it represents
     233      * an empty character sequence.  Note that use of this constructor is
     234      * unnecessary since Strings are immutable.
     235      */
     236     public String() {
     237         this.value = "".value;
     238         this.coder = "".coder;
     239     }
     240
     241     /**
     242      * Initializes a newly created {@code String} object so that it represents
     243      * the same sequence of characters as the argument; in other words, the
     244      * newly created string is a copy of the argument string. Unless an
     245      * explicit copy of {@code original} is needed, use of this constructor is
     246      * unnecessary since Strings are immutable.
     247      *
     248      * @param  original
     249      *         A {@code String}
     250      */
     251     @HotSpotIntrinsicCandidate
     252     public String(String original) {
     253         this.value = original.value;
     254         this.coder = original.coder;
     255         this.hash = original.hash;
     256     }
     257
     258     /**
     259      * Allocates a new {@code String} so that it represents the sequence of
     260      * characters currently contained in the character array argument. The
     261      * contents of the character array are copied; subsequent modification of
     262      * the character array does not affect the newly created string.
     263      *
     264      * @param  value
     265      *         The initial value of the string
     266      */
     267     public String(char value[]) {
     268         this(value, 0, value.length, null);
     269     }
     270
     271     /**
     272      * Allocates a new {@code String} that contains characters from a subarray
     273      * of the character array argument. The {@code offset} argument is the
     274      * index of the first character of the subarray and the {@code count}
     275      * argument specifies the length of the subarray. The contents of the
     276      * subarray are copied; subsequent modification of the character array does
     277      * not affect the newly created string.
     278      *
     279      * @param  value
     280      *         Array that is the source of characters
     281      *
     282      * @param  offset
     283      *         The initial offset
     284      *
     285      * @param  count
     286      *         The length
     287      *
     288      * @throws  IndexOutOfBoundsException
     289      *          If {@code offset} is negative, {@code count} is negative, or
     290      *          {@code offset} is greater than {@code value.length - count}
     291      */
     292     public String(char value[], int offset, int count) {
     293         this(value, offset, count, rangeCheck(value, offset, count));
     294     }
     295
     296     private static Void rangeCheck(char[] value, int offset, int count) {
     297         checkBoundsOffCount(offset, count, value.length);
     298         return null;
     299     }
     300
     301     /**
     302      * Allocates a new {@code String} that contains characters from a subarray
     303      * of the <a href="Character.html#unicode">Unicode code point</a> array
     304      * argument.  The {@code offset} argument is the index of the first code
     305      * point of the subarray and the {@code count} argument specifies the
     306      * length of the subarray.  The contents of the subarray are converted to
     307      * {@code char}s; subsequent modification of the {@code int} array does not
     308      * affect the newly created string.
     309      *
     310      * @param  codePoints
     311      *         Array that is the source of Unicode code points
     312      *
     313      * @param  offset
     314      *         The initial offset
     315      *
     316      * @param  count
     317      *         The length
     318      *
     319      * @throws  IllegalArgumentException
     320      *          If any invalid Unicode code point is found in {@code
     321      *          codePoints}
     322      *
     323      * @throws  IndexOutOfBoundsException
     324      *          If {@code offset} is negative, {@code count} is negative, or
     325      *          {@code offset} is greater than {@code codePoints.length - count}
     326      *
     327      * @since  1.5
     328      */
     329     public String(int[] codePoints, int offset, int count) {
     330         checkBoundsOffCount(offset, count, codePoints.length);
     331         if (count == 0) {
     332             this.value = "".value;
     333             this.coder = "".coder;
     334             return;
     335         }
     336         if (COMPACT_STRINGS) {
     337             byte[] val = StringLatin1.toBytes(codePoints, offset, count);
     338             if (val != null) {
     339                 this.coder = LATIN1;
     340                 this.value = val;
     341                 return;
     342             }
     343         }
     344         this.coder = UTF16;
     345         this.value = StringUTF16.toBytes(codePoints, offset, count);
     346     }
     347
     348     /**
     349      * Allocates a new {@code String} constructed from a subarray of an array
     350      * of 8-bit integer values.
     351      *
     352      * <p> The {@code offset} argument is the index of the first byte of the
     353      * subarray, and the {@code count} argument specifies the length of the
     354      * subarray.
     355      *
     356      * <p> Each {@code byte} in the subarray is converted to a {@code char} as
     357      * specified in the {@link #String(byte[],int) String(byte[],int)} constructor.
     358      *
     359      * @deprecated This method does not properly convert bytes into characters.
     360      * As of JDK&nbsp;1.1, the preferred way to do this is via the
     361      * {@code String} constructors that take a {@link
     362      * java.nio.charset.Charset}, charset name, or that use the platform's
     363      * default charset.
     364      *
     365      * @param  ascii
     366      *         The bytes to be converted to characters
     367      *
     368      * @param  hibyte
     369      *         The top 8 bits of each 16-bit Unicode code unit
     370      *
     371      * @param  offset
     372      *         The initial offset
     373      * @param  count
     374      *         The length
     375      *
     376      * @throws  IndexOutOfBoundsException
     377      *          If {@code offset} is negative, {@code count} is negative, or
     378      *          {@code offset} is greater than {@code ascii.length - count}
     379      *
     380      * @see  #String(byte[], int)
     381      * @see  #String(byte[], int, int, java.lang.String)
     382      * @see  #String(byte[], int, int, java.nio.charset.Charset)
     383      * @see  #String(byte[], int, int)
     384      * @see  #String(byte[], java.lang.String)
     385      * @see  #String(byte[], java.nio.charset.Charset)
     386      * @see  #String(byte[])
     387      */
     388     @Deprecated(since="1.1")
     389     public String(byte ascii[], int hibyte, int offset, int count) {
     390         checkBoundsOffCount(offset, count, ascii.length);
     391         if (count == 0) {
     392             this.value = "".value;
     393             this.coder = "".coder;
     394             return;
     395         }
     396         if (COMPACT_STRINGS && (byte)hibyte == 0) {
     397             this.value = Arrays.copyOfRange(ascii, offset, offset + count);
     398             this.coder = LATIN1;
     399         } else {
     400             hibyte <<= 8;
     401             byte[] val = StringUTF16.newBytesFor(count);
     402             for (int i = 0; i < count; i++) {
     403                 StringUTF16.putChar(val, i, hibyte | (ascii[offset++] & 0xff));
     404             }
     405             this.value = val;
     406             this.coder = UTF16;
     407         }
     408     }
     409
     410     /**
     411      * Allocates a new {@code String} containing characters constructed from
     412      * an array of 8-bit integer values. Each character <i>c</i> in the
     413      * resulting string is constructed from the corresponding component
     414      * <i>b</i> in the byte array such that:
     415      *
     416      * <blockquote><pre>
     417      *     <b><i>c</i></b> == (char)(((hibyte &amp; 0xff) &lt;&lt; 8)
     418      *                         | (<b><i>b</i></b> &amp; 0xff))
     419      * </pre></blockquote>
     420      *
     421      * @deprecated  This method does not properly convert bytes into
     422      * characters.  As of JDK&nbsp;1.1, the preferred way to do this is via the
     423      * {@code String} constructors that take a {@link
     424      * java.nio.charset.Charset}, charset name, or that use the platform's
     425      * default charset.
     426      *
     427      * @param  ascii
     428      *         The bytes to be converted to characters
     429      *
     430      * @param  hibyte
     431      *         The top 8 bits of each 16-bit Unicode code unit
     432      *
     433      * @see  #String(byte[], int, int, java.lang.String)
     434      * @see  #String(byte[], int, int, java.nio.charset.Charset)
     435      * @see  #String(byte[], int, int)
     436      * @see  #String(byte[], java.lang.String)
     437      * @see  #String(byte[], java.nio.charset.Charset)
     438      * @see  #String(byte[])
     439      */
     440     @Deprecated(since="1.1")
     441     public String(byte ascii[], int hibyte) {
     442         this(ascii, hibyte, 0, ascii.length);
     443     }
     444
     445     /**
     446      * Constructs a new {@code String} by decoding the specified subarray of
     447      * bytes using the specified charset.  The length of the new {@code String}
     448      * is a function of the charset, and hence may not be equal to the length
     449      * of the subarray.
     450      *
     451      * <p> The behavior of this constructor when the given bytes are not valid
     452      * in the given charset is unspecified.  The {@link
     453      * java.nio.charset.CharsetDecoder} class should be used when more control
     454      * over the decoding process is required.
     455      *
     456      * @param  bytes
     457      *         The bytes to be decoded into characters
     458      *
     459      * @param  offset
     460      *         The index of the first byte to decode
     461      *
     462      * @param  length
     463      *         The number of bytes to decode
     464      *
     465      * @param  charsetName
     466      *         The name of a supported {@linkplain java.nio.charset.Charset
     467      *         charset}
     468      *
     469      * @throws  UnsupportedEncodingException
     470      *          If the named charset is not supported
     471      *
     472      * @throws  IndexOutOfBoundsException
     473      *          If {@code offset} is negative, {@code length} is negative, or
     474      *          {@code offset} is greater than {@code bytes.length - length}
     475      *
     476      * @since  1.1
     477      */
     478     public String(byte bytes[], int offset, int length, String charsetName)
     479             throws UnsupportedEncodingException {
     480         if (charsetName == null)
     481             throw new NullPointerException("charsetName");
     482         checkBoundsOffCount(offset, length, bytes.length);
     483         StringCoding.Result ret =
     484             StringCoding.decode(charsetName, bytes, offset, length);
     485         this.value = ret.value;
     486         this.coder = ret.coder;
     487     }
     488
     489     /**
     490      * Constructs a new {@code String} by decoding the specified subarray of
     491      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
     492      * The length of the new {@code String} is a function of the charset, and
     493      * hence may not be equal to the length of the subarray.
     494      *
     495      * <p> This method always replaces malformed-input and unmappable-character
     496      * sequences with this charset's default replacement string.  The {@link
     497      * java.nio.charset.CharsetDecoder} class should be used when more control
     498      * over the decoding process is required.
     499      *
     500      * @param  bytes
     501      *         The bytes to be decoded into characters
     502      *
     503      * @param  offset
     504      *         The index of the first byte to decode
     505      *
     506      * @param  length
     507      *         The number of bytes to decode
     508      *
     509      * @param  charset
     510      *         The {@linkplain java.nio.charset.Charset charset} to be used to
     511      *         decode the {@code bytes}
     512      *
     513      * @throws  IndexOutOfBoundsException
     514      *          If {@code offset} is negative, {@code length} is negative, or
     515      *          {@code offset} is greater than {@code bytes.length - length}
     516      *
     517      * @since  1.6
     518      */
     519     public String(byte bytes[], int offset, int length, Charset charset) {
     520         if (charset == null)
     521             throw new NullPointerException("charset");
     522         checkBoundsOffCount(offset, length, bytes.length);
     523         StringCoding.Result ret =
     524             StringCoding.decode(charset, bytes, offset, length);
     525         this.value = ret.value;
     526         this.coder = ret.coder;
     527     }
     528
     529     /**
     530      * Constructs a new {@code String} by decoding the specified array of bytes
     531      * using the specified {@linkplain java.nio.charset.Charset charset}.  The
     532      * length of the new {@code String} is a function of the charset, and hence
     533      * may not be equal to the length of the byte array.
     534      *
     535      * <p> The behavior of this constructor when the given bytes are not valid
     536      * in the given charset is unspecified.  The {@link
     537      * java.nio.charset.CharsetDecoder} class should be used when more control
     538      * over the decoding process is required.
     539      *
     540      * @param  bytes
     541      *         The bytes to be decoded into characters
     542      *
     543      * @param  charsetName
     544      *         The name of a supported {@linkplain java.nio.charset.Charset
     545      *         charset}
     546      *
     547      * @throws  UnsupportedEncodingException
     548      *          If the named charset is not supported
     549      *
     550      * @since  1.1
     551      */
     552     public String(byte bytes[], String charsetName)
     553             throws UnsupportedEncodingException {
     554         this(bytes, 0, bytes.length, charsetName);
     555     }
     556
     557     /**
     558      * Constructs a new {@code String} by decoding the specified array of
     559      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
     560      * The length of the new {@code String} is a function of the charset, and
     561      * hence may not be equal to the length of the byte array.
     562      *
     563      * <p> This method always replaces malformed-input and unmappable-character
     564      * sequences with this charset's default replacement string.  The {@link
     565      * java.nio.charset.CharsetDecoder} class should be used when more control
     566      * over the decoding process is required.
     567      *
     568      * @param  bytes
     569      *         The bytes to be decoded into characters
     570      *
     571      * @param  charset
     572      *         The {@linkplain java.nio.charset.Charset charset} to be used to
     573      *         decode the {@code bytes}
     574      *
     575      * @since  1.6
     576      */
     577     public String(byte bytes[], Charset charset) {
     578         this(bytes, 0, bytes.length, charset);
     579     }
     580
     581     /**
     582      * Constructs a new {@code String} by decoding the specified subarray of
     583      * bytes using the platform's default charset.  The length of the new
     584      * {@code String} is a function of the charset, and hence may not be equal
     585      * to the length of the subarray.
     586      *
     587      * <p> The behavior of this constructor when the given bytes are not valid
     588      * in the default charset is unspecified.  The {@link
     589      * java.nio.charset.CharsetDecoder} class should be used when more control
     590      * over the decoding process is required.
     591      *
     592      * @param  bytes
     593      *         The bytes to be decoded into characters
     594      *
     595      * @param  offset
     596      *         The index of the first byte to decode
     597      *
     598      * @param  length
     599      *         The number of bytes to decode
     600      *
     601      * @throws  IndexOutOfBoundsException
     602      *          If {@code offset} is negative, {@code length} is negative, or
     603      *          {@code offset} is greater than {@code bytes.length - length}
     604      *
     605      * @since  1.1
     606      */
     607     public String(byte bytes[], int offset, int length) {
     608         checkBoundsOffCount(offset, length, bytes.length);
     609         StringCoding.Result ret = StringCoding.decode(bytes, offset, length);
     610         this.value = ret.value;
     611         this.coder = ret.coder;
     612     }
     613
     614     /**
     615      * Constructs a new {@code String} by decoding the specified array of bytes
     616      * using the platform's default charset.  The length of the new {@code
     617      * String} is a function of the charset, and hence may not be equal to the
     618      * length of the byte array.
     619      *
     620      * <p> The behavior of this constructor when the given bytes are not valid
     621      * in the default charset is unspecified.  The {@link
     622      * java.nio.charset.CharsetDecoder} class should be used when more control
     623      * over the decoding process is required.
     624      *
     625      * @param  bytes
     626      *         The bytes to be decoded into characters
     627      *
     628      * @since  1.1
     629      */
     630     public String(byte[] bytes) {
     631         this(bytes, 0, bytes.length);
     632     }
     633
     634     /**
     635      * Allocates a new string that contains the sequence of characters
     636      * currently contained in the string buffer argument. The contents of the
     637      * string buffer are copied; subsequent modification of the string buffer
     638      * does not affect the newly created string.
     639      *
     640      * @param  buffer
     641      *         A {@code StringBuffer}
     642      */
     643     public String(StringBuffer buffer) {
     644         this(buffer.toString());
     645     }
     646
     647     /**
     648      * Allocates a new string that contains the sequence of characters
     649      * currently contained in the string builder argument. The contents of the
     650      * string builder are copied; subsequent modification of the string builder
     651      * does not affect the newly created string.
     652      *
     653      * <p> This constructor is provided to ease migration to {@code
     654      * StringBuilder}. Obtaining a string from a string builder via the {@code
     655      * toString} method is likely to run faster and is generally preferred.
     656      *
     657      * @param   builder
     658      *          A {@code StringBuilder}
     659      *
     660      * @since  1.5
     661      */
     662     public String(StringBuilder builder) {
     663         this(builder, null);
     664     }
     665
     666     /**
     667      * Returns the length of this string.
     668      * The length is equal to the number of <a href="Character.html#unicode">Unicode
     669      * code units</a> in the string.
     670      *
     671      * @return  the length of the sequence of characters represented by this
     672      *          object.
     673      */
     674     public int length() {
     675         return value.length >> coder();
     676     }
     677
     678     /**
     679      * Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
     680      *
     681      * @return {@code true} if {@link #length()} is {@code 0}, otherwise
     682      * {@code false}
     683      *
     684      * @since 1.6
     685      */
     686     @Override
     687     public boolean isEmpty() {
     688         return value.length == 0;
     689     }
     690
     691     /**
     692      * Returns the {@code char} value at the
     693      * specified index. An index ranges from {@code 0} to
     694      * {@code length() - 1}. The first {@code char} value of the sequence
     695      * is at index {@code 0}, the next at index {@code 1},
     696      * and so on, as for array indexing.
     697      *
     698      * <p>If the {@code char} value specified by the index is a
     699      * <a href="Character.html#unicode">surrogate</a>, the surrogate
     700      * value is returned.
     701      *
     702      * @param      index   the index of the {@code char} value.
     703      * @return     the {@code char} value at the specified index of this string.
     704      *             The first {@code char} value is at index {@code 0}.
     705      * @throws     IndexOutOfBoundsException  if the {@code index}
     706      *             argument is negative or not less than the length of this
     707      *             string.
     708      */
     709     public char charAt(int index) {
     710         if (isLatin1()) {
     711             return StringLatin1.charAt(value, index);
     712         } else {
     713             return StringUTF16.charAt(value, index);
     714         }
     715     }
     716
     717     /**
     718      * Returns the character (Unicode code point) at the specified
     719      * index. The index refers to {@code char} values
     720      * (Unicode code units) and ranges from {@code 0} to
     721      * {@link #length()}{@code  - 1}.
     722      *
     723      * <p> If the {@code char} value specified at the given index
     724      * is in the high-surrogate range, the following index is less
     725      * than the length of this {@code String}, and the
     726      * {@code char} value at the following index is in the
     727      * low-surrogate range, then the supplementary code point
     728      * corresponding to this surrogate pair is returned. Otherwise,
     729      * the {@code char} value at the given index is returned.
     730      *
     731      * @param      index the index to the {@code char} values
     732      * @return     the code point value of the character at the
     733      *             {@code index}
     734      * @throws     IndexOutOfBoundsException  if the {@code index}
     735      *             argument is negative or not less than the length of this
     736      *             string.
     737      * @since      1.5
     738      */
     739     public int codePointAt(int index) {
     740         if (isLatin1()) {
     741             checkIndex(index, value.length);
     742             return value[index] & 0xff;
     743         }
     744         int length = value.length >> 1;
     745         checkIndex(index, length);
     746         return StringUTF16.codePointAt(value, index, length);
     747     }
     748
     749     /**
     750      * Returns the character (Unicode code point) before the specified
     751      * index. The index refers to {@code char} values
     752      * (Unicode code units) and ranges from {@code 1} to {@link
     753      * CharSequence#length() length}.
     754      *
     755      * <p> If the {@code char} value at {@code (index - 1)}
     756      * is in the low-surrogate range, {@code (index - 2)} is not
     757      * negative, and the {@code char} value at {@code (index -
     758      * 2)} is in the high-surrogate range, then the
     759      * supplementary code point value of the surrogate pair is
     760      * returned. If the {@code char} value at {@code index -
     761      * 1} is an unpaired low-surrogate or a high-surrogate, the
     762      * surrogate value is returned.
     763      *
     764      * @param     index the index following the code point that should be returned
     765      * @return    the Unicode code point value before the given index.
     766      * @throws    IndexOutOfBoundsException if the {@code index}
     767      *            argument is less than 1 or greater than the length
     768      *            of this string.
     769      * @since     1.5
     770      */
     771     public int codePointBefore(int index) {
     772         int i = index - 1;
     773         if (i < 0 || i >= length()) {
     774             throw new StringIndexOutOfBoundsException(index);
     775         }
     776         if (isLatin1()) {
     777             return (value[i] & 0xff);
     778         }
     779         return StringUTF16.codePointBefore(value, index);
     780     }
     781
     782     /**
     783      * Returns the number of Unicode code points in the specified text
     784      * range of this {@code String}. The text range begins at the
     785      * specified {@code beginIndex} and extends to the
     786      * {@code char} at index {@code endIndex - 1}. Thus the
     787      * length (in {@code char}s) of the text range is
     788      * {@code endIndex-beginIndex}. Unpaired surrogates within
     789      * the text range count as one code point each.
     790      *
     791      * @param beginIndex the index to the first {@code char} of
     792      * the text range.
     793      * @param endIndex the index after the last {@code char} of
     794      * the text range.
     795      * @return the number of Unicode code points in the specified text
     796      * range
     797      * @throws    IndexOutOfBoundsException if the
     798      * {@code beginIndex} is negative, or {@code endIndex}
     799      * is larger than the length of this {@code String}, or
     800      * {@code beginIndex} is larger than {@code endIndex}.
     801      * @since  1.5
     802      */
     803     public int codePointCount(int beginIndex, int endIndex) {
     804         if (beginIndex < 0 || beginIndex > endIndex ||
     805             endIndex > length()) {
     806             throw new IndexOutOfBoundsException();
     807         }
     808         if (isLatin1()) {
     809             return endIndex - beginIndex;
     810         }
     811         return StringUTF16.codePointCount(value, beginIndex, endIndex);
     812     }
     813
     814     /**
     815      * Returns the index within this {@code String} that is
     816      * offset from the given {@code index} by
     817      * {@code codePointOffset} code points. Unpaired surrogates
     818      * within the text range given by {@code index} and
     819      * {@code codePointOffset} count as one code point each.
     820      *
     821      * @param index the index to be offset
     822      * @param codePointOffset the offset in code points
     823      * @return the index within this {@code String}
     824      * @throws    IndexOutOfBoundsException if {@code index}
     825      *   is negative or larger then the length of this
     826      *   {@code String}, or if {@code codePointOffset} is positive
     827      *   and the substring starting with {@code index} has fewer
     828      *   than {@code codePointOffset} code points,
     829      *   or if {@code codePointOffset} is negative and the substring
     830      *   before {@code index} has fewer than the absolute value
     831      *   of {@code codePointOffset} code points.
     832      * @since 1.5
     833      */
     834     public int offsetByCodePoints(int index, int codePointOffset) {
     835         if (index < 0 || index > length()) {
     836             throw new IndexOutOfBoundsException();
     837         }
     838         return Character.offsetByCodePoints(this, index, codePointOffset);
     839     }
     840
     841     /**
     842      * Copies characters from this string into the destination character
     843      * array.
     844      * <p>
     845      * The first character to be copied is at index {@code srcBegin};
     846      * the last character to be copied is at index {@code srcEnd-1}
     847      * (thus the total number of characters to be copied is
     848      * {@code srcEnd-srcBegin}). The characters are copied into the
     849      * subarray of {@code dst} starting at index {@code dstBegin}
     850      * and ending at index:
     851      * <blockquote><pre>
     852      *     dstBegin + (srcEnd-srcBegin) - 1
     853      * </pre></blockquote>
     854      *
     855      * @param      srcBegin   index of the first character in the string
     856      *                        to copy.
     857      * @param      srcEnd     index after the last character in the string
     858      *                        to copy.
     859      * @param      dst        the destination array.
     860      * @param      dstBegin   the start offset in the destination array.
     861      * @throws    IndexOutOfBoundsException If any of the following
     862      *            is true:
     863      *            <ul><li>{@code srcBegin} is negative.
     864      *            <li>{@code srcBegin} is greater than {@code srcEnd}
     865      *            <li>{@code srcEnd} is greater than the length of this
     866      *                string
     867      *            <li>{@code dstBegin} is negative
     868      *            <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
     869      *                {@code dst.length}</ul>
     870      */
     871     public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
     872         checkBoundsBeginEnd(srcBegin, srcEnd, length());
     873         checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
     874         if (isLatin1()) {
     875             StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
     876         } else {
     877             StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
     878         }
     879     }
     880
     881     /**
     882      * Copies characters from this string into the destination byte array. Each
     883      * byte receives the 8 low-order bits of the corresponding character. The
     884      * eight high-order bits of each character are not copied and do not
     885      * participate in the transfer in any way.
     886      *
     887      * <p> The first character to be copied is at index {@code srcBegin}; the
     888      * last character to be copied is at index {@code srcEnd-1}.  The total
     889      * number of characters to be copied is {@code srcEnd-srcBegin}. The
     890      * characters, converted to bytes, are copied into the subarray of {@code
     891      * dst} starting at index {@code dstBegin} and ending at index:
     892      *
     893      * <blockquote><pre>
     894      *     dstBegin + (srcEnd-srcBegin) - 1
     895      * </pre></blockquote>
     896      *
     897      * @deprecated  This method does not properly convert characters into
     898      * bytes.  As of JDK&nbsp;1.1, the preferred way to do this is via the
     899      * {@link #getBytes()} method, which uses the platform's default charset.
     900      *
     901      * @param  srcBegin
     902      *         Index of the first character in the string to copy
     903      *
     904      * @param  srcEnd
     905      *         Index after the last character in the string to copy
     906      *
     907      * @param  dst
     908      *         The destination array
     909      *
     910      * @param  dstBegin
     911      *         The start offset in the destination array
     912      *
     913      * @throws  IndexOutOfBoundsException
     914      *          If any of the following is true:
     915      *          <ul>
     916      *            <li> {@code srcBegin} is negative
     917      *            <li> {@code srcBegin} is greater than {@code srcEnd}
     918      *            <li> {@code srcEnd} is greater than the length of this String
     919      *            <li> {@code dstBegin} is negative
     920      *            <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
     921      *                 dst.length}
     922      *          </ul>
     923      */
     924     @Deprecated(since="1.1")
     925     public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
     926         checkBoundsBeginEnd(srcBegin, srcEnd, length());
     927         Objects.requireNonNull(dst);
     928         checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
     929         if (isLatin1()) {
     930             StringLatin1.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
     931         } else {
     932             StringUTF16.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
     933         }
     934     }
     935
     936     /**
     937      * Encodes this {@code String} into a sequence of bytes using the named
     938      * charset, storing the result into a new byte array.
     939      *
     940      * <p> The behavior of this method when this string cannot be encoded in
     941      * the given charset is unspecified.  The {@link
     942      * java.nio.charset.CharsetEncoder} class should be used when more control
     943      * over the encoding process is required.
     944      *
     945      * @param  charsetName
     946      *         The name of a supported {@linkplain java.nio.charset.Charset
     947      *         charset}
     948      *
     949      * @return  The resultant byte array
     950      *
     951      * @throws  UnsupportedEncodingException
     952      *          If the named charset is not supported
     953      *
     954      * @since  1.1
     955      */
     956     public byte[] getBytes(String charsetName)
     957             throws UnsupportedEncodingException {
     958         if (charsetName == null) throw new NullPointerException();
     959         return StringCoding.encode(charsetName, coder(), value);
     960     }
     961
     962     /**
     963      * Encodes this {@code String} into a sequence of bytes using the given
     964      * {@linkplain java.nio.charset.Charset charset}, storing the result into a
     965      * new byte array.
     966      *
     967      * <p> This method always replaces malformed-input and unmappable-character
     968      * sequences with this charset's default replacement byte array.  The
     969      * {@link java.nio.charset.CharsetEncoder} class should be used when more
     970      * control over the encoding process is required.
     971      *
     972      * @param  charset
     973      *         The {@linkplain java.nio.charset.Charset} to be used to encode
     974      *         the {@code String}
     975      *
     976      * @return  The resultant byte array
     977      *
     978      * @since  1.6
     979      */
     980     public byte[] getBytes(Charset charset) {
     981         if (charset == null) throw new NullPointerException();
     982         return StringCoding.encode(charset, coder(), value);
     983      }
     984
     985     /**
     986      * Encodes this {@code String} into a sequence of bytes using the
     987      * platform's default charset, storing the result into a new byte array.
     988      *
     989      * <p> The behavior of this method when this string cannot be encoded in
     990      * the default charset is unspecified.  The {@link
     991      * java.nio.charset.CharsetEncoder} class should be used when more control
     992      * over the encoding process is required.
     993      *
     994      * @return  The resultant byte array
     995      *
     996      * @since      1.1
     997      */
     998     public byte[] getBytes() {
     999         return StringCoding.encode(coder(), value);
    1000     }
    1001
    1002     /**
    1003      * Compares this string to the specified object.  The result is {@code
    1004      * true} if and only if the argument is not {@code null} and is a {@code
    1005      * String} object that represents the same sequence of characters as this
    1006      * object.
    1007      *
    1008      * <p>For finer-grained String comparison, refer to
    1009      * {@link java.text.Collator}.
    1010      *
    1011      * @param  anObject
    1012      *         The object to compare this {@code String} against
    1013      *
    1014      * @return  {@code true} if the given object represents a {@code String}
    1015      *          equivalent to this string, {@code false} otherwise
    1016      *
    1017      * @see  #compareTo(String)
    1018      * @see  #equalsIgnoreCase(String)
    1019      */
    1020     public boolean equals(Object anObject) {
    1021         if (this == anObject) {
    1022             return true;
    1023         }
    1024         if (anObject instanceof String) {
    1025             String aString = (String)anObject;
    1026             if (!COMPACT_STRINGS || this.coder == aString.coder) {
    1027                 return StringLatin1.equals(value, aString.value);
    1028             }
    1029         }
    1030         return false;
    1031     }
    1032
    1033     /**
    1034      * Compares this string to the specified {@code StringBuffer}.  The result
    1035      * is {@code true} if and only if this {@code String} represents the same
    1036      * sequence of characters as the specified {@code StringBuffer}. This method
    1037      * synchronizes on the {@code StringBuffer}.
    1038      *
    1039      * <p>For finer-grained String comparison, refer to
    1040      * {@link java.text.Collator}.
    1041      *
    1042      * @param  sb
    1043      *         The {@code StringBuffer} to compare this {@code String} against
    1044      *
    1045      * @return  {@code true} if this {@code String} represents the same
    1046      *          sequence of characters as the specified {@code StringBuffer},
    1047      *          {@code false} otherwise
    1048      *
    1049      * @since  1.4
    1050      */
    1051     public boolean contentEquals(StringBuffer sb) {
    1052         return contentEquals((CharSequence)sb);
    1053     }
    1054
    1055     private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
    1056         int len = length();
    1057         if (len != sb.length()) {
    1058             return false;
    1059         }
    1060         byte v1[] = value;
    1061         byte v2[] = sb.getValue();
    1062         byte coder = coder();
    1063         if (coder == sb.getCoder()) {
    1064             int n = v1.length;
    1065             for (int i = 0; i < n; i++) {
    1066                 if (v1[i] != v2[i]) {
    1067                     return false;
    1068                 }
    1069             }
    1070         } else {
    1071             if (coder != LATIN1) {  // utf16 str and latin1 abs can never be "equal"
    1072                 return false;
    1073             }
    1074             return StringUTF16.contentEquals(v1, v2, len);
    1075         }
    1076         return true;
    1077     }
    1078
    1079     /**
    1080      * Compares this string to the specified {@code CharSequence}.  The
    1081      * result is {@code true} if and only if this {@code String} represents the
    1082      * same sequence of char values as the specified sequence. Note that if the
    1083      * {@code CharSequence} is a {@code StringBuffer} then the method
    1084      * synchronizes on it.
    1085      *
    1086      * <p>For finer-grained String comparison, refer to
    1087      * {@link java.text.Collator}.
    1088      *
    1089      * @param  cs
    1090      *         The sequence to compare this {@code String} against
    1091      *
    1092      * @return  {@code true} if this {@code String} represents the same
    1093      *          sequence of char values as the specified sequence, {@code
    1094      *          false} otherwise
    1095      *
    1096      * @since  1.5
    1097      */
    1098     public boolean contentEquals(CharSequence cs) {
    1099         // Argument is a StringBuffer, StringBuilder
    1100         if (cs instanceof AbstractStringBuilder) {
    1101             if (cs instanceof StringBuffer) {
    1102                 synchronized(cs) {
    1103                    return nonSyncContentEquals((AbstractStringBuilder)cs);
    1104                 }
    1105             } else {
    1106                 return nonSyncContentEquals((AbstractStringBuilder)cs);
    1107             }
    1108         }
    1109         // Argument is a String
    1110         if (cs instanceof String) {
    1111             return equals(cs);
    1112         }
    1113         // Argument is a generic CharSequence
    1114         int n = cs.length();
    1115         if (n != length()) {
    1116             return false;
    1117         }
    1118         byte[] val = this.value;
    1119         if (isLatin1()) {
    1120             for (int i = 0; i < n; i++) {
    1121                 if ((val[i] & 0xff) != cs.charAt(i)) {
    1122                     return false;
    1123                 }
    1124             }
    1125         } else {
    1126             if (!StringUTF16.contentEquals(val, cs, n)) {
    1127                 return false;
    1128             }
    1129         }
    1130         return true;
    1131     }
    1132
    1133     /**
    1134      * Compares this {@code String} to another {@code String}, ignoring case
    1135      * considerations.  Two strings are considered equal ignoring case if they
    1136      * are of the same length and corresponding Unicode code points in the two
    1137      * strings are equal ignoring case.
    1138      *
    1139      * <p> Two Unicode code points are considered the same
    1140      * ignoring case if at least one of the following is true:
    1141      * <ul>
    1142      *   <li> The two Unicode code points are the same (as compared by the
    1143      *        {@code ==} operator)
    1144      *   <li> Calling {@code Character.toLowerCase(Character.toUpperCase(int))}
    1145      *        on each Unicode code point produces the same result
    1146      * </ul>
    1147      *
    1148      * <p>Note that this method does <em>not</em> take locale into account, and
    1149      * will result in unsatisfactory results for certain locales.  The
    1150      * {@link java.text.Collator} class provides locale-sensitive comparison.
    1151      *
    1152      * @param  anotherString
    1153      *         The {@code String} to compare this {@code String} against
    1154      *
    1155      * @return  {@code true} if the argument is not {@code null} and it
    1156      *          represents an equivalent {@code String} ignoring case; {@code
    1157      *          false} otherwise
    1158      *
    1159      * @see  #equals(Object)
    1160      * @see  #codePoints()
    1161      */
    1162     public boolean equalsIgnoreCase(String anotherString) {
    1163         return (this == anotherString) ? true
    1164                 : (anotherString != null)
    1165                 && (anotherString.length() == length())
    1166                 && regionMatches(true, 0, anotherString, 0, length());
    1167     }
    1168
    1169     /**
    1170      * Compares two strings lexicographically.
    1171      * The comparison is based on the Unicode value of each character in
    1172      * the strings. The character sequence represented by this
    1173      * {@code String} object is compared lexicographically to the
    1174      * character sequence represented by the argument string. The result is
    1175      * a negative integer if this {@code String} object
    1176      * lexicographically precedes the argument string. The result is a
    1177      * positive integer if this {@code String} object lexicographically
    1178      * follows the argument string. The result is zero if the strings
    1179      * are equal; {@code compareTo} returns {@code 0} exactly when
    1180      * the {@link #equals(Object)} method would return {@code true}.
    1181      * <p>
    1182      * This is the definition of lexicographic ordering. If two strings are
    1183      * different, then either they have different characters at some index
    1184      * that is a valid index for both strings, or their lengths are different,
    1185      * or both. If they have different characters at one or more index
    1186      * positions, let <i>k</i> be the smallest such index; then the string
    1187      * whose character at position <i>k</i> has the smaller value, as
    1188      * determined by using the {@code <} operator, lexicographically precedes the
    1189      * other string. In this case, {@code compareTo} returns the
    1190      * difference of the two character values at position {@code k} in
    1191      * the two string -- that is, the value:
    1192      * <blockquote><pre>
    1193      * this.charAt(k)-anotherString.charAt(k)
    1194      * </pre></blockquote>
    1195      * If there is no index position at which they differ, then the shorter
    1196      * string lexicographically precedes the longer string. In this case,
    1197      * {@code compareTo} returns the difference of the lengths of the
    1198      * strings -- that is, the value:
    1199      * <blockquote><pre>
    1200      * this.length()-anotherString.length()
    1201      * </pre></blockquote>
    1202      *
    1203      * <p>For finer-grained String comparison, refer to
    1204      * {@link java.text.Collator}.
    1205      *
    1206      * @param   anotherString   the {@code String} to be compared.
    1207      * @return  the value {@code 0} if the argument string is equal to
    1208      *          this string; a value less than {@code 0} if this string
    1209      *          is lexicographically less than the string argument; and a
    1210      *          value greater than {@code 0} if this string is
    1211      *          lexicographically greater than the string argument.
    1212      */
    1213     public int compareTo(String anotherString) {
    1214         byte v1[] = value;
    1215         byte v2[] = anotherString.value;
    1216         byte coder = coder();
    1217         if (coder == anotherString.coder()) {
    1218             return coder == LATIN1 ? StringLatin1.compareTo(v1, v2)
    1219                                    : StringUTF16.compareTo(v1, v2);
    1220         }
    1221         return coder == LATIN1 ? StringLatin1.compareToUTF16(v1, v2)
    1222                                : StringUTF16.compareToLatin1(v1, v2);
    1223      }
    1224
    1225     /**
    1226      * A Comparator that orders {@code String} objects as by
    1227      * {@link #compareToIgnoreCase(String) compareToIgnoreCase}.
    1228      * This comparator is serializable.
    1229      * <p>
    1230      * Note that this Comparator does <em>not</em> take locale into account,
    1231      * and will result in an unsatisfactory ordering for certain locales.
    1232      * The {@link java.text.Collator} class provides locale-sensitive comparison.
    1233      *
    1234      * @see     java.text.Collator
    1235      * @since   1.2
    1236      */
    1237     public static final Comparator<String> CASE_INSENSITIVE_ORDER
    1238                                          = new CaseInsensitiveComparator();
    1239     private static class CaseInsensitiveComparator
    1240             implements Comparator<String>, java.io.Serializable {
    1241         // use serialVersionUID from JDK 1.2.2 for interoperability
    1242         @java.io.Serial
    1243         private static final long serialVersionUID = 8575799808933029326L;
    1244
    1245         public int compare(String s1, String s2) {
    1246             byte v1[] = s1.value;
    1247             byte v2[] = s2.value;
    1248             byte coder = s1.coder();
    1249             if (coder == s2.coder()) {
    1250                 return coder == LATIN1 ? StringLatin1.compareToCI(v1, v2)
    1251                                        : StringUTF16.compareToCI(v1, v2);
    1252             }
    1253             return coder == LATIN1 ? StringLatin1.compareToCI_UTF16(v1, v2)
    1254                                    : StringUTF16.compareToCI_Latin1(v1, v2);
    1255         }
    1256
    1257         /** Replaces the de-serialized object. */
    1258         @java.io.Serial
    1259         private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
    1260     }
    1261
    1262     /**
    1263      * Compares two strings lexicographically, ignoring case
    1264      * differences. This method returns an integer whose sign is that of
    1265      * calling {@code compareTo} with case folded versions of the strings
    1266      * where case differences have been eliminated by calling
    1267      * {@code Character.toLowerCase(Character.toUpperCase(int))} on
    1268      * each Unicode code point.
    1269      * <p>
    1270      * Note that this method does <em>not</em> take locale into account,
    1271      * and will result in an unsatisfactory ordering for certain locales.
    1272      * The {@link java.text.Collator} class provides locale-sensitive comparison.
    1273      *
    1274      * @param   str   the {@code String} to be compared.
    1275      * @return  a negative integer, zero, or a positive integer as the
    1276      *          specified String is greater than, equal to, or less
    1277      *          than this String, ignoring case considerations.
    1278      * @see     java.text.Collator
    1279      * @see     #codePoints()
    1280      * @since   1.2
    1281      */
    1282     public int compareToIgnoreCase(String str) {
    1283         return CASE_INSENSITIVE_ORDER.compare(this, str);
    1284     }
    1285
    1286     /**
    1287      * Tests if two string regions are equal.
    1288      * <p>
    1289      * A substring of this {@code String} object is compared to a substring
    1290      * of the argument other. The result is true if these substrings
    1291      * represent identical character sequences. The substring of this
    1292      * {@code String} object to be compared begins at index {@code toffset}
    1293      * and has length {@code len}. The substring of other to be compared
    1294      * begins at index {@code ooffset} and has length {@code len}. The
    1295      * result is {@code false} if and only if at least one of the following
    1296      * is true:
    1297      * <ul><li>{@code toffset} is negative.
    1298      * <li>{@code ooffset} is negative.
    1299      * <li>{@code toffset+len} is greater than the length of this
    1300      * {@code String} object.
    1301      * <li>{@code ooffset+len} is greater than the length of the other
    1302      * argument.
    1303      * <li>There is some nonnegative integer <i>k</i> less than {@code len}
    1304      * such that:
    1305      * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
    1306      * <i>k</i>{@code )}
    1307      * </ul>
    1308      *
    1309      * <p>Note that this method does <em>not</em> take locale into account.  The
    1310      * {@link java.text.Collator} class provides locale-sensitive comparison.
    1311      *
    1312      * @param   toffset   the starting offset of the subregion in this string.
    1313      * @param   other     the string argument.
    1314      * @param   ooffset   the starting offset of the subregion in the string
    1315      *                    argument.
    1316      * @param   len       the number of characters to compare.
    1317      * @return  {@code true} if the specified subregion of this string
    1318      *          exactly matches the specified subregion of the string argument;
    1319      *          {@code false} otherwise.
    1320      */
    1321     public boolean regionMatches(int toffset, String other, int ooffset, int len) {
    1322         byte tv[] = value;
    1323         byte ov[] = other.value;
    1324         // Note: toffset, ooffset, or len might be near -1>>>1.
    1325         if ((ooffset < 0) || (toffset < 0) ||
    1326              (toffset > (long)length() - len) ||
    1327              (ooffset > (long)other.length() - len)) {
    1328             return false;
    1329         }
    1330         byte coder = coder();
    1331         if (coder == other.coder()) {
    1332             if (!isLatin1() && (len > 0)) {
    1333                 toffset = toffset << 1;
    1334                 ooffset = ooffset << 1;
    1335                 len = len << 1;
    1336             }
    1337             while (len-- > 0) {
    1338                 if (tv[toffset++] != ov[ooffset++]) {
    1339                     return false;
    1340                 }
    1341             }
    1342         } else {
    1343             if (coder == LATIN1) {
    1344                 while (len-- > 0) {
    1345                     if (StringLatin1.getChar(tv, toffset++) !=
    1346                         StringUTF16.getChar(ov, ooffset++)) {
    1347                         return false;
    1348                     }
    1349                 }
    1350             } else {
    1351                 while (len-- > 0) {
    1352                     if (StringUTF16.getChar(tv, toffset++) !=
    1353                         StringLatin1.getChar(ov, ooffset++)) {
    1354                         return false;
    1355                     }
    1356                 }
    1357             }
    1358         }
    1359         return true;
    1360     }
    1361
    1362     /**
    1363      * Tests if two string regions are equal.
    1364      * <p>
    1365      * A substring of this {@code String} object is compared to a substring
    1366      * of the argument {@code other}. The result is {@code true} if these
    1367      * substrings represent Unicode code point sequences that are the same,
    1368      * ignoring case if and only if {@code ignoreCase} is true.
    1369      * The sequences {@code tsequence} and {@code osequence} are compared,
    1370      * where {@code tsequence} is the sequence produced as if by calling
    1371      * {@code this.substring(toffset, len).codePoints()} and {@code osequence}
    1372      * is the sequence produced as if by calling
    1373      * {@code other.substring(ooffset, len).codePoints()}.
    1374      * The result is {@code true} if and only if all of the following
    1375      * are true:
    1376      * <ul><li>{@code toffset} is non-negative.
    1377      * <li>{@code ooffset} is non-negative.
    1378      * <li>{@code toffset+len} is less than or equal to the length of this
    1379      * {@code String} object.
    1380      * <li>{@code ooffset+len} is less than or equal to the length of the other
    1381      * argument.
    1382      * <li>if {@code ignoreCase} is {@code false}, all pairs of corresponding Unicode
    1383      * code points are equal integer values; or if {@code ignoreCase} is {@code true},
    1384      * {@link Character#toLowerCase(int) Character.toLowerCase(}
    1385      * {@link Character#toUpperCase(int)}{@code )} on all pairs of Unicode code points
    1386      * results in equal integer values.
    1387      * </ul>
    1388      *
    1389      * <p>Note that this method does <em>not</em> take locale into account,
    1390      * and will result in unsatisfactory results for certain locales when
    1391      * {@code ignoreCase} is {@code true}.  The {@link java.text.Collator} class
    1392      * provides locale-sensitive comparison.
    1393      *
    1394      * @param   ignoreCase   if {@code true}, ignore case when comparing
    1395      *                       characters.
    1396      * @param   toffset      the starting offset of the subregion in this
    1397      *                       string.
    1398      * @param   other        the string argument.
    1399      * @param   ooffset      the starting offset of the subregion in the string
    1400      *                       argument.
    1401      * @param   len          the number of characters (Unicode code units -
    1402      *                       16bit {@code char} value) to compare.
    1403      * @return  {@code true} if the specified subregion of this string
    1404      *          matches the specified subregion of the string argument;
    1405      *          {@code false} otherwise. Whether the matching is exact
    1406      *          or case insensitive depends on the {@code ignoreCase}
    1407      *          argument.
    1408      * @see     #codePoints()
    1409      */
    1410     public boolean regionMatches(boolean ignoreCase, int toffset,
    1411             String other, int ooffset, int len) {
    1412         if (!ignoreCase) {
    1413             return regionMatches(toffset, other, ooffset, len);
    1414         }
    1415         // Note: toffset, ooffset, or len might be near -1>>>1.
    1416         if ((ooffset < 0) || (toffset < 0)
    1417                 || (toffset > (long)length() - len)
    1418                 || (ooffset > (long)other.length() - len)) {
    1419             return false;
    1420         }
    1421         byte tv[] = value;
    1422         byte ov[] = other.value;
    1423         byte coder = coder();
    1424         if (coder == other.coder()) {
    1425             return coder == LATIN1
    1426               ? StringLatin1.regionMatchesCI(tv, toffset, ov, ooffset, len)
    1427               : StringUTF16.regionMatchesCI(tv, toffset, ov, ooffset, len);
    1428         }
    1429         return coder == LATIN1
    1430               ? StringLatin1.regionMatchesCI_UTF16(tv, toffset, ov, ooffset, len)
    1431               : StringUTF16.regionMatchesCI_Latin1(tv, toffset, ov, ooffset, len);
    1432     }
    1433
    1434     /**
    1435      * Tests if the substring of this string beginning at the
    1436      * specified index starts with the specified prefix.
    1437      *
    1438      * @param   prefix    the prefix.
    1439      * @param   toffset   where to begin looking in this string.
    1440      * @return  {@code true} if the character sequence represented by the
    1441      *          argument is a prefix of the substring of this object starting
    1442      *          at index {@code toffset}; {@code false} otherwise.
    1443      *          The result is {@code false} if {@code toffset} is
    1444      *          negative or greater than the length of this
    1445      *          {@code String} object; otherwise the result is the same
    1446      *          as the result of the expression
    1447      *          <pre>
    1448      *          this.substring(toffset).startsWith(prefix)
    1449      *          </pre>
    1450      */
    1451     public boolean startsWith(String prefix, int toffset) {
    1452         // Note: toffset might be near -1>>>1.
    1453         if (toffset < 0 || toffset > length() - prefix.length()) {
    1454             return false;
    1455         }
    1456         byte ta[] = value;
    1457         byte pa[] = prefix.value;
    1458         int po = 0;
    1459         int pc = pa.length;
    1460         byte coder = coder();
    1461         if (coder == prefix.coder()) {
    1462             int to = (coder == LATIN1) ? toffset : toffset << 1;
    1463             while (po < pc) {
    1464                 if (ta[to++] != pa[po++]) {
    1465                     return false;
    1466                 }
    1467             }
    1468         } else {
    1469             if (coder == LATIN1) {  // && pcoder == UTF16
    1470                 return false;
    1471             }
    1472             // coder == UTF16 && pcoder == LATIN1)
    1473             while (po < pc) {
    1474                 if (StringUTF16.getChar(ta, toffset++) != (pa[po++] & 0xff)) {
    1475                     return false;
    1476                }
    1477             }
    1478         }
    1479         return true;
    1480     }
    1481
    1482     /**
    1483      * Tests if this string starts with the specified prefix.
    1484      *
    1485      * @param   prefix   the prefix.
    1486      * @return  {@code true} if the character sequence represented by the
    1487      *          argument is a prefix of the character sequence represented by
    1488      *          this string; {@code false} otherwise.
    1489      *          Note also that {@code true} will be returned if the
    1490      *          argument is an empty string or is equal to this
    1491      *          {@code String} object as determined by the
    1492      *          {@link #equals(Object)} method.
    1493      * @since   1.0
    1494      */
    1495     public boolean startsWith(String prefix) {
    1496         return startsWith(prefix, 0);
    1497     }
    1498
    1499     /**
    1500      * Tests if this string ends with the specified suffix.
    1501      *
    1502      * @param   suffix   the suffix.
    1503      * @return  {@code true} if the character sequence represented by the
    1504      *          argument is a suffix of the character sequence represented by
    1505      *          this object; {@code false} otherwise. Note that the
    1506      *          result will be {@code true} if the argument is the
    1507      *          empty string or is equal to this {@code String} object
    1508      *          as determined by the {@link #equals(Object)} method.
    1509      */
    1510     public boolean endsWith(String suffix) {
    1511         return startsWith(suffix, length() - suffix.length());
    1512     }
    1513
    1514     /**
    1515      * Returns a hash code for this string. The hash code for a
    1516      * {@code String} object is computed as
    1517      * <blockquote><pre>
    1518      * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
    1519      * </pre></blockquote>
    1520      * using {@code int} arithmetic, where {@code s[i]} is the
    1521      * <i>i</i>th character of the string, {@code n} is the length of
    1522      * the string, and {@code ^} indicates exponentiation.
    1523      * (The hash value of the empty string is zero.)
    1524      *
    1525      * @return  a hash code value for this object.
    1526      */
    1527     public int hashCode() {
    1528         // The hash or hashIsZero fields are subject to a benign data race,
    1529         // making it crucial to ensure that any observable result of the
    1530         // calculation in this method stays correct under any possible read of
    1531         // these fields. Necessary restrictions to allow this to be correct
    1532         // without explicit memory fences or similar concurrency primitives is
    1533         // that we can ever only write to one of these two fields for a given
    1534         // String instance, and that the computation is idempotent and derived
    1535         // from immutable state
    1536         int h = hash;
    1537         if (h == 0 && !hashIsZero) {
    1538             h = isLatin1() ? StringLatin1.hashCode(value)
    1539                            : StringUTF16.hashCode(value);
    1540             if (h == 0) {
    1541                 hashIsZero = true;
    1542             } else {
    1543                 hash = h;
    1544             }
    1545         }
    1546         return h;
    1547     }
    1548
    1549     /**
    1550      * Returns the index within this string of the first occurrence of
    1551      * the specified character. If a character with value
    1552      * {@code ch} occurs in the character sequence represented by
    1553      * this {@code String} object, then the index (in Unicode
    1554      * code units) of the first such occurrence is returned. For
    1555      * values of {@code ch} in the range from 0 to 0xFFFF
    1556      * (inclusive), this is the smallest value <i>k</i> such that:
    1557      * <blockquote><pre>
    1558      * this.charAt(<i>k</i>) == ch
    1559      * </pre></blockquote>
    1560      * is true. For other values of {@code ch}, it is the
    1561      * smallest value <i>k</i> such that:
    1562      * <blockquote><pre>
    1563      * this.codePointAt(<i>k</i>) == ch
    1564      * </pre></blockquote>
    1565      * is true. In either case, if no such character occurs in this
    1566      * string, then {@code -1} is returned.
    1567      *
    1568      * @param   ch   a character (Unicode code point).
    1569      * @return  the index of the first occurrence of the character in the
    1570      *          character sequence represented by this object, or
    1571      *          {@code -1} if the character does not occur.
    1572      */
    1573     public int indexOf(int ch) {
    1574         return indexOf(ch, 0);
    1575     }
    1576
    1577     /**
    1578      * Returns the index within this string of the first occurrence of the
    1579      * specified character, starting the search at the specified index.
    1580      * <p>
    1581      * If a character with value {@code ch} occurs in the
    1582      * character sequence represented by this {@code String}
    1583      * object at an index no smaller than {@code fromIndex}, then
    1584      * the index of the first such occurrence is returned. For values
    1585      * of {@code ch} in the range from 0 to 0xFFFF (inclusive),
    1586      * this is the smallest value <i>k</i> such that:
    1587      * <blockquote><pre>
    1588      * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex)
    1589      * </pre></blockquote>
    1590      * is true. For other values of {@code ch}, it is the
    1591      * smallest value <i>k</i> such that:
    1592      * <blockquote><pre>
    1593      * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex)
    1594      * </pre></blockquote>
    1595      * is true. In either case, if no such character occurs in this
    1596      * string at or after position {@code fromIndex}, then
    1597      * {@code -1} is returned.
    1598      *
    1599      * <p>
    1600      * There is no restriction on the value of {@code fromIndex}. If it
    1601      * is negative, it has the same effect as if it were zero: this entire
    1602      * string may be searched. If it is greater than the length of this
    1603      * string, it has the same effect as if it were equal to the length of
    1604      * this string: {@code -1} is returned.
    1605      *
    1606      * <p>All indices are specified in {@code char} values
    1607      * (Unicode code units).
    1608      *
    1609      * @param   ch          a character (Unicode code point).
    1610      * @param   fromIndex   the index to start the search from.
    1611      * @return  the index of the first occurrence of the character in the
    1612      *          character sequence represented by this object that is greater
    1613      *          than or equal to {@code fromIndex}, or {@code -1}
    1614      *          if the character does not occur.
    1615      */
    1616     public int indexOf(int ch, int fromIndex) {
    1617         return isLatin1() ? StringLatin1.indexOf(value, ch, fromIndex)
    1618                           : StringUTF16.indexOf(value, ch, fromIndex);
    1619     }
    1620
    1621     /**
    1622      * Returns the index within this string of the last occurrence of
    1623      * the specified character. For values of {@code ch} in the
    1624      * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
    1625      * units) returned is the largest value <i>k</i> such that:
    1626      * <blockquote><pre>
    1627      * this.charAt(<i>k</i>) == ch
    1628      * </pre></blockquote>
    1629      * is true. For other values of {@code ch}, it is the
    1630      * largest value <i>k</i> such that:
    1631      * <blockquote><pre>
    1632      * this.codePointAt(<i>k</i>) == ch
    1633      * </pre></blockquote>
    1634      * is true.  In either case, if no such character occurs in this
    1635      * string, then {@code -1} is returned.  The
    1636      * {@code String} is searched backwards starting at the last
    1637      * character.
    1638      *
    1639      * @param   ch   a character (Unicode code point).
    1640      * @return  the index of the last occurrence of the character in the
    1641      *          character sequence represented by this object, or
    1642      *          {@code -1} if the character does not occur.
    1643      */
    1644     public int lastIndexOf(int ch) {
    1645         return lastIndexOf(ch, length() - 1);
    1646     }
    1647
    1648     /**
    1649      * Returns the index within this string of the last occurrence of
    1650      * the specified character, searching backward starting at the
    1651      * specified index. For values of {@code ch} in the range
    1652      * from 0 to 0xFFFF (inclusive), the index returned is the largest
    1653      * value <i>k</i> such that:
    1654      * <blockquote><pre>
    1655      * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex)
    1656      * </pre></blockquote>
    1657      * is true. For other values of {@code ch}, it is the
    1658      * largest value <i>k</i> such that:
    1659      * <blockquote><pre>
    1660      * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex)
    1661      * </pre></blockquote>
    1662      * is true. In either case, if no such character occurs in this
    1663      * string at or before position {@code fromIndex}, then
    1664      * {@code -1} is returned.
    1665      *
    1666      * <p>All indices are specified in {@code char} values
    1667      * (Unicode code units).
    1668      *
    1669      * @param   ch          a character (Unicode code point).
    1670      * @param   fromIndex   the index to start the search from. There is no
    1671      *          restriction on the value of {@code fromIndex}. If it is
    1672      *          greater than or equal to the length of this string, it has
    1673      *          the same effect as if it were equal to one less than the
    1674      *          length of this string: this entire string may be searched.
    1675      *          If it is negative, it has the same effect as if it were -1:
    1676      *          -1 is returned.
    1677      * @return  the index of the last occurrence of the character in the
    1678      *          character sequence represented by this object that is less
    1679      *          than or equal to {@code fromIndex}, or {@code -1}
    1680      *          if the character does not occur before that point.
    1681      */
    1682     public int lastIndexOf(int ch, int fromIndex) {
    1683         return isLatin1() ? StringLatin1.lastIndexOf(value, ch, fromIndex)
    1684                           : StringUTF16.lastIndexOf(value, ch, fromIndex);
    1685     }
    1686
    1687     /**
    1688      * Returns the index within this string of the first occurrence of the
    1689      * specified substring.
    1690      *
    1691      * <p>The returned index is the smallest value {@code k} for which:
    1692      * <pre>{@code
    1693      * this.startsWith(str, k)
    1694      * }</pre>
    1695      * If no such value of {@code k} exists, then {@code -1} is returned.
    1696      *
    1697      * @param   str   the substring to search for.
    1698      * @return  the index of the first occurrence of the specified substring,
    1699      *          or {@code -1} if there is no such occurrence.
    1700      */
    1701     public int indexOf(String str) {
    1702         byte coder = coder();
    1703         if (coder == str.coder()) {
    1704             return isLatin1() ? StringLatin1.indexOf(value, str.value)
    1705                               : StringUTF16.indexOf(value, str.value);
    1706         }
    1707         if (coder == LATIN1) {  // str.coder == UTF16
    1708             return -1;
    1709         }
    1710         return StringUTF16.indexOfLatin1(value, str.value);
    1711     }
    1712
    1713     /**
    1714      * Returns the index within this string of the first occurrence of the
    1715      * specified substring, starting at the specified index.
    1716      *
    1717      * <p>The returned index is the smallest value {@code k} for which:
    1718      * <pre>{@code
    1719      *     k >= Math.min(fromIndex, this.length()) &&
    1720      *                   this.startsWith(str, k)
    1721      * }</pre>
    1722      * If no such value of {@code k} exists, then {@code -1} is returned.
    1723      *
    1724      * @param   str         the substring to search for.
    1725      * @param   fromIndex   the index from which to start the search.
    1726      * @return  the index of the first occurrence of the specified substring,
    1727      *          starting at the specified index,
    1728      *          or {@code -1} if there is no such occurrence.
    1729      */
    1730     public int indexOf(String str, int fromIndex) {
    1731         return indexOf(value, coder(), length(), str, fromIndex);
    1732     }
    1733
    1734     /**
    1735      * Code shared by String and AbstractStringBuilder to do searches. The
    1736      * source is the character array being searched, and the target
    1737      * is the string being searched for.
    1738      *
    1739      * @param   src       the characters being searched.
    1740      * @param   srcCoder  the coder of the source string.
    1741      * @param   srcCount  length of the source string.
    1742      * @param   tgtStr    the characters being searched for.
    1743      * @param   fromIndex the index to begin searching from.
    1744      */
    1745     static int indexOf(byte[] src, byte srcCoder, int srcCount,
    1746                        String tgtStr, int fromIndex) {
    1747         byte[] tgt    = tgtStr.value;
    1748         byte tgtCoder = tgtStr.coder();
    1749         int tgtCount  = tgtStr.length();
    1750
    1751         if (fromIndex >= srcCount) {
    1752             return (tgtCount == 0 ? srcCount : -1);
    1753         }
    1754         if (fromIndex < 0) {
    1755             fromIndex = 0;
    1756         }
    1757         if (tgtCount == 0) {
    1758             return fromIndex;
    1759         }
    1760         if (tgtCount > srcCount) {
    1761             return -1;
    1762         }
    1763         if (srcCoder == tgtCoder) {
    1764             return srcCoder == LATIN1
    1765                 ? StringLatin1.indexOf(src, srcCount, tgt, tgtCount, fromIndex)
    1766                 : StringUTF16.indexOf(src, srcCount, tgt, tgtCount, fromIndex);
    1767         }
    1768         if (srcCoder == LATIN1) {    //  && tgtCoder == UTF16
    1769             return -1;
    1770         }
    1771         // srcCoder == UTF16 && tgtCoder == LATIN1) {
    1772         return StringUTF16.indexOfLatin1(src, srcCount, tgt, tgtCount, fromIndex);
    1773     }
    1774
    1775     /**
    1776      * Returns the index within this string of the last occurrence of the
    1777      * specified substring.  The last occurrence of the empty string ""
    1778      * is considered to occur at the index value {@code this.length()}.
    1779      *
    1780      * <p>The returned index is the largest value {@code k} for which:
    1781      * <pre>{@code
    1782      * this.startsWith(str, k)
    1783      * }</pre>
    1784      * If no such value of {@code k} exists, then {@code -1} is returned.
    1785      *
    1786      * @param   str   the substring to search for.
    1787      * @return  the index of the last occurrence of the specified substring,
    1788      *          or {@code -1} if there is no such occurrence.
    1789      */
    1790     public int lastIndexOf(String str) {
    1791         return lastIndexOf(str, length());
    1792     }
    1793
    1794     /**
    1795      * Returns the index within this string of the last occurrence of the
    1796      * specified substring, searching backward starting at the specified index.
    1797      *
    1798      * <p>The returned index is the largest value {@code k} for which:
    1799      * <pre>{@code
    1800      *     k <= Math.min(fromIndex, this.length()) &&
    1801      *                   this.startsWith(str, k)
    1802      * }</pre>
    1803      * If no such value of {@code k} exists, then {@code -1} is returned.
    1804      *
    1805      * @param   str         the substring to search for.
    1806      * @param   fromIndex   the index to start the search from.
    1807      * @return  the index of the last occurrence of the specified substring,
    1808      *          searching backward from the specified index,
    1809      *          or {@code -1} if there is no such occurrence.
    1810      */
    1811     public int lastIndexOf(String str, int fromIndex) {
    1812         return lastIndexOf(value, coder(), length(), str, fromIndex);
    1813     }
    1814
    1815     /**
    1816      * Code shared by String and AbstractStringBuilder to do searches. The
    1817      * source is the character array being searched, and the target
    1818      * is the string being searched for.
    1819      *
    1820      * @param   src         the characters being searched.
    1821      * @param   srcCoder    coder handles the mapping between bytes/chars
    1822      * @param   srcCount    count of the source string.
    1823      * @param   tgtStr      the characters being searched for.
    1824      * @param   fromIndex   the index to begin searching from.
    1825      */
    1826     static int lastIndexOf(byte[] src, byte srcCoder, int srcCount,
    1827                            String tgtStr, int fromIndex) {
    1828         byte[] tgt = tgtStr.value;
    1829         byte tgtCoder = tgtStr.coder();
    1830         int tgtCount = tgtStr.length();
    1831         /*
    1832          * Check arguments; return immediately where possible. For
    1833          * consistency, don't check for null str.
    1834          */
    1835         int rightIndex = srcCount - tgtCount;
    1836         if (fromIndex > rightIndex) {
    1837             fromIndex = rightIndex;
    1838         }
    1839         if (fromIndex < 0) {
    1840             return -1;
    1841         }
    1842         /* Empty string always matches. */
    1843         if (tgtCount == 0) {
    1844             return fromIndex;
    1845         }
    1846         if (srcCoder == tgtCoder) {
    1847             return srcCoder == LATIN1
    1848                 ? StringLatin1.lastIndexOf(src, srcCount, tgt, tgtCount, fromIndex)
    1849                 : StringUTF16.lastIndexOf(src, srcCount, tgt, tgtCount, fromIndex);
    1850         }
    1851         if (srcCoder == LATIN1) {    // && tgtCoder == UTF16
    1852             return -1;
    1853         }
    1854         // srcCoder == UTF16 && tgtCoder == LATIN1
    1855         return StringUTF16.lastIndexOfLatin1(src, srcCount, tgt, tgtCount, fromIndex);
    1856     }
    1857
    1858     /**
    1859      * Returns a string that is a substring of this string. The
    1860      * substring begins with the character at the specified index and
    1861      * extends to the end of this string. <p>
    1862      * Examples:
    1863      * <blockquote><pre>
    1864      * "unhappy".substring(2) returns "happy"
    1865      * "Harbison".substring(3) returns "bison"
    1866      * "emptiness".substring(9) returns "" (an empty string)
    1867      * </pre></blockquote>
    1868      *
    1869      * @param      beginIndex   the beginning index, inclusive.
    1870      * @return     the specified substring.
    1871      * @throws     IndexOutOfBoundsException  if
    1872      *             {@code beginIndex} is negative or larger than the
    1873      *             length of this {@code String} object.
    1874      */
    1875     public String substring(int beginIndex) {
    1876         return substring(beginIndex, length());
    1877     }
    1878
    1879     /**
    1880      * Returns a string that is a substring of this string. The
    1881      * substring begins at the specified {@code beginIndex} and
    1882      * extends to the character at index {@code endIndex - 1}.
    1883      * Thus the length of the substring is {@code endIndex-beginIndex}.
    1884      * <p>
    1885      * Examples:
    1886      * <blockquote><pre>
    1887      * "hamburger".substring(4, 8) returns "urge"
    1888      * "smiles".substring(1, 5) returns "mile"
    1889      * </pre></blockquote>
    1890      *
    1891      * @param      beginIndex   the beginning index, inclusive.
    1892      * @param      endIndex     the ending index, exclusive.
    1893      * @return     the specified substring.
    1894      * @throws     IndexOutOfBoundsException  if the
    1895      *             {@code beginIndex} is negative, or
    1896      *             {@code endIndex} is larger than the length of
    1897      *             this {@code String} object, or
    1898      *             {@code beginIndex} is larger than
    1899      *             {@code endIndex}.
    1900      */
    1901     public String substring(int beginIndex, int endIndex) {
    1902         int length = length();
    1903         checkBoundsBeginEnd(beginIndex, endIndex, length);
    1904         if (beginIndex == 0 && endIndex == length) {
    1905             return this;
    1906         }
    1907         int subLen = endIndex - beginIndex;
    1908         return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
    1909                           : StringUTF16.newString(value, beginIndex, subLen);
    1910     }
    1911
    1912     /**
    1913      * Returns a character sequence that is a subsequence of this sequence.
    1914      *
    1915      * <p> An invocation of this method of the form
    1916      *
    1917      * <blockquote><pre>
    1918      * str.subSequence(begin,&nbsp;end)</pre></blockquote>
    1919      *
    1920      * behaves in exactly the same way as the invocation
    1921      *
    1922      * <blockquote><pre>
    1923      * str.substring(begin,&nbsp;end)</pre></blockquote>
    1924      *
    1925      * @apiNote
    1926      * This method is defined so that the {@code String} class can implement
    1927      * the {@link CharSequence} interface.
    1928      *
    1929      * @param   beginIndex   the begin index, inclusive.
    1930      * @param   endIndex     the end index, exclusive.
    1931      * @return  the specified subsequence.
    1932      *
    1933      * @throws  IndexOutOfBoundsException
    1934      *          if {@code beginIndex} or {@code endIndex} is negative,
    1935      *          if {@code endIndex} is greater than {@code length()},
    1936      *          or if {@code beginIndex} is greater than {@code endIndex}
    1937      *
    1938      * @since 1.4
    1939      * @spec JSR-51
    1940      */
    1941     public CharSequence subSequence(int beginIndex, int endIndex) {
    1942         return this.substring(beginIndex, endIndex);
    1943     }
    1944
    1945     /**
    1946      * Concatenates the specified string to the end of this string.
    1947      * <p>
    1948      * If the length of the argument string is {@code 0}, then this
    1949      * {@code String} object is returned. Otherwise, a
    1950      * {@code String} object is returned that represents a character
    1951      * sequence that is the concatenation of the character sequence
    1952      * represented by this {@code String} object and the character
    1953      * sequence represented by the argument string.<p>
    1954      * Examples:
    1955      * <blockquote><pre>
    1956      * "cares".concat("s") returns "caress"
    1957      * "to".concat("get").concat("her") returns "together"
    1958      * </pre></blockquote>
    1959      *
    1960      * @param   str   the {@code String} that is concatenated to the end
    1961      *                of this {@code String}.
    1962      * @return  a string that represents the concatenation of this object's
    1963      *          characters followed by the string argument's characters.
    1964      */
    1965     public String concat(String str) {
    1966         if (str.isEmpty()) {
    1967             return this;
    1968         }
    1969         return StringConcatHelper.simpleConcat(this, str);
    1970     }
    1971
    1972     /**
    1973      * Returns a string resulting from replacing all occurrences of
    1974      * {@code oldChar} in this string with {@code newChar}.
    1975      * <p>
    1976      * If the character {@code oldChar} does not occur in the
    1977      * character sequence represented by this {@code String} object,
    1978      * then a reference to this {@code String} object is returned.
    1979      * Otherwise, a {@code String} object is returned that
    1980      * represents a character sequence identical to the character sequence
    1981      * represented by this {@code String} object, except that every
    1982      * occurrence of {@code oldChar} is replaced by an occurrence
    1983      * of {@code newChar}.
    1984      * <p>
    1985      * Examples:
    1986      * <blockquote><pre>
    1987      * "mesquite in your cellar".replace('e', 'o')
    1988      *         returns "mosquito in your collar"
    1989      * "the war of baronets".replace('r', 'y')
    1990      *         returns "the way of bayonets"
    1991      * "sparring with a purple porpoise".replace('p', 't')
    1992      *         returns "starring with a turtle tortoise"
    1993      * "JonL".replace('q', 'x') returns "JonL" (no change)
    1994      * </pre></blockquote>
    1995      *
    1996      * @param   oldChar   the old character.
    1997      * @param   newChar   the new character.
    1998      * @return  a string derived from this string by replacing every
    1999      *          occurrence of {@code oldChar} with {@code newChar}.
    2000      */
    2001     public String replace(char oldChar, char newChar) {
    2002         if (oldChar != newChar) {
    2003             String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar)
    2004                                     : StringUTF16.replace(value, oldChar, newChar);
    2005             if (ret != null) {
    2006                 return ret;
    2007             }
    2008         }
    2009         return this;
    2010     }
    2011
    2012     /**
    2013      * Tells whether or not this string matches the given <a
    2014      * href="../util/regex/Pattern.html#sum">regular expression</a>.
    2015      *
    2016      * <p> An invocation of this method of the form
    2017      * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
    2018      * same result as the expression
    2019      *
    2020      * <blockquote>
    2021      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence)
    2022      * matches(<i>regex</i>, <i>str</i>)}
    2023      * </blockquote>
    2024      *
    2025      * @param   regex
    2026      *          the regular expression to which this string is to be matched
    2027      *
    2028      * @return  {@code true} if, and only if, this string matches the
    2029      *          given regular expression
    2030      *
    2031      * @throws  PatternSyntaxException
    2032      *          if the regular expression's syntax is invalid
    2033      *
    2034      * @see java.util.regex.Pattern
    2035      *
    2036      * @since 1.4
    2037      * @spec JSR-51
    2038      */
    2039     public boolean matches(String regex) {
    2040         return Pattern.matches(regex, this);
    2041     }
    2042
    2043     /**
    2044      * Returns true if and only if this string contains the specified
    2045      * sequence of char values.
    2046      *
    2047      * @param s the sequence to search for
    2048      * @return true if this string contains {@code s}, false otherwise
    2049      * @since 1.5
    2050      */
    2051     public boolean contains(CharSequence s) {
    2052         return indexOf(s.toString()) >= 0;
    2053     }
    2054
    2055     /**
    2056      * Replaces the first substring of this string that matches the given <a
    2057      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
    2058      * given replacement.
    2059      *
    2060      * <p> An invocation of this method of the form
    2061      * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
    2062      * yields exactly the same result as the expression
    2063      *
    2064      * <blockquote>
    2065      * <code>
    2066      * {@link java.util.regex.Pattern}.{@link
    2067      * java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
    2068      * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
    2069      * java.util.regex.Matcher#replaceFirst(String) replaceFirst}(<i>repl</i>)
    2070      * </code>
    2071      * </blockquote>
    2072      *
    2073      *<p>
    2074      * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
    2075      * replacement string may cause the results to be different than if it were
    2076      * being treated as a literal replacement string; see
    2077      * {@link java.util.regex.Matcher#replaceFirst}.
    2078      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
    2079      * meaning of these characters, if desired.
    2080      *
    2081      * @param   regex
    2082      *          the regular expression to which this string is to be matched
    2083      * @param   replacement
    2084      *          the string to be substituted for the first match
    2085      *
    2086      * @return  The resulting {@code String}
    2087      *
    2088      * @throws  PatternSyntaxException
    2089      *          if the regular expression's syntax is invalid
    2090      *
    2091      * @see java.util.regex.Pattern
    2092      *
    2093      * @since 1.4
    2094      * @spec JSR-51
    2095      */
    2096     public String replaceFirst(String regex, String replacement) {
    2097         return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
    2098     }
    2099
    2100     /**
    2101      * Replaces each substring of this string that matches the given <a
    2102      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
    2103      * given replacement.
    2104      *
    2105      * <p> An invocation of this method of the form
    2106      * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
    2107      * yields exactly the same result as the expression
    2108      *
    2109      * <blockquote>
    2110      * <code>
    2111      * {@link java.util.regex.Pattern}.{@link
    2112      * java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
    2113      * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
    2114      * java.util.regex.Matcher#replaceAll(String) replaceAll}(<i>repl</i>)
    2115      * </code>
    2116      * </blockquote>
    2117      *
    2118      *<p>
    2119      * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
    2120      * replacement string may cause the results to be different than if it were
    2121      * being treated as a literal replacement string; see
    2122      * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
    2123      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
    2124      * meaning of these characters, if desired.
    2125      *
    2126      * @param   regex
    2127      *          the regular expression to which this string is to be matched
    2128      * @param   replacement
    2129      *          the string to be substituted for each match
    2130      *
    2131      * @return  The resulting {@code String}
    2132      *
    2133      * @throws  PatternSyntaxException
    2134      *          if the regular expression's syntax is invalid
    2135      *
    2136      * @see java.util.regex.Pattern
    2137      *
    2138      * @since 1.4
    2139      * @spec JSR-51
    2140      */
    2141     public String replaceAll(String regex, String replacement) {
    2142         return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    2143     }
    2144
    2145     /**
    2146      * Replaces each substring of this string that matches the literal target
    2147      * sequence with the specified literal replacement sequence. The
    2148      * replacement proceeds from the beginning of the string to the end, for
    2149      * example, replacing "aa" with "b" in the string "aaa" will result in
    2150      * "ba" rather than "ab".
    2151      *
    2152      * @param  target The sequence of char values to be replaced
    2153      * @param  replacement The replacement sequence of char values
    2154      * @return  The resulting string
    2155      * @since 1.5
    2156      */
    2157     public String replace(CharSequence target, CharSequence replacement) {
    2158         String trgtStr = target.toString();
    2159         String replStr = replacement.toString();
    2160         int thisLen = length();
    2161         int trgtLen = trgtStr.length();
    2162         int replLen = replStr.length();
    2163
    2164         if (trgtLen > 0) {
    2165             if (trgtLen == 1 && replLen == 1) {
    2166                 return replace(trgtStr.charAt(0), replStr.charAt(0));
    2167             }
    2168
    2169             boolean thisIsLatin1 = this.isLatin1();
    2170             boolean trgtIsLatin1 = trgtStr.isLatin1();
    2171             boolean replIsLatin1 = replStr.isLatin1();
    2172             String ret = (thisIsLatin1 && trgtIsLatin1 && replIsLatin1)
    2173                     ? StringLatin1.replace(value, thisLen,
    2174                                            trgtStr.value, trgtLen,
    2175                                            replStr.value, replLen)
    2176                     : StringUTF16.replace(value, thisLen, thisIsLatin1,
    2177                                           trgtStr.value, trgtLen, trgtIsLatin1,
    2178                                           replStr.value, replLen, replIsLatin1);
    2179             if (ret != null) {
    2180                 return ret;
    2181             }
    2182             return this;
    2183
    2184         } else { // trgtLen == 0
    2185             int resultLen;
    2186             try {
    2187                 resultLen = Math.addExact(thisLen, Math.multiplyExact(
    2188                         Math.addExact(thisLen, 1), replLen));
    2189             } catch (ArithmeticException ignored) {
    2190                 throw new OutOfMemoryError("Required length exceeds implementation limit");
    2191             }
    2192
    2193             StringBuilder sb = new StringBuilder(resultLen);
    2194             sb.append(replStr);
    2195             for (int i = 0; i < thisLen; ++i) {
    2196                 sb.append(charAt(i)).append(replStr);
    2197             }
    2198             return sb.toString();
    2199         }
    2200     }
    2201
    2202     /**
    2203      * Splits this string around matches of the given
    2204      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
    2205      *
    2206      * <p> The array returned by this method contains each substring of this
    2207      * string that is terminated by another substring that matches the given
    2208      * expression or is terminated by the end of the string.  The substrings in
    2209      * the array are in the order in which they occur in this string.  If the
    2210      * expression does not match any part of the input then the resulting array
    2211      * has just one element, namely this string.
    2212      *
    2213      * <p> When there is a positive-width match at the beginning of this
    2214      * string then an empty leading substring is included at the beginning
    2215      * of the resulting array. A zero-width match at the beginning however
    2216      * never produces such empty leading substring.
    2217      *
    2218      * <p> The {@code limit} parameter controls the number of times the
    2219      * pattern is applied and therefore affects the length of the resulting
    2220      * array.
    2221      * <ul>
    2222      *    <li><p>
    2223      *    If the <i>limit</i> is positive then the pattern will be applied
    2224      *    at most <i>limit</i>&nbsp;-&nbsp;1 times, the array's length will be
    2225      *    no greater than <i>limit</i>, and the array's last entry will contain
    2226      *    all input beyond the last matched delimiter.</p></li>
    2227      *
    2228      *    <li><p>
    2229      *    If the <i>limit</i> is zero then the pattern will be applied as
    2230      *    many times as possible, the array can have any length, and trailing
    2231      *    empty strings will be discarded.</p></li>
    2232      *
    2233      *    <li><p>
    2234      *    If the <i>limit</i> is negative then the pattern will be applied
    2235      *    as many times as possible and the array can have any length.</p></li>
    2236      * </ul>
    2237      *
    2238      * <p> The string {@code "boo:and:foo"}, for example, yields the
    2239      * following results with these parameters:
    2240      *
    2241      * <blockquote><table class="plain">
    2242      * <caption style="display:none">Split example showing regex, limit, and result</caption>
    2243      * <thead>
    2244      * <tr>
    2245      *     <th scope="col">Regex</th>
    2246      *     <th scope="col">Limit</th>
    2247      *     <th scope="col">Result</th>
    2248      * </tr>
    2249      * </thead>
    2250      * <tbody>
    2251      * <tr><th scope="row" rowspan="3" style="font-weight:normal">:</th>
    2252      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">2</th>
    2253      *     <td>{@code { "boo", "and:foo" }}</td></tr>
    2254      * <tr><!-- : -->
    2255      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
    2256      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
    2257      * <tr><!-- : -->
    2258      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
    2259      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
    2260      * <tr><th scope="row" rowspan="3" style="font-weight:normal">o</th>
    2261      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
    2262      *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
    2263      * <tr><!-- o -->
    2264      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
    2265      *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
    2266      * <tr><!-- o -->
    2267      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">0</th>
    2268      *     <td>{@code { "b", "", ":and:f" }}</td></tr>
    2269      * </tbody>
    2270      * </table></blockquote>
    2271      *
    2272      * <p> An invocation of this method of the form
    2273      * <i>str.</i>{@code split(}<i>regex</i>{@code ,}&nbsp;<i>n</i>{@code )}
    2274      * yields the same result as the expression
    2275      *
    2276      * <blockquote>
    2277      * <code>
    2278      * {@link java.util.regex.Pattern}.{@link
    2279      * java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
    2280      * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>,&nbsp;<i>n</i>)
    2281      * </code>
    2282      * </blockquote>
    2283      *
    2284      *
    2285      * @param  regex
    2286      *         the delimiting regular expression
    2287      *
    2288      * @param  limit
    2289      *         the result threshold, as described above
    2290      *
    2291      * @return  the array of strings computed by splitting this string
    2292      *          around matches of the given regular expression
    2293      *
    2294      * @throws  PatternSyntaxException
    2295      *          if the regular expression's syntax is invalid
    2296      *
    2297      * @see java.util.regex.Pattern
    2298      *
    2299      * @since 1.4
    2300      * @spec JSR-51
    2301      */
    2302     public String[] split(String regex, int limit) {
    2303         /* fastpath if the regex is a
    2304          * (1) one-char String and this character is not one of the
    2305          *     RegEx's meta characters ".$|()[{^?*+\\", or
    2306          * (2) two-char String and the first char is the backslash and
    2307          *     the second is not the ascii digit or ascii letter.
    2308          */
    2309         char ch = 0;
    2310         if (((regex.length() == 1 &&
    2311              ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
    2312              (regex.length() == 2 &&
    2313               regex.charAt(0) == '\\' &&
    2314               (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
    2315               ((ch-'a')|('z'-ch)) < 0 &&
    2316               ((ch-'A')|('Z'-ch)) < 0)) &&
    2317             (ch < Character.MIN_HIGH_SURROGATE ||
    2318              ch > Character.MAX_LOW_SURROGATE))
    2319         {
    2320             int off = 0;
    2321             int next = 0;
    2322             boolean limited = limit > 0;
    2323             ArrayList<String> list = new ArrayList<>();
    2324             while ((next = indexOf(ch, off)) != -1) {
    2325                 if (!limited || list.size() < limit - 1) {
    2326                     list.add(substring(off, next));
    2327                     off = next + 1;
    2328                 } else {    // last one
    2329                     //assert (list.size() == limit - 1);
    2330                     int last = length();
    2331                     list.add(substring(off, last));
    2332                     off = last;
    2333                     break;
    2334                 }
    2335             }
    2336             // If no match was found, return this
    2337             if (off == 0)
    2338                 return new String[]{this};
    2339
    2340             // Add remaining segment
    2341             if (!limited || list.size() < limit)
    2342                 list.add(substring(off, length()));
    2343
    2344             // Construct result
    2345             int resultSize = list.size();
    2346             if (limit == 0) {
    2347                 while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {
    2348                     resultSize--;
    2349                 }
    2350             }
    2351             String[] result = new String[resultSize];
    2352             return list.subList(0, resultSize).toArray(result);
    2353         }
    2354         return Pattern.compile(regex).split(this, limit);
    2355     }
    2356
    2357     /**
    2358      * Splits this string around matches of the given <a
    2359      * href="../util/regex/Pattern.html#sum">regular expression</a>.
    2360      *
    2361      * <p> This method works as if by invoking the two-argument {@link
    2362      * #split(String, int) split} method with the given expression and a limit
    2363      * argument of zero.  Trailing empty strings are therefore not included in
    2364      * the resulting array.
    2365      *
    2366      * <p> The string {@code "boo:and:foo"}, for example, yields the following
    2367      * results with these expressions:
    2368      *
    2369      * <blockquote><table class="plain">
    2370      * <caption style="display:none">Split examples showing regex and result</caption>
    2371      * <thead>
    2372      * <tr>
    2373      *  <th scope="col">Regex</th>
    2374      *  <th scope="col">Result</th>
    2375      * </tr>
    2376      * </thead>
    2377      * <tbody>
    2378      * <tr><th scope="row" style="text-weight:normal">:</th>
    2379      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
    2380      * <tr><th scope="row" style="text-weight:normal">o</th>
    2381      *     <td>{@code { "b", "", ":and:f" }}</td></tr>
    2382      * </tbody>
    2383      * </table></blockquote>
    2384      *
    2385      *
    2386      * @param  regex
    2387      *         the delimiting regular expression
    2388      *
    2389      * @return  the array of strings computed by splitting this string
    2390      *          around matches of the given regular expression
    2391      *
    2392      * @throws  PatternSyntaxException
    2393      *          if the regular expression's syntax is invalid
    2394      *
    2395      * @see java.util.regex.Pattern
    2396      *
    2397      * @since 1.4
    2398      * @spec JSR-51
    2399      */
    2400     public String[] split(String regex) {
    2401         return split(regex, 0);
    2402     }
    2403
    2404     /**
    2405      * Returns a new String composed of copies of the
    2406      * {@code CharSequence elements} joined together with a copy of
    2407      * the specified {@code delimiter}.
    2408      *
    2409      * <blockquote>For example,
    2410      * <pre>{@code
    2411      *     String message = String.join("-", "Java", "is", "cool");
    2412      *     // message returned is: "Java-is-cool"
    2413      * }</pre></blockquote>
    2414      *
    2415      * Note that if an element is null, then {@code "null"} is added.
    2416      *
    2417      * @param  delimiter the delimiter that separates each element
    2418      * @param  elements the elements to join together.
    2419      *
    2420      * @return a new {@code String} that is composed of the {@code elements}
    2421      *         separated by the {@code delimiter}
    2422      *
    2423      * @throws NullPointerException If {@code delimiter} or {@code elements}
    2424      *         is {@code null}
    2425      *
    2426      * @see java.util.StringJoiner
    2427      * @since 1.8
    2428      */
    2429     public static String join(CharSequence delimiter, CharSequence... elements) {
    2430         Objects.requireNonNull(delimiter);
    2431         Objects.requireNonNull(elements);
    2432         // Number of elements not likely worth Arrays.stream overhead.
    2433         StringJoiner joiner = new StringJoiner(delimiter);
    2434         for (CharSequence cs: elements) {
    2435             joiner.add(cs);
    2436         }
    2437         return joiner.toString();
    2438     }
    2439
    2440     /**
    2441      * Returns a new {@code String} composed of copies of the
    2442      * {@code CharSequence elements} joined together with a copy of the
    2443      * specified {@code delimiter}.
    2444      *
    2445      * <blockquote>For example,
    2446      * <pre>{@code
    2447      *     List<String> strings = List.of("Java", "is", "cool");
    2448      *     String message = String.join(" ", strings);
    2449      *     // message returned is: "Java is cool"
    2450      *
    2451      *     Set<String> strings =
    2452      *         new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
    2453      *     String message = String.join("-", strings);
    2454      *     // message returned is: "Java-is-very-cool"
    2455      * }</pre></blockquote>
    2456      *
    2457      * Note that if an individual element is {@code null}, then {@code "null"} is added.
    2458      *
    2459      * @param  delimiter a sequence of characters that is used to separate each
    2460      *         of the {@code elements} in the resulting {@code String}
    2461      * @param  elements an {@code Iterable} that will have its {@code elements}
    2462      *         joined together.
    2463      *
    2464      * @return a new {@code String} that is composed from the {@code elements}
    2465      *         argument
    2466      *
    2467      * @throws NullPointerException If {@code delimiter} or {@code elements}
    2468      *         is {@code null}
    2469      *
    2470      * @see    #join(CharSequence,CharSequence...)
    2471      * @see    java.util.StringJoiner
    2472      * @since 1.8
    2473      */
    2474     public static String join(CharSequence delimiter,
    2475             Iterable<? extends CharSequence> elements) {
    2476         Objects.requireNonNull(delimiter);
    2477         Objects.requireNonNull(elements);
    2478         StringJoiner joiner = new StringJoiner(delimiter);
    2479         for (CharSequence cs: elements) {
    2480             joiner.add(cs);
    2481         }
    2482         return joiner.toString();
    2483     }
    2484
    2485     /**
    2486      * Converts all of the characters in this {@code String} to lower
    2487      * case using the rules of the given {@code Locale}.  Case mapping is based
    2488      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
    2489      * class. Since case mappings are not always 1:1 char mappings, the resulting
    2490      * {@code String} may be a different length than the original {@code String}.
    2491      * <p>
    2492      * Examples of lowercase  mappings are in the following table:
    2493      * <table class="plain">
    2494      * <caption style="display:none">Lowercase mapping examples showing language code of locale, upper case, lower case, and description</caption>
    2495      * <thead>
    2496      * <tr>
    2497      *   <th scope="col">Language Code of Locale</th>
    2498      *   <th scope="col">Upper Case</th>
    2499      *   <th scope="col">Lower Case</th>
    2500      *   <th scope="col">Description</th>
    2501      * </tr>
    2502      * </thead>
    2503      * <tbody>
    2504      * <tr>
    2505      *   <td>tr (Turkish)</td>
    2506      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0130</th>
    2507      *   <td>&#92;u0069</td>
    2508      *   <td>capital letter I with dot above -&gt; small letter i</td>
    2509      * </tr>
    2510      * <tr>
    2511      *   <td>tr (Turkish)</td>
    2512      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0049</th>
    2513      *   <td>&#92;u0131</td>
    2514      *   <td>capital letter I -&gt; small letter dotless i </td>
    2515      * </tr>
    2516      * <tr>
    2517      *   <td>(all)</td>
    2518      *   <th scope="row" style="font-weight:normal; text-align:left">French Fries</th>
    2519      *   <td>french fries</td>
    2520      *   <td>lowercased all chars in String</td>
    2521      * </tr>
    2522      * <tr>
    2523      *   <td>(all)</td>
    2524      *   <th scope="row" style="font-weight:normal; text-align:left">
    2525      *       &Iota;&Chi;&Theta;&Upsilon;&Sigma;</th>
    2526      *   <td>&iota;&chi;&theta;&upsilon;&sigma;</td>
    2527      *   <td>lowercased all chars in String</td>
    2528      * </tr>
    2529      * </tbody>
    2530      * </table>
    2531      *
    2532      * @param locale use the case transformation rules for this locale
    2533      * @return the {@code String}, converted to lowercase.
    2534      * @see     java.lang.String#toLowerCase()
    2535      * @see     java.lang.String#toUpperCase()
    2536      * @see     java.lang.String#toUpperCase(Locale)
    2537      * @since   1.1
    2538      */
    2539     public String toLowerCase(Locale locale) {
    2540         return isLatin1() ? StringLatin1.toLowerCase(this, value, locale)
    2541                           : StringUTF16.toLowerCase(this, value, locale);
    2542     }
    2543
    2544     /**
    2545      * Converts all of the characters in this {@code String} to lower
    2546      * case using the rules of the default locale. This is equivalent to calling
    2547      * {@code toLowerCase(Locale.getDefault())}.
    2548      * <p>
    2549      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
    2550      * results if used for strings that are intended to be interpreted locale
    2551      * independently.
    2552      * Examples are programming language identifiers, protocol keys, and HTML
    2553      * tags.
    2554      * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
    2555      * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
    2556      * LATIN SMALL LETTER DOTLESS I character.
    2557      * To obtain correct results for locale insensitive strings, use
    2558      * {@code toLowerCase(Locale.ROOT)}.
    2559      *
    2560      * @return  the {@code String}, converted to lowercase.
    2561      * @see     java.lang.String#toLowerCase(Locale)
    2562      */
    2563     public String toLowerCase() {
    2564         return toLowerCase(Locale.getDefault());
    2565     }
    2566
    2567     /**
    2568      * Converts all of the characters in this {@code String} to upper
    2569      * case using the rules of the given {@code Locale}. Case mapping is based
    2570      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
    2571      * class. Since case mappings are not always 1:1 char mappings, the resulting
    2572      * {@code String} may be a different length than the original {@code String}.
    2573      * <p>
    2574      * Examples of locale-sensitive and 1:M case mappings are in the following table.
    2575      *
    2576      * <table class="plain">
    2577      * <caption style="display:none">Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.</caption>
    2578      * <thead>
    2579      * <tr>
    2580      *   <th scope="col">Language Code of Locale</th>
    2581      *   <th scope="col">Lower Case</th>
    2582      *   <th scope="col">Upper Case</th>
    2583      *   <th scope="col">Description</th>
    2584      * </tr>
    2585      * </thead>
    2586      * <tbody>
    2587      * <tr>
    2588      *   <td>tr (Turkish)</td>
    2589      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0069</th>
    2590      *   <td>&#92;u0130</td>
    2591      *   <td>small letter i -&gt; capital letter I with dot above</td>
    2592      * </tr>
    2593      * <tr>
    2594      *   <td>tr (Turkish)</td>
    2595      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0131</th>
    2596      *   <td>&#92;u0049</td>
    2597      *   <td>small letter dotless i -&gt; capital letter I</td>
    2598      * </tr>
    2599      * <tr>
    2600      *   <td>(all)</td>
    2601      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u00df</th>
    2602      *   <td>&#92;u0053 &#92;u0053</td>
    2603      *   <td>small letter sharp s -&gt; two letters: SS</td>
    2604      * </tr>
    2605      * <tr>
    2606      *   <td>(all)</td>
    2607      *   <th scope="row" style="font-weight:normal; text-align:left">Fahrvergn&uuml;gen</th>
    2608      *   <td>FAHRVERGN&Uuml;GEN</td>
    2609      *   <td></td>
    2610      * </tr>
    2611      * </tbody>
    2612      * </table>
    2613      * @param locale use the case transformation rules for this locale
    2614      * @return the {@code String}, converted to uppercase.
    2615      * @see     java.lang.String#toUpperCase()
    2616      * @see     java.lang.String#toLowerCase()
    2617      * @see     java.lang.String#toLowerCase(Locale)
    2618      * @since   1.1
    2619      */
    2620     public String toUpperCase(Locale locale) {
    2621         return isLatin1() ? StringLatin1.toUpperCase(this, value, locale)
    2622                           : StringUTF16.toUpperCase(this, value, locale);
    2623     }
    2624
    2625     /**
    2626      * Converts all of the characters in this {@code String} to upper
    2627      * case using the rules of the default locale. This method is equivalent to
    2628      * {@code toUpperCase(Locale.getDefault())}.
    2629      * <p>
    2630      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
    2631      * results if used for strings that are intended to be interpreted locale
    2632      * independently.
    2633      * Examples are programming language identifiers, protocol keys, and HTML
    2634      * tags.
    2635      * For instance, {@code "title".toUpperCase()} in a Turkish locale
    2636      * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
    2637      * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
    2638      * To obtain correct results for locale insensitive strings, use
    2639      * {@code toUpperCase(Locale.ROOT)}.
    2640      *
    2641      * @return  the {@code String}, converted to uppercase.
    2642      * @see     java.lang.String#toUpperCase(Locale)
    2643      */
    2644     public String toUpperCase() {
    2645         return toUpperCase(Locale.getDefault());
    2646     }
    2647
    2648     /**
    2649      * Returns a string whose value is this string, with all leading
    2650      * and trailing space removed, where space is defined
    2651      * as any character whose codepoint is less than or equal to
    2652      * {@code 'U+0020'} (the space character).
    2653      * <p>
    2654      * If this {@code String} object represents an empty character
    2655      * sequence, or the first and last characters of character sequence
    2656      * represented by this {@code String} object both have codes
    2657      * that are not space (as defined above), then a
    2658      * reference to this {@code String} object is returned.
    2659      * <p>
    2660      * Otherwise, if all characters in this string are space (as
    2661      * defined above), then a  {@code String} object representing an
    2662      * empty string is returned.
    2663      * <p>
    2664      * Otherwise, let <i>k</i> be the index of the first character in the
    2665      * string whose code is not a space (as defined above) and let
    2666      * <i>m</i> be the index of the last character in the string whose code
    2667      * is not a space (as defined above). A {@code String}
    2668      * object is returned, representing the substring of this string that
    2669      * begins with the character at index <i>k</i> and ends with the
    2670      * character at index <i>m</i>-that is, the result of
    2671      * {@code this.substring(k, m + 1)}.
    2672      * <p>
    2673      * This method may be used to trim space (as defined above) from
    2674      * the beginning and end of a string.
    2675      *
    2676      * @return  a string whose value is this string, with all leading
    2677      *          and trailing space removed, or this string if it
    2678      *          has no leading or trailing space.
    2679      */
    2680     public String trim() {
    2681         String ret = isLatin1() ? StringLatin1.trim(value)
    2682                                 : StringUTF16.trim(value);
    2683         return ret == null ? this : ret;
    2684     }
    2685
    2686     /**
    2687      * Returns a string whose value is this string, with all leading
    2688      * and trailing {@linkplain Character#isWhitespace(int) white space}
    2689      * removed.
    2690      * <p>
    2691      * If this {@code String} object represents an empty string,
    2692      * or if all code points in this string are
    2693      * {@linkplain Character#isWhitespace(int) white space}, then an empty string
    2694      * is returned.
    2695      * <p>
    2696      * Otherwise, returns a substring of this string beginning with the first
    2697      * code point that is not a {@linkplain Character#isWhitespace(int) white space}
    2698      * up to and including the last code point that is not a
    2699      * {@linkplain Character#isWhitespace(int) white space}.
    2700      * <p>
    2701      * This method may be used to strip
    2702      * {@linkplain Character#isWhitespace(int) white space} from
    2703      * the beginning and end of a string.
    2704      *
    2705      * @return  a string whose value is this string, with all leading
    2706      *          and trailing white space removed
    2707      *
    2708      * @see Character#isWhitespace(int)
    2709      *
    2710      * @since 11
    2711      */
    2712     public String strip() {
    2713         String ret = isLatin1() ? StringLatin1.strip(value)
    2714                                 : StringUTF16.strip(value);
    2715         return ret == null ? this : ret;
    2716     }
    2717
    2718     /**
    2719      * Returns a string whose value is this string, with all leading
    2720      * {@linkplain Character#isWhitespace(int) white space} removed.
    2721      * <p>
    2722      * If this {@code String} object represents an empty string,
    2723      * or if all code points in this string are
    2724      * {@linkplain Character#isWhitespace(int) white space}, then an empty string
    2725      * is returned.
    2726      * <p>
    2727      * Otherwise, returns a substring of this string beginning with the first
    2728      * code point that is not a {@linkplain Character#isWhitespace(int) white space}
    2729      * up to and including the last code point of this string.
    2730      * <p>
    2731      * This method may be used to trim
    2732      * {@linkplain Character#isWhitespace(int) white space} from
    2733      * the beginning of a string.
    2734      *
    2735      * @return  a string whose value is this string, with all leading white
    2736      *          space removed
    2737      *
    2738      * @see Character#isWhitespace(int)
    2739      *
    2740      * @since 11
    2741      */
    2742     public String stripLeading() {
    2743         String ret = isLatin1() ? StringLatin1.stripLeading(value)
    2744                                 : StringUTF16.stripLeading(value);
    2745         return ret == null ? this : ret;
    2746     }
    2747
    2748     /**
    2749      * Returns a string whose value is this string, with all trailing
    2750      * {@linkplain Character#isWhitespace(int) white space} removed.
    2751      * <p>
    2752      * If this {@code String} object represents an empty string,
    2753      * or if all characters in this string are
    2754      * {@linkplain Character#isWhitespace(int) white space}, then an empty string
    2755      * is returned.
    2756      * <p>
    2757      * Otherwise, returns a substring of this string beginning with the first
    2758      * code point of this string up to and including the last code point
    2759      * that is not a {@linkplain Character#isWhitespace(int) white space}.
    2760      * <p>
    2761      * This method may be used to trim
    2762      * {@linkplain Character#isWhitespace(int) white space} from
    2763      * the end of a string.
    2764      *
    2765      * @return  a string whose value is this string, with all trailing white
    2766      *          space removed
    2767      *
    2768      * @see Character#isWhitespace(int)
    2769      *
    2770      * @since 11
    2771      */
    2772     public String stripTrailing() {
    2773         String ret = isLatin1() ? StringLatin1.stripTrailing(value)
    2774                                 : StringUTF16.stripTrailing(value);
    2775         return ret == null ? this : ret;
    2776     }
    2777
    2778     /**
    2779      * Returns {@code true} if the string is empty or contains only
    2780      * {@linkplain Character#isWhitespace(int) white space} codepoints,
    2781      * otherwise {@code false}.
    2782      *
    2783      * @return {@code true} if the string is empty or contains only
    2784      *         {@linkplain Character#isWhitespace(int) white space} codepoints,
    2785      *         otherwise {@code false}
    2786      *
    2787      * @see Character#isWhitespace(int)
    2788      *
    2789      * @since 11
    2790      */
    2791     public boolean isBlank() {
    2792         return indexOfNonWhitespace() == length();
    2793     }
    2794
    2795     /**
    2796      * Returns a stream of lines extracted from this string,
    2797      * separated by line terminators.
    2798      * <p>
    2799      * A <i>line terminator</i> is one of the following:
    2800      * a line feed character {@code "\n"} (U+000A),
    2801      * a carriage return character {@code "\r"} (U+000D),
    2802      * or a carriage return followed immediately by a line feed
    2803      * {@code "\r\n"} (U+000D U+000A).
    2804      * <p>
    2805      * A <i>line</i> is either a sequence of zero or more characters
    2806      * followed by a line terminator, or it is a sequence of one or
    2807      * more characters followed by the end of the string. A
    2808      * line does not include the line terminator.
    2809      * <p>
    2810      * The stream returned by this method contains the lines from
    2811      * this string in the order in which they occur.
    2812      *
    2813      * @apiNote This definition of <i>line</i> implies that an empty
    2814      *          string has zero lines and that there is no empty line
    2815      *          following a line terminator at the end of a string.
    2816      *
    2817      * @implNote This method provides better performance than
    2818      *           split("\R") by supplying elements lazily and
    2819      *           by faster search of new line terminators.
    2820      *
    2821      * @return  the stream of lines extracted from this string
    2822      *
    2823      * @since 11
    2824      */
    2825     public Stream<String> lines() {
    2826         return isLatin1() ? StringLatin1.lines(value) : StringUTF16.lines(value);
    2827     }
    2828
    2829     /**
    2830      * Adjusts the indentation of each line of this string based on the value of
    2831      * {@code n}, and normalizes line termination characters.
    2832      * <p>
    2833      * This string is conceptually separated into lines using
    2834      * {@link String#lines()}. Each line is then adjusted as described below
    2835      * and then suffixed with a line feed {@code "\n"} (U+000A). The resulting
    2836      * lines are then concatenated and returned.
    2837      * <p>
    2838      * If {@code n > 0} then {@code n} spaces (U+0020) are inserted at the
    2839      * beginning of each line.
    2840      * <p>
    2841      * If {@code n < 0} then up to {@code n}
    2842      * {@linkplain Character#isWhitespace(int) white space characters} are removed
    2843      * from the beginning of each line. If a given line does not contain
    2844      * sufficient white space then all leading
    2845      * {@linkplain Character#isWhitespace(int) white space characters} are removed.
    2846      * Each white space character is treated as a single character. In
    2847      * particular, the tab character {@code "\t"} (U+0009) is considered a
    2848      * single character; it is not expanded.
    2849      * <p>
    2850      * If {@code n == 0} then the line remains unchanged. However, line
    2851      * terminators are still normalized.
    2852      *
    2853      * @param n  number of leading
    2854      *           {@linkplain Character#isWhitespace(int) white space characters}
    2855      *           to add or remove
    2856      *
    2857      * @return string with indentation adjusted and line endings normalized
    2858      *
    2859      * @see String#lines()
    2860      * @see String#isBlank()
    2861      * @see Character#isWhitespace(int)
    2862      *
    2863      * @since 12
    2864      */
    2865     public String indent(int n) {
    2866         if (isEmpty()) {
    2867             return "";
    2868         }
    2869         Stream<String> stream = lines();
    2870         if (n > 0) {
    2871             final String spaces = " ".repeat(n);
    2872             stream = stream.map(s -> spaces + s);
    2873         } else if (n == Integer.MIN_VALUE) {
    2874             stream = stream.map(s -> s.stripLeading());
    2875         } else if (n < 0) {
    2876             stream = stream.map(s -> s.substring(Math.min(-n, s.indexOfNonWhitespace())));
    2877         }
    2878         return stream.collect(Collectors.joining("\n", "", "\n"));
    2879     }
    2880
    2881     private int indexOfNonWhitespace() {
    2882         return isLatin1() ? StringLatin1.indexOfNonWhitespace(value)
    2883                           : StringUTF16.indexOfNonWhitespace(value);
    2884     }
    2885
    2886     private int lastIndexOfNonWhitespace() {
    2887         return isLatin1() ? StringLatin1.lastIndexOfNonWhitespace(value)
    2888                           : StringUTF16.lastIndexOfNonWhitespace(value);
    2889     }
    2890
    2891     /**
    2892      * Returns a string whose value is this string, with incidental
    2893      * {@linkplain Character#isWhitespace(int) white space} removed from
    2894      * the beginning and end of every line.
    2895      * <p>
    2896      * Incidental {@linkplain Character#isWhitespace(int) white space}
    2897      * is often present in a text block to align the content with the opening
    2898      * delimiter. For example, in the following code, dots represent incidental
    2899      * {@linkplain Character#isWhitespace(int) white space}:
    2900      * <blockquote><pre>
    2901      * String html = """
    2902      * ..............&lt;html&gt;
    2903      * ..............    &lt;body&gt;
    2904      * ..............        &lt;p&gt;Hello, world&lt;/p&gt;
    2905      * ..............    &lt;/body&gt;
    2906      * ..............&lt;/html&gt;
    2907      * ..............""";
    2908      * </pre></blockquote>
    2909      * This method treats the incidental
    2910      * {@linkplain Character#isWhitespace(int) white space} as indentation to be
    2911      * stripped, producing a string that preserves the relative indentation of
    2912      * the content. Using | to visualize the start of each line of the string:
    2913      * <blockquote><pre>
    2914      * |&lt;html&gt;
    2915      * |    &lt;body&gt;
    2916      * |        &lt;p&gt;Hello, world&lt;/p&gt;
    2917      * |    &lt;/body&gt;
    2918      * |&lt;/html&gt;
    2919      * </pre></blockquote>
    2920      * First, the individual lines of this string are extracted. A <i>line</i>
    2921      * is a sequence of zero or more characters followed by either a line
    2922      * terminator or the end of the string.
    2923      * If the string has at least one line terminator, the last line consists
    2924      * of the characters between the last terminator and the end of the string.
    2925      * Otherwise, if the string has no terminators, the last line is the start
    2926      * of the string to the end of the string, in other words, the entire
    2927      * string.
    2928      * A line does not include the line terminator.
    2929      * <p>
    2930      * Then, the <i>minimum indentation</i> (min) is determined as follows:
    2931      * <ul>
    2932      *   <li><p>For each non-blank line (as defined by {@link String#isBlank()}),
    2933      *   the leading {@linkplain Character#isWhitespace(int) white space}
    2934      *   characters are counted.</p>
    2935      *   </li>
    2936      *   <li><p>The leading {@linkplain Character#isWhitespace(int) white space}
    2937      *   characters on the last line are also counted even if
    2938      *   {@linkplain String#isBlank() blank}.</p>
    2939      *   </li>
    2940      * </ul>
    2941      * <p>The <i>min</i> value is the smallest of these counts.
    2942      * <p>
    2943      * For each {@linkplain String#isBlank() non-blank} line, <i>min</i> leading
    2944      * {@linkplain Character#isWhitespace(int) white space} characters are
    2945      * removed, and any trailing {@linkplain Character#isWhitespace(int) white
    2946      * space} characters are removed. {@linkplain String#isBlank() Blank} lines
    2947      * are replaced with the empty string.
    2948      *
    2949      * <p>
    2950      * Finally, the lines are joined into a new string, using the LF character
    2951      * {@code "\n"} (U+000A) to separate lines.
    2952      *
    2953      * @apiNote
    2954      * This method's primary purpose is to shift a block of lines as far as
    2955      * possible to the left, while preserving relative indentation. Lines
    2956      * that were indented the least will thus have no leading
    2957      * {@linkplain Character#isWhitespace(int) white space}.
    2958      * The result will have the same number of line terminators as this string.
    2959      * If this string ends with a line terminator then the result will end
    2960      * with a line terminator.
    2961      *
    2962      * @implSpec
    2963      * This method treats all {@linkplain Character#isWhitespace(int) white space}
    2964      * characters as having equal width. As long as the indentation on every
    2965      * line is consistently composed of the same character sequences, then the
    2966      * result will be as described above.
    2967      *
    2968      * @return string with incidental indentation removed and line
    2969      *         terminators normalized
    2970      *
    2971      * @see String#lines()
    2972      * @see String#isBlank()
    2973      * @see String#indent(int)
    2974      * @see Character#isWhitespace(int)
    2975      *
    2976      * @since 15
    2977      *
    2978      */
    2979     public String stripIndent() {
    2980         int length = length();
    2981         if (length == 0) {
    2982             return "";
    2983         }
    2984         char lastChar = charAt(length - 1);
    2985         boolean optOut = lastChar == '\n' || lastChar == '\r';
    2986         List<String> lines = lines().collect(Collectors.toList());
    2987         final int outdent = optOut ? 0 : outdent(lines);
    2988         return lines.stream()
    2989             .map(line -> {
    2990                 int firstNonWhitespace = line.indexOfNonWhitespace();
    2991                 int lastNonWhitespace = line.lastIndexOfNonWhitespace();
    2992                 int incidentalWhitespace = Math.min(outdent, firstNonWhitespace);
    2993                 return firstNonWhitespace > lastNonWhitespace
    2994                     ? "" : line.substring(incidentalWhitespace, lastNonWhitespace);
    2995             })
    2996             .collect(Collectors.joining("\n", "", optOut ? "\n" : ""));
    2997     }
    2998
    2999     private static int outdent(List<String> lines) {
    3000         // Note: outdent is guaranteed to be zero or positive number.
    3001         // If there isn't a non-blank line then the last must be blank
    3002         int outdent = Integer.MAX_VALUE;
    3003         for (String line : lines) {
    3004             int leadingWhitespace = line.indexOfNonWhitespace();
    3005             if (leadingWhitespace != line.length()) {
    3006                 outdent = Integer.min(outdent, leadingWhitespace);
    3007             }
    3008         }
    3009         String lastLine = lines.get(lines.size() - 1);
    3010         if (lastLine.isBlank()) {
    3011             outdent = Integer.min(outdent, lastLine.length());
    3012         }
    3013         return outdent;
    3014     }
    3015
    3016     /**
    3017      * Returns a string whose value is this string, with escape sequences
    3018      * translated as if in a string literal.
    3019      * <p>
    3020      * Escape sequences are translated as follows;
    3021      * <table class="striped">
    3022      *   <caption style="display:none">Translation</caption>
    3023      *   <thead>
    3024      *   <tr>
    3025      *     <th scope="col">Escape</th>
    3026      *     <th scope="col">Name</th>
    3027      *     <th scope="col">Translation</th>
    3028      *   </tr>
    3029      *   </thead>
    3030      *   <tbody>
    3031      *   <tr>
    3032      *     <th scope="row">{@code \u005Cb}</th>
    3033      *     <td>backspace</td>
    3034      *     <td>{@code U+0008}</td>
    3035      *   </tr>
    3036      *   <tr>
    3037      *     <th scope="row">{@code \u005Ct}</th>
    3038      *     <td>horizontal tab</td>
    3039      *     <td>{@code U+0009}</td>
    3040      *   </tr>
    3041      *   <tr>
    3042      *     <th scope="row">{@code \u005Cn}</th>
    3043      *     <td>line feed</td>
    3044      *     <td>{@code U+000A}</td>
    3045      *   </tr>
    3046      *   <tr>
    3047      *     <th scope="row">{@code \u005Cf}</th>
    3048      *     <td>form feed</td>
    3049      *     <td>{@code U+000C}</td>
    3050      *   </tr>
    3051      *   <tr>
    3052      *     <th scope="row">{@code \u005Cr}</th>
    3053      *     <td>carriage return</td>
    3054      *     <td>{@code U+000D}</td>
    3055      *   </tr>
    3056      *   <tr>
    3057      *     <th scope="row">{@code \u005Cs}</th>
    3058      *     <td>space</td>
    3059      *     <td>{@code U+0020}</td>
    3060      *   </tr>
    3061      *   <tr>
    3062      *     <th scope="row">{@code \u005C"}</th>
    3063      *     <td>double quote</td>
    3064      *     <td>{@code U+0022}</td>
    3065      *   </tr>
    3066      *   <tr>
    3067      *     <th scope="row">{@code \u005C'}</th>
    3068      *     <td>single quote</td>
    3069      *     <td>{@code U+0027}</td>
    3070      *   </tr>
    3071      *   <tr>
    3072      *     <th scope="row">{@code \u005C\u005C}</th>
    3073      *     <td>backslash</td>
    3074      *     <td>{@code U+005C}</td>
    3075      *   </tr>
    3076      *   <tr>
    3077      *     <th scope="row">{@code \u005C0 - \u005C377}</th>
    3078      *     <td>octal escape</td>
    3079      *     <td>code point equivalents</td>
    3080      *   </tr>
    3081      *   <tr>
    3082      *     <th scope="row">{@code \u005C<line-terminator>}</th>
    3083      *     <td>continuation</td>
    3084      *     <td>discard</td>
    3085      *   </tr>
    3086      *   </tbody>
    3087      * </table>
    3088      *
    3089      * @implNote
    3090      * This method does <em>not</em> translate Unicode escapes such as "{@code \u005cu2022}".
    3091      * Unicode escapes are translated by the Java compiler when reading input characters and
    3092      * are not part of the string literal specification.
    3093      *
    3094      * @throws IllegalArgumentException when an escape sequence is malformed.
    3095      *
    3096      * @return String with escape sequences translated.
    3097      *
    3098      * @jls 3.10.7 Escape Sequences
    3099      *
    3100      * @since 15
    3101      */
    3102     public String translateEscapes() {
    3103         if (isEmpty()) {
    3104             return "";
    3105         }
    3106         char[] chars = toCharArray();
    3107         int length = chars.length;
    3108         int from = 0;
    3109         int to = 0;
    3110         while (from < length) {
    3111             char ch = chars[from++];
    3112             if (ch == '\\') {
    3113                 ch = from < length ? chars[from++] : '\0';
    3114                 switch (ch) {
    3115                 case 'b':
    3116                     ch = '\b';
    3117                     break;
    3118                 case 'f':
    3119                     ch = '\f';
    3120                     break;
    3121                 case 'n':
    3122                     ch = '\n';
    3123                     break;
    3124                 case 'r':
    3125                     ch = '\r';
    3126                     break;
    3127                 case 's':
    3128                     ch = ' ';
    3129                     break;
    3130                 case 't':
    3131                     ch = '\t';
    3132                     break;
    3133                 case '\'':
    3134                 case '\"':
    3135                 case '\\':
    3136                     // as is
    3137                     break;
    3138                 case '0': case '1': case '2': case '3':
    3139                 case '4': case '5': case '6': case '7':
    3140                     int limit = Integer.min(from + (ch <= '3' ? 2 : 1), length);
    3141                     int code = ch - '0';
    3142                     while (from < limit) {
    3143                         ch = chars[from];
    3144                         if (ch < '0' || '7' < ch) {
    3145                             break;
    3146                         }
    3147                         from++;
    3148                         code = (code << 3) | (ch - '0');
    3149                     }
    3150                     ch = (char)code;
    3151                     break;
    3152                 case '\n':
    3153                     continue;
    3154                 case '\r':
    3155                     if (from < length && chars[from] == '\n') {
    3156                         from++;
    3157                     }
    3158                     continue;
    3159                 default: {
    3160                     String msg = String.format(
    3161                         "Invalid escape sequence: \\%c \\\\u%04X",
    3162                         ch, (int)ch);
    3163                     throw new IllegalArgumentException(msg);
    3164                 }
    3165                 }
    3166             }
    3167
    3168             chars[to++] = ch;
    3169         }
    3170
    3171         return new String(chars, 0, to);
    3172     }
    3173
    3174     /**
    3175      * This method allows the application of a function to {@code this}
    3176      * string. The function should expect a single String argument
    3177      * and produce an {@code R} result.
    3178      * <p>
    3179      * Any exception thrown by {@code f()} will be propagated to the
    3180      * caller.
    3181      *
    3182      * @param f    functional interface to a apply
    3183      *
    3184      * @param <R>  class of the result
    3185      *
    3186      * @return     the result of applying the function to this string
    3187      *
    3188      * @see java.util.function.Function
    3189      *
    3190      * @since 12
    3191      */
    3192     public <R> R transform(Function<? super String, ? extends R> f) {
    3193         return f.apply(this);
    3194     }
    3195
    3196     /**
    3197      * This object (which is already a string!) is itself returned.
    3198      *
    3199      * @return  the string itself.
    3200      */
    3201     public String toString() {
    3202         return this;
    3203     }
    3204
    3205     /**
    3206      * Returns a stream of {@code int} zero-extending the {@code char} values
    3207      * from this sequence.  Any char which maps to a <a
    3208      * href="{@docRoot}/java.base/java/lang/Character.html#unicode">surrogate code
    3209      * point</a> is passed through uninterpreted.
    3210      *
    3211      * @return an IntStream of char values from this sequence
    3212      * @since 9
    3213      */
    3214     @Override
    3215     public IntStream chars() {
    3216         return StreamSupport.intStream(
    3217             isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
    3218                        : new StringUTF16.CharsSpliterator(value, Spliterator.IMMUTABLE),
    3219             false);
    3220     }
    3221
    3222
    3223     /**
    3224      * Returns a stream of code point values from this sequence.  Any surrogate
    3225      * pairs encountered in the sequence are combined as if by {@linkplain
    3226      * Character#toCodePoint Character.toCodePoint} and the result is passed
    3227      * to the stream. Any other code units, including ordinary BMP characters,
    3228      * unpaired surrogates, and undefined code units, are zero-extended to
    3229      * {@code int} values which are then passed to the stream.
    3230      *
    3231      * @return an IntStream of Unicode code points from this sequence
    3232      * @since 9
    3233      */
    3234     @Override
    3235     public IntStream codePoints() {
    3236         return StreamSupport.intStream(
    3237             isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
    3238                        : new StringUTF16.CodePointsSpliterator(value, Spliterator.IMMUTABLE),
    3239             false);
    3240     }
    3241
    3242     /**
    3243      * Converts this string to a new character array.
    3244      *
    3245      * @return  a newly allocated character array whose length is the length
    3246      *          of this string and whose contents are initialized to contain
    3247      *          the character sequence represented by this string.
    3248      */
    3249     public char[] toCharArray() {
    3250         return isLatin1() ? StringLatin1.toChars(value)
    3251                           : StringUTF16.toChars(value);
    3252     }
    3253
    3254     /**
    3255      * Returns a formatted string using the specified format string and
    3256      * arguments.
    3257      *
    3258      * <p> The locale always used is the one returned by {@link
    3259      * java.util.Locale#getDefault(java.util.Locale.Category)
    3260      * Locale.getDefault(Locale.Category)} with
    3261      * {@link java.util.Locale.Category#FORMAT FORMAT} category specified.
    3262      *
    3263      * @param  format
    3264      *         A <a href="../util/Formatter.html#syntax">format string</a>
    3265      *
    3266      * @param  args
    3267      *         Arguments referenced by the format specifiers in the format
    3268      *         string.  If there are more arguments than format specifiers, the
    3269      *         extra arguments are ignored.  The number of arguments is
    3270      *         variable and may be zero.  The maximum number of arguments is
    3271      *         limited by the maximum dimension of a Java array as defined by
    3272      *         <cite>The Java Virtual Machine Specification</cite>.
    3273      *         The behaviour on a
    3274      *         {@code null} argument depends on the <a
    3275      *         href="../util/Formatter.html#syntax">conversion</a>.
    3276      *
    3277      * @throws  java.util.IllegalFormatException
    3278      *          If a format string contains an illegal syntax, a format
    3279      *          specifier that is incompatible with the given arguments,
    3280      *          insufficient arguments given the format string, or other
    3281      *          illegal conditions.  For specification of all possible
    3282      *          formatting errors, see the <a
    3283      *          href="../util/Formatter.html#detail">Details</a> section of the
    3284      *          formatter class specification.
    3285      *
    3286      * @return  A formatted string
    3287      *
    3288      * @see  java.util.Formatter
    3289      * @since  1.5
    3290      */
    3291     public static String format(String format, Object... args) {
    3292         return new Formatter().format(format, args).toString();
    3293     }
    3294
    3295     /**
    3296      * Returns a formatted string using the specified locale, format string,
    3297      * and arguments.
    3298      *
    3299      * @param  l
    3300      *         The {@linkplain java.util.Locale locale} to apply during
    3301      *         formatting.  If {@code l} is {@code null} then no localization
    3302      *         is applied.
    3303      *
    3304      * @param  format
    3305      *         A <a href="../util/Formatter.html#syntax">format string</a>
    3306      *
    3307      * @param  args
    3308      *         Arguments referenced by the format specifiers in the format
    3309      *         string.  If there are more arguments than format specifiers, the
    3310      *         extra arguments are ignored.  The number of arguments is
    3311      *         variable and may be zero.  The maximum number of arguments is
    3312      *         limited by the maximum dimension of a Java array as defined by
    3313      *         <cite>The Java Virtual Machine Specification</cite>.
    3314      *         The behaviour on a
    3315      *         {@code null} argument depends on the
    3316      *         <a href="../util/Formatter.html#syntax">conversion</a>.
    3317      *
    3318      * @throws  java.util.IllegalFormatException
    3319      *          If a format string contains an illegal syntax, a format
    3320      *          specifier that is incompatible with the given arguments,
    3321      *          insufficient arguments given the format string, or other
    3322      *          illegal conditions.  For specification of all possible
    3323      *          formatting errors, see the <a
    3324      *          href="../util/Formatter.html#detail">Details</a> section of the
    3325      *          formatter class specification
    3326      *
    3327      * @return  A formatted string
    3328      *
    3329      * @see  java.util.Formatter
    3330      * @since  1.5
    3331      */
    3332     public static String format(Locale l, String format, Object... args) {
    3333         return new Formatter(l).format(format, args).toString();
    3334     }
    3335
    3336     /**
    3337      * Formats using this string as the format string, and the supplied
    3338      * arguments.
    3339      *
    3340      * @implSpec This method is equivalent to {@code String.format(this, args)}.
    3341      *
    3342      * @param  args
    3343      *         Arguments referenced by the format specifiers in this string.
    3344      *
    3345      * @return  A formatted string
    3346      *
    3347      * @see  java.lang.String#format(String,Object...)
    3348      * @see  java.util.Formatter
    3349      *
    3350      * @since 15
    3351      *
    3352      */
    3353     public String formatted(Object... args) {
    3354         return new Formatter().format(this, args).toString();
    3355     }
    3356
    3357     /**
    3358      * Returns the string representation of the {@code Object} argument.
    3359      *
    3360      * @param   obj   an {@code Object}.
    3361      * @return  if the argument is {@code null}, then a string equal to
    3362      *          {@code "null"}; otherwise, the value of
    3363      *          {@code obj.toString()} is returned.
    3364      * @see     java.lang.Object#toString()
    3365      */
    3366     public static String valueOf(Object obj) {
    3367         return (obj == null) ? "null" : obj.toString();
    3368     }
    3369
    3370     /**
    3371      * Returns the string representation of the {@code char} array
    3372      * argument. The contents of the character array are copied; subsequent
    3373      * modification of the character array does not affect the returned
    3374      * string.
    3375      *
    3376      * @param   data     the character array.
    3377      * @return  a {@code String} that contains the characters of the
    3378      *          character array.
    3379      */
    3380     public static String valueOf(char data[]) {
    3381         return new String(data);
    3382     }
    3383
    3384     /**
    3385      * Returns the string representation of a specific subarray of the
    3386      * {@code char} array argument.
    3387      * <p>
    3388      * The {@code offset} argument is the index of the first
    3389      * character of the subarray. The {@code count} argument
    3390      * specifies the length of the subarray. The contents of the subarray
    3391      * are copied; subsequent modification of the character array does not
    3392      * affect the returned string.
    3393      *
    3394      * @param   data     the character array.
    3395      * @param   offset   initial offset of the subarray.
    3396      * @param   count    length of the subarray.
    3397      * @return  a {@code String} that contains the characters of the
    3398      *          specified subarray of the character array.
    3399      * @throws    IndexOutOfBoundsException if {@code offset} is
    3400      *          negative, or {@code count} is negative, or
    3401      *          {@code offset+count} is larger than
    3402      *          {@code data.length}.
    3403      */
    3404     public static String valueOf(char data[], int offset, int count) {
    3405         return new String(data, offset, count);
    3406     }
    3407
    3408     /**
    3409      * Equivalent to {@link #valueOf(char[], int, int)}.
    3410      *
    3411      * @param   data     the character array.
    3412      * @param   offset   initial offset of the subarray.
    3413      * @param   count    length of the subarray.
    3414      * @return  a {@code String} that contains the characters of the
    3415      *          specified subarray of the character array.
    3416      * @throws    IndexOutOfBoundsException if {@code offset} is
    3417      *          negative, or {@code count} is negative, or
    3418      *          {@code offset+count} is larger than
    3419      *          {@code data.length}.
    3420      */
    3421     public static String copyValueOf(char data[], int offset, int count) {
    3422         return new String(data, offset, count);
    3423     }
    3424
    3425     /**
    3426      * Equivalent to {@link #valueOf(char[])}.
    3427      *
    3428      * @param   data   the character array.
    3429      * @return  a {@code String} that contains the characters of the
    3430      *          character array.
    3431      */
    3432     public static String copyValueOf(char data[]) {
    3433         return new String(data);
    3434     }
    3435
    3436     /**
    3437      * Returns the string representation of the {@code boolean} argument.
    3438      *
    3439      * @param   b   a {@code boolean}.
    3440      * @return  if the argument is {@code true}, a string equal to
    3441      *          {@code "true"} is returned; otherwise, a string equal to
    3442      *          {@code "false"} is returned.
    3443      */
    3444     public static String valueOf(boolean b) {
    3445         return b ? "true" : "false";
    3446     }
    3447
    3448     /**
    3449      * Returns the string representation of the {@code char}
    3450      * argument.
    3451      *
    3452      * @param   c   a {@code char}.
    3453      * @return  a string of length {@code 1} containing
    3454      *          as its single character the argument {@code c}.
    3455      */
    3456     public static String valueOf(char c) {
    3457         if (COMPACT_STRINGS && StringLatin1.canEncode(c)) {
    3458             return new String(StringLatin1.toBytes(c), LATIN1);
    3459         }
    3460         return new String(StringUTF16.toBytes(c), UTF16);
    3461     }
    3462
    3463     /**
    3464      * Returns the string representation of the {@code int} argument.
    3465      * <p>
    3466      * The representation is exactly the one returned by the
    3467      * {@code Integer.toString} method of one argument.
    3468      *
    3469      * @param   i   an {@code int}.
    3470      * @return  a string representation of the {@code int} argument.
    3471      * @see     java.lang.Integer#toString(int, int)
    3472      */
    3473     public static String valueOf(int i) {
    3474         return Integer.toString(i);
    3475     }
    3476
    3477     /**
    3478      * Returns the string representation of the {@code long} argument.
    3479      * <p>
    3480      * The representation is exactly the one returned by the
    3481      * {@code Long.toString} method of one argument.
    3482      *
    3483      * @param   l   a {@code long}.
    3484      * @return  a string representation of the {@code long} argument.
    3485      * @see     java.lang.Long#toString(long)
    3486      */
    3487     public static String valueOf(long l) {
    3488         return Long.toString(l);
    3489     }
    3490
    3491     /**
    3492      * Returns the string representation of the {@code float} argument.
    3493      * <p>
    3494      * The representation is exactly the one returned by the
    3495      * {@code Float.toString} method of one argument.
    3496      *
    3497      * @param   f   a {@code float}.
    3498      * @return  a string representation of the {@code float} argument.
    3499      * @see     java.lang.Float#toString(float)
    3500      */
    3501     public static String valueOf(float f) {
    3502         return Float.toString(f);
    3503     }
    3504
    3505     /**
    3506      * Returns the string representation of the {@code double} argument.
    3507      * <p>
    3508      * The representation is exactly the one returned by the
    3509      * {@code Double.toString} method of one argument.
    3510      *
    3511      * @param   d   a {@code double}.
    3512      * @return  a  string representation of the {@code double} argument.
    3513      * @see     java.lang.Double#toString(double)
    3514      */
    3515     public static String valueOf(double d) {
    3516         return Double.toString(d);
    3517     }
    3518
    3519     /**
    3520      * Returns a canonical representation for the string object.
    3521      * <p>
    3522      * A pool of strings, initially empty, is maintained privately by the
    3523      * class {@code String}.
    3524      * <p>
    3525      * When the intern method is invoked, if the pool already contains a
    3526      * string equal to this {@code String} object as determined by
    3527      * the {@link #equals(Object)} method, then the string from the pool is
    3528      * returned. Otherwise, this {@code String} object is added to the
    3529      * pool and a reference to this {@code String} object is returned.
    3530      * <p>
    3531      * It follows that for any two strings {@code s} and {@code t},
    3532      * {@code s.intern() == t.intern()} is {@code true}
    3533      * if and only if {@code s.equals(t)} is {@code true}.
    3534      * <p>
    3535      * All literal strings and string-valued constant expressions are
    3536      * interned. String literals are defined in section {@jls 3.10.5} of the
    3537      * <cite>The Java Language Specification</cite>.
    3538      *
    3539      * @return  a string that has the same contents as this string, but is
    3540      *          guaranteed to be from a pool of unique strings.
    3541      */
    3542     public native String intern();
    3543
    3544     /**
    3545      * Returns a string whose value is the concatenation of this
    3546      * string repeated {@code count} times.
    3547      * <p>
    3548      * If this string is empty or count is zero then the empty
    3549      * string is returned.
    3550      *
    3551      * @param   count number of times to repeat
    3552      *
    3553      * @return  A string composed of this string repeated
    3554      *          {@code count} times or the empty string if this
    3555      *          string is empty or count is zero
    3556      *
    3557      * @throws  IllegalArgumentException if the {@code count} is
    3558      *          negative.
    3559      *
    3560      * @since 11
    3561      */
    3562     public String repeat(int count) {
    3563         if (count < 0) {
    3564             throw new IllegalArgumentException("count is negative: " + count);
    3565         }
    3566         if (count == 1) {
    3567             return this;
    3568         }
    3569         final int len = value.length;
    3570         if (len == 0 || count == 0) {
    3571             return "";
    3572         }
    3573         if (Integer.MAX_VALUE / count < len) {
    3574             throw new OutOfMemoryError("Required length exceeds implementation limit");
    3575         }
    3576         if (len == 1) {
    3577             final byte[] single = new byte[count];
    3578             Arrays.fill(single, value[0]);
    3579             return new String(single, coder);
    3580         }
    3581         final int limit = len * count;
    3582         final byte[] multiple = new byte[limit];
    3583         System.arraycopy(value, 0, multiple, 0, len);
    3584         int copied = len;
    3585         for (; copied < limit - copied; copied <<= 1) {
    3586             System.arraycopy(multiple, 0, multiple, copied, copied);
    3587         }
    3588         System.arraycopy(multiple, 0, multiple, copied, limit - copied);
    3589         return new String(multiple, coder);
    3590     }
    3591
    3592     ////////////////////////////////////////////////////////////////
    3593
    3594     /**
    3595      * Copy character bytes from this string into dst starting at dstBegin.
    3596      * This method doesn't perform any range checking.
    3597      *
    3598      * Invoker guarantees: dst is in UTF16 (inflate itself for asb), if two
    3599      * coders are different, and dst is big enough (range check)
    3600      *
    3601      * @param dstBegin  the char index, not offset of byte[]
    3602      * @param coder     the coder of dst[]
    3603      */
    3604     void getBytes(byte dst[], int dstBegin, byte coder) {
    3605         if (coder() == coder) {
    3606             System.arraycopy(value, 0, dst, dstBegin << coder, value.length);
    3607         } else {    // this.coder == LATIN && coder == UTF16
    3608             StringLatin1.inflate(value, 0, dst, dstBegin, value.length);
    3609         }
    3610     }
    3611
    3612     /*
    3613      * Package private constructor. Trailing Void argument is there for
    3614      * disambiguating it against other (public) constructors.
    3615      *
    3616      * Stores the char[] value into a byte[] that each byte represents
    3617      * the8 low-order bits of the corresponding character, if the char[]
    3618      * contains only latin1 character. Or a byte[] that stores all
    3619      * characters in their byte sequences defined by the {@code StringUTF16}.
    3620      */
    3621     String(char[] value, int off, int len, Void sig) {
    3622         if (len == 0) {
    3623             this.value = "".value;
    3624             this.coder = "".coder;
    3625             return;
    3626         }
    3627         if (COMPACT_STRINGS) {
    3628             byte[] val = StringUTF16.compress(value, off, len);
    3629             if (val != null) {
    3630                 this.value = val;
    3631                 this.coder = LATIN1;
    3632                 return;
    3633             }
    3634         }
    3635         this.coder = UTF16;
    3636         this.value = StringUTF16.toBytes(value, off, len);
    3637     }
    3638
    3639     /*
    3640      * Package private constructor. Trailing Void argument is there for
    3641      * disambiguating it against other (public) constructors.
    3642      */
    3643     String(AbstractStringBuilder asb, Void sig) {
    3644         byte[] val = asb.getValue();
    3645         int length = asb.length();
    3646         if (asb.isLatin1()) {
    3647             this.coder = LATIN1;
    3648             this.value = Arrays.copyOfRange(val, 0, length);
    3649         } else {
    3650             if (COMPACT_STRINGS) {
    3651                 byte[] buf = StringUTF16.compress(val, 0, length);
    3652                 if (buf != null) {
    3653                     this.coder = LATIN1;
    3654                     this.value = buf;
    3655                     return;
    3656                 }
    3657             }
    3658             this.coder = UTF16;
    3659             this.value = Arrays.copyOfRange(val, 0, length << 1);
    3660         }
    3661     }
    3662
    3663    /*
    3664     * Package private constructor which shares value array for speed.
    3665     */
    3666     String(byte[] value, byte coder) {
    3667         this.value = value;
    3668         this.coder = coder;
    3669     }
    3670
    3671     byte coder() {
    3672         return COMPACT_STRINGS ? coder : UTF16;
    3673     }
    3674
    3675     byte[] value() {
    3676         return value;
    3677     }
    3678
    3679     boolean isLatin1() {
    3680         return COMPACT_STRINGS && coder == LATIN1;
    3681     }
    3682
    3683     @Native static final byte LATIN1 = 0;
    3684     @Native static final byte UTF16  = 1;
    3685
    3686     /*
    3687      * StringIndexOutOfBoundsException  if {@code index} is
    3688      * negative or greater than or equal to {@code length}.
    3689      */
    3690     static void checkIndex(int index, int length) {
    3691         if (index < 0 || index >= length) {
    3692             throw new StringIndexOutOfBoundsException("index " + index +
    3693                                                       ", length " + length);
    3694         }
    3695     }
    3696
    3697     /*
    3698      * StringIndexOutOfBoundsException  if {@code offset}
    3699      * is negative or greater than {@code length}.
    3700      */
    3701     static void checkOffset(int offset, int length) {
    3702         if (offset < 0 || offset > length) {
    3703             throw new StringIndexOutOfBoundsException("offset " + offset +
    3704                                                       ", length " + length);
    3705         }
    3706     }
    3707
    3708     /*
    3709      * Check {@code offset}, {@code count} against {@code 0} and {@code length}
    3710      * bounds.
    3711      *
    3712      * @throws  StringIndexOutOfBoundsException
    3713      *          If {@code offset} is negative, {@code count} is negative,
    3714      *          or {@code offset} is greater than {@code length - count}
    3715      */
    3716     static void checkBoundsOffCount(int offset, int count, int length) {
    3717         if (offset < 0 || count < 0 || offset > length - count) {
    3718             throw new StringIndexOutOfBoundsException(
    3719                 "offset " + offset + ", count " + count + ", length " + length);
    3720         }
    3721     }
    3722
    3723     /*
    3724      * Check {@code begin}, {@code end} against {@code 0} and {@code length}
    3725      * bounds.
    3726      *
    3727      * @throws  StringIndexOutOfBoundsException
    3728      *          If {@code begin} is negative, {@code begin} is greater than
    3729      *          {@code end}, or {@code end} is greater than {@code length}.
    3730      */
    3731     static void checkBoundsBeginEnd(int begin, int end, int length) {
    3732         if (begin < 0 || begin > end || end > length) {
    3733             throw new StringIndexOutOfBoundsException(
    3734                 "begin " + begin + ", end " + end + ", length " + length);
    3735         }
    3736     }
    3737
    3738     /**
    3739      * Returns the string representation of the {@code codePoint}
    3740      * argument.
    3741      *
    3742      * @param   codePoint a {@code codePoint}.
    3743      * @return  a string of length {@code 1} or {@code 2} containing
    3744      *          as its single character the argument {@code codePoint}.
    3745      * @throws IllegalArgumentException if the specified
    3746      *          {@code codePoint} is not a {@linkplain Character#isValidCodePoint
    3747      *          valid Unicode code point}.
    3748      */
    3749     static String valueOfCodePoint(int codePoint) {
    3750         if (COMPACT_STRINGS && StringLatin1.canEncode(codePoint)) {
    3751             return new String(StringLatin1.toBytes((char)codePoint), LATIN1);
    3752         } else if (Character.isBmpCodePoint(codePoint)) {
    3753             return new String(StringUTF16.toBytes((char)codePoint), UTF16);
    3754         } else if (Character.isSupplementaryCodePoint(codePoint)) {
    3755             return new String(StringUTF16.toBytesSupplementary(codePoint), UTF16);
    3756         }
    3757
    3758         throw new IllegalArgumentException(
    3759             format("Not a valid Unicode code point: 0x%X", codePoint));
    3760     }
    3761
    3762     /**
    3763      * Returns an {@link Optional} containing the nominal descriptor for this
    3764      * instance, which is the instance itself.
    3765      *
    3766      * @return an {@link Optional} describing the {@linkplain String} instance
    3767      * @since 12
    3768      */
    3769     @Override
    3770     public Optional<String> describeConstable() {
    3771         return Optional.of(this);
    3772     }
    3773
    3774     /**
    3775      * Resolves this instance as a {@link ConstantDesc}, the result of which is
    3776      * the instance itself.
    3777      *
    3778      * @param lookup ignored
    3779      * @return the {@linkplain String} instance
    3780      * @since 12
    3781      */
    3782     @Override
    3783     public String resolveConstantDesc(MethodHandles.Lookup lookup) {
    3784         return this;
    3785     }
    3786
    3787 }