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.Matcher;
  47 import java.util.regex.Pattern;
  48 import java.util.regex.PatternSyntaxException;
  49 import java.util.stream.Collectors;
  50 import java.util.stream.IntStream;
  51 import java.util.stream.Stream;
  52 import java.util.stream.StreamSupport;
  53 import jdk.internal.HotSpotIntrinsicCandidate;
  54 import jdk.internal.vm.annotation.Stable;
  55 
  56 import static java.util.function.Predicate.not;
  57 
  58 /**
  59  * The {@code String} class represents character strings. All
  60  * string literals in Java programs, such as {@code "abc"}, are
  61  * implemented as instances of this class.
  62  * <p>
  63  * Strings are constant; their values cannot be changed after they
  64  * are created. String buffers support mutable strings.
  65  * Because String objects are immutable they can be shared. For example:
  66  * <blockquote><pre>
  67  *     String str = "abc";
  68  * </pre></blockquote><p>
  69  * is equivalent to:
  70  * <blockquote><pre>
  71  *     char data[] = {'a', 'b', 'c'};
  72  *     String str = new String(data);
  73  * </pre></blockquote><p>
  74  * Here are some more examples of how strings can be used:
  75  * <blockquote><pre>
  76  *     System.out.println("abc");
  77  *     String cde = "cde";
  78  *     System.out.println("abc" + cde);
  79  *     String c = "abc".substring(2, 3);
  80  *     String d = cde.substring(1, 2);
  81  * </pre></blockquote>
  82  * <p>
  83  * The class {@code String} includes methods for examining
  84  * individual characters of the sequence, for comparing strings, for
  85  * searching strings, for extracting substrings, and for creating a
  86  * copy of a string with all characters translated to uppercase or to
  87  * lowercase. Case mapping is based on the Unicode Standard version
  88  * specified by the {@link java.lang.Character Character} class.
  89  * <p>
  90  * The Java language provides special support for the string
  91  * concatenation operator (&nbsp;+&nbsp;), and for conversion of
  92  * other objects to strings. For additional information on string
  93  * concatenation and conversion, see <i>The Java&trade; Language Specification</i>.
  94  *
  95  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
  96  * or method in this class will cause a {@link NullPointerException} to be
  97  * thrown.
  98  *
  99  * <p>A {@code String} represents a string in the UTF-16 format
 100  * in which <em>supplementary characters</em> are represented by <em>surrogate
 101  * pairs</em> (see the section <a href="Character.html#unicode">Unicode
 102  * Character Representations</a> in the {@code Character} class for
 103  * more information).
 104  * Index values refer to {@code char} code units, so a supplementary
 105  * character uses two positions in a {@code String}.
 106  * <p>The {@code String} class provides methods for dealing with
 107  * Unicode code points (i.e., characters), in addition to those for
 108  * dealing with Unicode code units (i.e., {@code char} values).
 109  *
 110  * <p>Unless otherwise noted, methods for comparing Strings do not take locale
 111  * into account.  The {@link java.text.Collator} class provides methods for
 112  * finer-grain, locale-sensitive String comparison.
 113  *
 114  * @implNote The implementation of the string concatenation operator is left to
 115  * the discretion of a Java compiler, as long as the compiler ultimately conforms
 116  * to <i>The Java&trade; Language Specification</i>. For example, the {@code javac} compiler
 117  * may implement the operator with {@code StringBuffer}, {@code StringBuilder},
 118  * or {@code java.lang.invoke.StringConcatFactory} depending on the JDK version. The
 119  * implementation of string conversion is typically through the method {@code toString},
 120  * defined by {@code Object} and inherited by all classes in Java.
 121  *
 122  * @author  Lee Boynton
 123  * @author  Arthur van Hoff
 124  * @author  Martin Buchholz
 125  * @author  Ulf Zibis
 126  * @see     java.lang.Object#toString()
 127  * @see     java.lang.StringBuffer
 128  * @see     java.lang.StringBuilder
 129  * @see     java.nio.charset.Charset
 130  * @since   1.0
 131  * @jls     15.18.1 String Concatenation Operator +
 132  */
 133 
 134 public final class String
 135     implements java.io.Serializable, Comparable<String>, CharSequence,
 136                Constable, ConstantDesc {
 137 
 138     /**
 139      * The value is used for character storage.
 140      *
 141      * @implNote This field is trusted by the VM, and is a subject to
 142      * constant folding if String instance is constant. Overwriting this
 143      * field after construction will cause problems.
 144      *
 145      * Additionally, it is marked with {@link Stable} to trust the contents
 146      * of the array. No other facility in JDK provides this functionality (yet).
 147      * {@link Stable} is safe here, because value is never null.
 148      */
 149     @Stable
 150     private final byte[] value;
 151 
 152     /**
 153      * The identifier of the encoding used to encode the bytes in
 154      * {@code value}. The supported values in this implementation are
 155      *
 156      * LATIN1
 157      * UTF16
 158      *
 159      * @implNote This field is trusted by the VM, and is a subject to
 160      * constant folding if String instance is constant. Overwriting this
 161      * field after construction will cause problems.
 162      */
 163     private final byte coder;
 164 
 165     /** Cache the hash code for the string */
 166     private int hash; // Default to 0
 167 
 168     /**
 169      * Cache if the hash has been calculated as actually being zero, enabling
 170      * us to avoid recalculating this.
 171      */
 172     private boolean hashIsZero; // Default to false;
 173 
 174     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 175     @java.io.Serial
 176     private static final long serialVersionUID = -6849794470754667710L;
 177 
 178     /**
 179      * If String compaction is disabled, the bytes in {@code value} are
 180      * always encoded in UTF16.
 181      *
 182      * For methods with several possible implementation paths, when String
 183      * compaction is disabled, only one code path is taken.
 184      *
 185      * The instance field value is generally opaque to optimizing JIT
 186      * compilers. Therefore, in performance-sensitive place, an explicit
 187      * check of the static boolean {@code COMPACT_STRINGS} is done first
 188      * before checking the {@code coder} field since the static boolean
 189      * {@code COMPACT_STRINGS} would be constant folded away by an
 190      * optimizing JIT compiler. The idioms for these cases are as follows.
 191      *
 192      * For code such as:
 193      *
 194      *    if (coder == LATIN1) { ... }
 195      *
 196      * can be written more optimally as
 197      *
 198      *    if (coder() == LATIN1) { ... }
 199      *
 200      * or:
 201      *
 202      *    if (COMPACT_STRINGS && coder == LATIN1) { ... }
 203      *
 204      * An optimizing JIT compiler can fold the above conditional as:
 205      *
 206      *    COMPACT_STRINGS == true  => if (coder == LATIN1) { ... }
 207      *    COMPACT_STRINGS == false => if (false)           { ... }
 208      *
 209      * @implNote
 210      * The actual value for this field is injected by JVM. The static
 211      * initialization block is used to set the value here to communicate
 212      * that this static final field is not statically foldable, and to
 213      * avoid any possible circular dependency during vm initialization.
 214      */
 215     static final boolean COMPACT_STRINGS;
 216 
 217     static {
 218         COMPACT_STRINGS = true;
 219     }
 220 
 221     /**
 222      * Class String is special cased within the Serialization Stream Protocol.
 223      *
 224      * A String instance is written into an ObjectOutputStream according to
 225      * <a href="{@docRoot}/../specs/serialization/protocol.html#stream-elements">
 226      * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
 227      */
 228     @java.io.Serial
 229     private static final ObjectStreamField[] serialPersistentFields =
 230         new ObjectStreamField[0];
 231 
 232     /**
 233      * Initializes a newly created {@code String} object so that it represents
 234      * an empty character sequence.  Note that use of this constructor is
 235      * unnecessary since Strings are immutable.
 236      */
 237     public String() {
 238         this.value = "".value;
 239         this.coder = "".coder;
 240     }
 241 
 242     /**
 243      * Initializes a newly created {@code String} object so that it represents
 244      * the same sequence of characters as the argument; in other words, the
 245      * newly created string is a copy of the argument string. Unless an
 246      * explicit copy of {@code original} is needed, use of this constructor is
 247      * unnecessary since Strings are immutable.
 248      *
 249      * @param  original
 250      *         A {@code String}
 251      */
 252     @HotSpotIntrinsicCandidate
 253     public String(String original) {
 254         this.value = original.value;
 255         this.coder = original.coder;
 256         this.hash = original.hash;
 257     }
 258 
 259     /**
 260      * Allocates a new {@code String} so that it represents the sequence of
 261      * characters currently contained in the character array argument. The
 262      * contents of the character array are copied; subsequent modification of
 263      * the character array does not affect the newly created string.
 264      *
 265      * @param  value
 266      *         The initial value of the string
 267      */
 268     public String(char value[]) {
 269         this(value, 0, value.length, null);
 270     }
 271 
 272     /**
 273      * Allocates a new {@code String} that contains characters from a subarray
 274      * of the character array argument. The {@code offset} argument is the
 275      * index of the first character of the subarray and the {@code count}
 276      * argument specifies the length of the subarray. The contents of the
 277      * subarray are copied; subsequent modification of the character array does
 278      * not affect the newly created string.
 279      *
 280      * @param  value
 281      *         Array that is the source of characters
 282      *
 283      * @param  offset
 284      *         The initial offset
 285      *
 286      * @param  count
 287      *         The length
 288      *
 289      * @throws  IndexOutOfBoundsException
 290      *          If {@code offset} is negative, {@code count} is negative, or
 291      *          {@code offset} is greater than {@code value.length - count}
 292      */
 293     public String(char value[], int offset, int count) {
 294         this(value, offset, count, rangeCheck(value, offset, count));
 295     }
 296 
 297     private static Void rangeCheck(char[] value, int offset, int count) {
 298         checkBoundsOffCount(offset, count, value.length);
 299         return null;
 300     }
 301 
 302     /**
 303      * Allocates a new {@code String} that contains characters from a subarray
 304      * of the <a href="Character.html#unicode">Unicode code point</a> array
 305      * argument.  The {@code offset} argument is the index of the first code
 306      * point of the subarray and the {@code count} argument specifies the
 307      * length of the subarray.  The contents of the subarray are converted to
 308      * {@code char}s; subsequent modification of the {@code int} array does not
 309      * affect the newly created string.
 310      *
 311      * @param  codePoints
 312      *         Array that is the source of Unicode code points
 313      *
 314      * @param  offset
 315      *         The initial offset
 316      *
 317      * @param  count
 318      *         The length
 319      *
 320      * @throws  IllegalArgumentException
 321      *          If any invalid Unicode code point is found in {@code
 322      *          codePoints}
 323      *
 324      * @throws  IndexOutOfBoundsException
 325      *          If {@code offset} is negative, {@code count} is negative, or
 326      *          {@code offset} is greater than {@code codePoints.length - count}
 327      *
 328      * @since  1.5
 329      */
 330     public String(int[] codePoints, int offset, int count) {
 331         checkBoundsOffCount(offset, count, codePoints.length);
 332         if (count == 0) {
 333             this.value = "".value;
 334             this.coder = "".coder;
 335             return;
 336         }
 337         if (COMPACT_STRINGS) {
 338             byte[] val = StringLatin1.toBytes(codePoints, offset, count);
 339             if (val != null) {
 340                 this.coder = LATIN1;
 341                 this.value = val;
 342                 return;
 343             }
 344         }
 345         this.coder = UTF16;
 346         this.value = StringUTF16.toBytes(codePoints, offset, count);
 347     }
 348 
 349     /**
 350      * Allocates a new {@code String} constructed from a subarray of an array
 351      * of 8-bit integer values.
 352      *
 353      * <p> The {@code offset} argument is the index of the first byte of the
 354      * subarray, and the {@code count} argument specifies the length of the
 355      * subarray.
 356      *
 357      * <p> Each {@code byte} in the subarray is converted to a {@code char} as
 358      * specified in the {@link #String(byte[],int) String(byte[],int)} constructor.
 359      *
 360      * @deprecated This method does not properly convert bytes into characters.
 361      * As of JDK&nbsp;1.1, the preferred way to do this is via the
 362      * {@code String} constructors that take a {@link
 363      * java.nio.charset.Charset}, charset name, or that use the platform's
 364      * default charset.
 365      *
 366      * @param  ascii
 367      *         The bytes to be converted to characters
 368      *
 369      * @param  hibyte
 370      *         The top 8 bits of each 16-bit Unicode code unit
 371      *
 372      * @param  offset
 373      *         The initial offset
 374      * @param  count
 375      *         The length
 376      *
 377      * @throws  IndexOutOfBoundsException
 378      *          If {@code offset} is negative, {@code count} is negative, or
 379      *          {@code offset} is greater than {@code ascii.length - count}
 380      *
 381      * @see  #String(byte[], int)
 382      * @see  #String(byte[], int, int, java.lang.String)
 383      * @see  #String(byte[], int, int, java.nio.charset.Charset)
 384      * @see  #String(byte[], int, int)
 385      * @see  #String(byte[], java.lang.String)
 386      * @see  #String(byte[], java.nio.charset.Charset)
 387      * @see  #String(byte[])
 388      */
 389     @Deprecated(since="1.1")
 390     public String(byte ascii[], int hibyte, int offset, int count) {
 391         checkBoundsOffCount(offset, count, ascii.length);
 392         if (count == 0) {
 393             this.value = "".value;
 394             this.coder = "".coder;
 395             return;
 396         }
 397         if (COMPACT_STRINGS && (byte)hibyte == 0) {
 398             this.value = Arrays.copyOfRange(ascii, offset, offset + count);
 399             this.coder = LATIN1;
 400         } else {
 401             hibyte <<= 8;
 402             byte[] val = StringUTF16.newBytesFor(count);
 403             for (int i = 0; i < count; i++) {
 404                 StringUTF16.putChar(val, i, hibyte | (ascii[offset++] & 0xff));
 405             }
 406             this.value = val;
 407             this.coder = UTF16;
 408         }
 409     }
 410 
 411     /**
 412      * Allocates a new {@code String} containing characters constructed from
 413      * an array of 8-bit integer values. Each character <i>c</i> in the
 414      * resulting string is constructed from the corresponding component
 415      * <i>b</i> in the byte array such that:
 416      *
 417      * <blockquote><pre>
 418      *     <b><i>c</i></b> == (char)(((hibyte &amp; 0xff) &lt;&lt; 8)
 419      *                         | (<b><i>b</i></b> &amp; 0xff))
 420      * </pre></blockquote>
 421      *
 422      * @deprecated  This method does not properly convert bytes into
 423      * characters.  As of JDK&nbsp;1.1, the preferred way to do this is via the
 424      * {@code String} constructors that take a {@link
 425      * java.nio.charset.Charset}, charset name, or that use the platform's
 426      * default charset.
 427      *
 428      * @param  ascii
 429      *         The bytes to be converted to characters
 430      *
 431      * @param  hibyte
 432      *         The top 8 bits of each 16-bit Unicode code unit
 433      *
 434      * @see  #String(byte[], int, int, java.lang.String)
 435      * @see  #String(byte[], int, int, java.nio.charset.Charset)
 436      * @see  #String(byte[], int, int)
 437      * @see  #String(byte[], java.lang.String)
 438      * @see  #String(byte[], java.nio.charset.Charset)
 439      * @see  #String(byte[])
 440      */
 441     @Deprecated(since="1.1")
 442     public String(byte ascii[], int hibyte) {
 443         this(ascii, hibyte, 0, ascii.length);
 444     }
 445 
 446     /**
 447      * Constructs a new {@code String} by decoding the specified subarray of
 448      * bytes using the specified charset.  The length of the new {@code String}
 449      * is a function of the charset, and hence may not be equal to the length
 450      * of the subarray.
 451      *
 452      * <p> The behavior of this constructor when the given bytes are not valid
 453      * in the given charset is unspecified.  The {@link
 454      * java.nio.charset.CharsetDecoder} class should be used when more control
 455      * over the decoding process is required.
 456      *
 457      * @param  bytes
 458      *         The bytes to be decoded into characters
 459      *
 460      * @param  offset
 461      *         The index of the first byte to decode
 462      *
 463      * @param  length
 464      *         The number of bytes to decode
 465      *
 466      * @param  charsetName
 467      *         The name of a supported {@linkplain java.nio.charset.Charset
 468      *         charset}
 469      *
 470      * @throws  UnsupportedEncodingException
 471      *          If the named charset is not supported
 472      *
 473      * @throws  IndexOutOfBoundsException
 474      *          If {@code offset} is negative, {@code length} is negative, or
 475      *          {@code offset} is greater than {@code bytes.length - length}
 476      *
 477      * @since  1.1
 478      */
 479     public String(byte bytes[], int offset, int length, String charsetName)
 480             throws UnsupportedEncodingException {
 481         if (charsetName == null)
 482             throw new NullPointerException("charsetName");
 483         checkBoundsOffCount(offset, length, bytes.length);
 484         StringCoding.Result ret =
 485             StringCoding.decode(charsetName, bytes, offset, length);
 486         this.value = ret.value;
 487         this.coder = ret.coder;
 488     }
 489 
 490     /**
 491      * Constructs a new {@code String} by decoding the specified subarray of
 492      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
 493      * The length of the new {@code String} is a function of the charset, and
 494      * hence may not be equal to the length of the subarray.
 495      *
 496      * <p> This method always replaces malformed-input and unmappable-character
 497      * sequences with this charset's default replacement string.  The {@link
 498      * java.nio.charset.CharsetDecoder} class should be used when more control
 499      * over the decoding process is required.
 500      *
 501      * @param  bytes
 502      *         The bytes to be decoded into characters
 503      *
 504      * @param  offset
 505      *         The index of the first byte to decode
 506      *
 507      * @param  length
 508      *         The number of bytes to decode
 509      *
 510      * @param  charset
 511      *         The {@linkplain java.nio.charset.Charset charset} to be used to
 512      *         decode the {@code bytes}
 513      *
 514      * @throws  IndexOutOfBoundsException
 515      *          If {@code offset} is negative, {@code length} is negative, or
 516      *          {@code offset} is greater than {@code bytes.length - length}
 517      *
 518      * @since  1.6
 519      */
 520     public String(byte bytes[], int offset, int length, Charset charset) {
 521         if (charset == null)
 522             throw new NullPointerException("charset");
 523         checkBoundsOffCount(offset, length, bytes.length);
 524         StringCoding.Result ret =
 525             StringCoding.decode(charset, bytes, offset, length);
 526         this.value = ret.value;
 527         this.coder = ret.coder;
 528     }
 529 
 530     /**
 531      * Constructs a new {@code String} by decoding the specified array of bytes
 532      * using the specified {@linkplain java.nio.charset.Charset charset}.  The
 533      * length of the new {@code String} is a function of the charset, and hence
 534      * may not be equal to the length of the byte array.
 535      *
 536      * <p> The behavior of this constructor when the given bytes are not valid
 537      * in the given charset is unspecified.  The {@link
 538      * java.nio.charset.CharsetDecoder} class should be used when more control
 539      * over the decoding process is required.
 540      *
 541      * @param  bytes
 542      *         The bytes to be decoded into characters
 543      *
 544      * @param  charsetName
 545      *         The name of a supported {@linkplain java.nio.charset.Charset
 546      *         charset}
 547      *
 548      * @throws  UnsupportedEncodingException
 549      *          If the named charset is not supported
 550      *
 551      * @since  1.1
 552      */
 553     public String(byte bytes[], String charsetName)
 554             throws UnsupportedEncodingException {
 555         this(bytes, 0, bytes.length, charsetName);
 556     }
 557 
 558     /**
 559      * Constructs a new {@code String} by decoding the specified array of
 560      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
 561      * The length of the new {@code String} is a function of the charset, and
 562      * hence may not be equal to the length of the byte array.
 563      *
 564      * <p> This method always replaces malformed-input and unmappable-character
 565      * sequences with this charset's default replacement string.  The {@link
 566      * java.nio.charset.CharsetDecoder} class should be used when more control
 567      * over the decoding process is required.
 568      *
 569      * @param  bytes
 570      *         The bytes to be decoded into characters
 571      *
 572      * @param  charset
 573      *         The {@linkplain java.nio.charset.Charset charset} to be used to
 574      *         decode the {@code bytes}
 575      *
 576      * @since  1.6
 577      */
 578     public String(byte bytes[], Charset charset) {
 579         this(bytes, 0, bytes.length, charset);
 580     }
 581 
 582     /**
 583      * Constructs a new {@code String} by decoding the specified subarray of
 584      * bytes using the platform's default charset.  The length of the new
 585      * {@code String} is a function of the charset, and hence may not be equal
 586      * to the length of the subarray.
 587      *
 588      * <p> The behavior of this constructor when the given bytes are not valid
 589      * in the default charset is unspecified.  The {@link
 590      * java.nio.charset.CharsetDecoder} class should be used when more control
 591      * over the decoding process is required.
 592      *
 593      * @param  bytes
 594      *         The bytes to be decoded into characters
 595      *
 596      * @param  offset
 597      *         The index of the first byte to decode
 598      *
 599      * @param  length
 600      *         The number of bytes to decode
 601      *
 602      * @throws  IndexOutOfBoundsException
 603      *          If {@code offset} is negative, {@code length} is negative, or
 604      *          {@code offset} is greater than {@code bytes.length - length}
 605      *
 606      * @since  1.1
 607      */
 608     public String(byte bytes[], int offset, int length) {
 609         checkBoundsOffCount(offset, length, bytes.length);
 610         StringCoding.Result ret = StringCoding.decode(bytes, offset, length);
 611         this.value = ret.value;
 612         this.coder = ret.coder;
 613     }
 614 
 615     /**
 616      * Constructs a new {@code String} by decoding the specified array of bytes
 617      * using the platform's default charset.  The length of the new {@code
 618      * String} is a function of the charset, and hence may not be equal to the
 619      * length of the byte array.
 620      *
 621      * <p> The behavior of this constructor when the given bytes are not valid
 622      * in the default charset is unspecified.  The {@link
 623      * java.nio.charset.CharsetDecoder} class should be used when more control
 624      * over the decoding process is required.
 625      *
 626      * @param  bytes
 627      *         The bytes to be decoded into characters
 628      *
 629      * @since  1.1
 630      */
 631     public String(byte[] bytes) {
 632         this(bytes, 0, bytes.length);
 633     }
 634 
 635     /**
 636      * Allocates a new string that contains the sequence of characters
 637      * currently contained in the string buffer argument. The contents of the
 638      * string buffer are copied; subsequent modification of the string buffer
 639      * does not affect the newly created string.
 640      *
 641      * @param  buffer
 642      *         A {@code StringBuffer}
 643      */
 644     public String(StringBuffer buffer) {
 645         this(buffer.toString());
 646     }
 647 
 648     /**
 649      * Allocates a new string that contains the sequence of characters
 650      * currently contained in the string builder argument. The contents of the
 651      * string builder are copied; subsequent modification of the string builder
 652      * does not affect the newly created string.
 653      *
 654      * <p> This constructor is provided to ease migration to {@code
 655      * StringBuilder}. Obtaining a string from a string builder via the {@code
 656      * toString} method is likely to run faster and is generally preferred.
 657      *
 658      * @param   builder
 659      *          A {@code StringBuilder}
 660      *
 661      * @since  1.5
 662      */
 663     public String(StringBuilder builder) {
 664         this(builder, null);
 665     }
 666 
 667     /**
 668      * Returns the length of this string.
 669      * The length is equal to the number of <a href="Character.html#unicode">Unicode
 670      * code units</a> in the string.
 671      *
 672      * @return  the length of the sequence of characters represented by this
 673      *          object.
 674      */
 675     public int length() {
 676         return value.length >> coder();
 677     }
 678 
 679     /**
 680      * Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
 681      *
 682      * @return {@code true} if {@link #length()} is {@code 0}, otherwise
 683      * {@code false}
 684      *
 685      * @since 1.6
 686      */
 687     @Override
 688     public boolean isEmpty() {
 689         return value.length == 0;
 690     }
 691 
 692     /**
 693      * Returns the {@code char} value at the
 694      * specified index. An index ranges from {@code 0} to
 695      * {@code length() - 1}. The first {@code char} value of the sequence
 696      * is at index {@code 0}, the next at index {@code 1},
 697      * and so on, as for array indexing.
 698      *
 699      * <p>If the {@code char} value specified by the index is a
 700      * <a href="Character.html#unicode">surrogate</a>, the surrogate
 701      * value is returned.
 702      *
 703      * @param      index   the index of the {@code char} value.
 704      * @return     the {@code char} value at the specified index of this string.
 705      *             The first {@code char} value is at index {@code 0}.
 706      * @throws     IndexOutOfBoundsException  if the {@code index}
 707      *             argument is negative or not less than the length of this
 708      *             string.
 709      */
 710     public char charAt(int index) {
 711         if (isLatin1()) {
 712             return StringLatin1.charAt(value, index);
 713         } else {
 714             return StringUTF16.charAt(value, index);
 715         }
 716     }
 717 
 718     /**
 719      * Returns the character (Unicode code point) at the specified
 720      * index. The index refers to {@code char} values
 721      * (Unicode code units) and ranges from {@code 0} to
 722      * {@link #length()}{@code  - 1}.
 723      *
 724      * <p> If the {@code char} value specified at the given index
 725      * is in the high-surrogate range, the following index is less
 726      * than the length of this {@code String}, and the
 727      * {@code char} value at the following index is in the
 728      * low-surrogate range, then the supplementary code point
 729      * corresponding to this surrogate pair is returned. Otherwise,
 730      * the {@code char} value at the given index is returned.
 731      *
 732      * @param      index the index to the {@code char} values
 733      * @return     the code point value of the character at the
 734      *             {@code index}
 735      * @throws     IndexOutOfBoundsException  if the {@code index}
 736      *             argument is negative or not less than the length of this
 737      *             string.
 738      * @since      1.5
 739      */
 740     public int codePointAt(int index) {
 741         if (isLatin1()) {
 742             checkIndex(index, value.length);
 743             return value[index] & 0xff;
 744         }
 745         int length = value.length >> 1;
 746         checkIndex(index, length);
 747         return StringUTF16.codePointAt(value, index, length);
 748     }
 749 
 750     /**
 751      * Returns the character (Unicode code point) before the specified
 752      * index. The index refers to {@code char} values
 753      * (Unicode code units) and ranges from {@code 1} to {@link
 754      * CharSequence#length() length}.
 755      *
 756      * <p> If the {@code char} value at {@code (index - 1)}
 757      * is in the low-surrogate range, {@code (index - 2)} is not
 758      * negative, and the {@code char} value at {@code (index -
 759      * 2)} is in the high-surrogate range, then the
 760      * supplementary code point value of the surrogate pair is
 761      * returned. If the {@code char} value at {@code index -
 762      * 1} is an unpaired low-surrogate or a high-surrogate, the
 763      * surrogate value is returned.
 764      *
 765      * @param     index the index following the code point that should be returned
 766      * @return    the Unicode code point value before the given index.
 767      * @throws    IndexOutOfBoundsException if the {@code index}
 768      *            argument is less than 1 or greater than the length
 769      *            of this string.
 770      * @since     1.5
 771      */
 772     public int codePointBefore(int index) {
 773         int i = index - 1;
 774         if (i < 0 || i >= length()) {
 775             throw new StringIndexOutOfBoundsException(index);
 776         }
 777         if (isLatin1()) {
 778             return (value[i] & 0xff);
 779         }
 780         return StringUTF16.codePointBefore(value, index);
 781     }
 782 
 783     /**
 784      * Returns the number of Unicode code points in the specified text
 785      * range of this {@code String}. The text range begins at the
 786      * specified {@code beginIndex} and extends to the
 787      * {@code char} at index {@code endIndex - 1}. Thus the
 788      * length (in {@code char}s) of the text range is
 789      * {@code endIndex-beginIndex}. Unpaired surrogates within
 790      * the text range count as one code point each.
 791      *
 792      * @param beginIndex the index to the first {@code char} of
 793      * the text range.
 794      * @param endIndex the index after the last {@code char} of
 795      * the text range.
 796      * @return the number of Unicode code points in the specified text
 797      * range
 798      * @throws    IndexOutOfBoundsException if the
 799      * {@code beginIndex} is negative, or {@code endIndex}
 800      * is larger than the length of this {@code String}, or
 801      * {@code beginIndex} is larger than {@code endIndex}.
 802      * @since  1.5
 803      */
 804     public int codePointCount(int beginIndex, int endIndex) {
 805         if (beginIndex < 0 || beginIndex > endIndex ||
 806             endIndex > length()) {
 807             throw new IndexOutOfBoundsException();
 808         }
 809         if (isLatin1()) {
 810             return endIndex - beginIndex;
 811         }
 812         return StringUTF16.codePointCount(value, beginIndex, endIndex);
 813     }
 814 
 815     /**
 816      * Returns the index within this {@code String} that is
 817      * offset from the given {@code index} by
 818      * {@code codePointOffset} code points. Unpaired surrogates
 819      * within the text range given by {@code index} and
 820      * {@code codePointOffset} count as one code point each.
 821      *
 822      * @param index the index to be offset
 823      * @param codePointOffset the offset in code points
 824      * @return the index within this {@code String}
 825      * @throws    IndexOutOfBoundsException if {@code index}
 826      *   is negative or larger then the length of this
 827      *   {@code String}, or if {@code codePointOffset} is positive
 828      *   and the substring starting with {@code index} has fewer
 829      *   than {@code codePointOffset} code points,
 830      *   or if {@code codePointOffset} is negative and the substring
 831      *   before {@code index} has fewer than the absolute value
 832      *   of {@code codePointOffset} code points.
 833      * @since 1.5
 834      */
 835     public int offsetByCodePoints(int index, int codePointOffset) {
 836         if (index < 0 || index > length()) {
 837             throw new IndexOutOfBoundsException();
 838         }
 839         return Character.offsetByCodePoints(this, index, codePointOffset);
 840     }
 841 
 842     /**
 843      * Copies characters from this string into the destination character
 844      * array.
 845      * <p>
 846      * The first character to be copied is at index {@code srcBegin};
 847      * the last character to be copied is at index {@code srcEnd-1}
 848      * (thus the total number of characters to be copied is
 849      * {@code srcEnd-srcBegin}). The characters are copied into the
 850      * subarray of {@code dst} starting at index {@code dstBegin}
 851      * and ending at index:
 852      * <blockquote><pre>
 853      *     dstBegin + (srcEnd-srcBegin) - 1
 854      * </pre></blockquote>
 855      *
 856      * @param      srcBegin   index of the first character in the string
 857      *                        to copy.
 858      * @param      srcEnd     index after the last character in the string
 859      *                        to copy.
 860      * @param      dst        the destination array.
 861      * @param      dstBegin   the start offset in the destination array.
 862      * @throws    IndexOutOfBoundsException If any of the following
 863      *            is true:
 864      *            <ul><li>{@code srcBegin} is negative.
 865      *            <li>{@code srcBegin} is greater than {@code srcEnd}
 866      *            <li>{@code srcEnd} is greater than the length of this
 867      *                string
 868      *            <li>{@code dstBegin} is negative
 869      *            <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
 870      *                {@code dst.length}</ul>
 871      */
 872     public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
 873         checkBoundsBeginEnd(srcBegin, srcEnd, length());
 874         checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
 875         if (isLatin1()) {
 876             StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
 877         } else {
 878             StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
 879         }
 880     }
 881 
 882     /**
 883      * Copies characters from this string into the destination byte array. Each
 884      * byte receives the 8 low-order bits of the corresponding character. The
 885      * eight high-order bits of each character are not copied and do not
 886      * participate in the transfer in any way.
 887      *
 888      * <p> The first character to be copied is at index {@code srcBegin}; the
 889      * last character to be copied is at index {@code srcEnd-1}.  The total
 890      * number of characters to be copied is {@code srcEnd-srcBegin}. The
 891      * characters, converted to bytes, are copied into the subarray of {@code
 892      * dst} starting at index {@code dstBegin} and ending at index:
 893      *
 894      * <blockquote><pre>
 895      *     dstBegin + (srcEnd-srcBegin) - 1
 896      * </pre></blockquote>
 897      *
 898      * @deprecated  This method does not properly convert characters into
 899      * bytes.  As of JDK&nbsp;1.1, the preferred way to do this is via the
 900      * {@link #getBytes()} method, which uses the platform's default charset.
 901      *
 902      * @param  srcBegin
 903      *         Index of the first character in the string to copy
 904      *
 905      * @param  srcEnd
 906      *         Index after the last character in the string to copy
 907      *
 908      * @param  dst
 909      *         The destination array
 910      *
 911      * @param  dstBegin
 912      *         The start offset in the destination array
 913      *
 914      * @throws  IndexOutOfBoundsException
 915      *          If any of the following is true:
 916      *          <ul>
 917      *            <li> {@code srcBegin} is negative
 918      *            <li> {@code srcBegin} is greater than {@code srcEnd}
 919      *            <li> {@code srcEnd} is greater than the length of this String
 920      *            <li> {@code dstBegin} is negative
 921      *            <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
 922      *                 dst.length}
 923      *          </ul>
 924      */
 925     @Deprecated(since="1.1")
 926     public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
 927         checkBoundsBeginEnd(srcBegin, srcEnd, length());
 928         Objects.requireNonNull(dst);
 929         checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
 930         if (isLatin1()) {
 931             StringLatin1.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
 932         } else {
 933             StringUTF16.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
 934         }
 935     }
 936 
 937     /**
 938      * Encodes this {@code String} into a sequence of bytes using the named
 939      * charset, storing the result into a new byte array.
 940      *
 941      * <p> The behavior of this method when this string cannot be encoded in
 942      * the given charset is unspecified.  The {@link
 943      * java.nio.charset.CharsetEncoder} class should be used when more control
 944      * over the encoding process is required.
 945      *
 946      * @param  charsetName
 947      *         The name of a supported {@linkplain java.nio.charset.Charset
 948      *         charset}
 949      *
 950      * @return  The resultant byte array
 951      *
 952      * @throws  UnsupportedEncodingException
 953      *          If the named charset is not supported
 954      *
 955      * @since  1.1
 956      */
 957     public byte[] getBytes(String charsetName)
 958             throws UnsupportedEncodingException {
 959         if (charsetName == null) throw new NullPointerException();
 960         return StringCoding.encode(charsetName, coder(), value);
 961     }
 962 
 963     /**
 964      * Encodes this {@code String} into a sequence of bytes using the given
 965      * {@linkplain java.nio.charset.Charset charset}, storing the result into a
 966      * new byte array.
 967      *
 968      * <p> This method always replaces malformed-input and unmappable-character
 969      * sequences with this charset's default replacement byte array.  The
 970      * {@link java.nio.charset.CharsetEncoder} class should be used when more
 971      * control over the encoding process is required.
 972      *
 973      * @param  charset
 974      *         The {@linkplain java.nio.charset.Charset} to be used to encode
 975      *         the {@code String}
 976      *
 977      * @return  The resultant byte array
 978      *
 979      * @since  1.6
 980      */
 981     public byte[] getBytes(Charset charset) {
 982         if (charset == null) throw new NullPointerException();
 983         return StringCoding.encode(charset, coder(), value);
 984      }
 985 
 986     /**
 987      * Encodes this {@code String} into a sequence of bytes using the
 988      * platform's default charset, storing the result into a new byte array.
 989      *
 990      * <p> The behavior of this method when this string cannot be encoded in
 991      * the default charset is unspecified.  The {@link
 992      * java.nio.charset.CharsetEncoder} class should be used when more control
 993      * over the encoding process is required.
 994      *
 995      * @return  The resultant byte array
 996      *
 997      * @since      1.1
 998      */
 999     public byte[] getBytes() {
1000         return StringCoding.encode(coder(), value);
1001     }
1002 
1003     /**
1004      * Compares this string to the specified object.  The result is {@code
1005      * true} if and only if the argument is not {@code null} and is a {@code
1006      * String} object that represents the same sequence of characters as this
1007      * object.
1008      *
1009      * <p>For finer-grained String comparison, refer to
1010      * {@link java.text.Collator}.
1011      *
1012      * @param  anObject
1013      *         The object to compare this {@code String} against
1014      *
1015      * @return  {@code true} if the given object represents a {@code String}
1016      *          equivalent to this string, {@code false} otherwise
1017      *
1018      * @see  #compareTo(String)
1019      * @see  #equalsIgnoreCase(String)
1020      */
1021     public boolean equals(Object anObject) {
1022         if (this == anObject) {
1023             return true;
1024         }
1025         if (anObject instanceof String) {
1026             String aString = (String)anObject;
1027             if (!COMPACT_STRINGS || this.coder == aString.coder) {
1028                 return StringLatin1.equals(value, aString.value);
1029             }
1030         }
1031         return false;
1032     }
1033 
1034     /**
1035      * Compares this string to the specified {@code StringBuffer}.  The result
1036      * is {@code true} if and only if this {@code String} represents the same
1037      * sequence of characters as the specified {@code StringBuffer}. This method
1038      * synchronizes on the {@code StringBuffer}.
1039      *
1040      * <p>For finer-grained String comparison, refer to
1041      * {@link java.text.Collator}.
1042      *
1043      * @param  sb
1044      *         The {@code StringBuffer} to compare this {@code String} against
1045      *
1046      * @return  {@code true} if this {@code String} represents the same
1047      *          sequence of characters as the specified {@code StringBuffer},
1048      *          {@code false} otherwise
1049      *
1050      * @since  1.4
1051      */
1052     public boolean contentEquals(StringBuffer sb) {
1053         return contentEquals((CharSequence)sb);
1054     }
1055 
1056     private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
1057         int len = length();
1058         if (len != sb.length()) {
1059             return false;
1060         }
1061         byte v1[] = value;
1062         byte v2[] = sb.getValue();
1063         byte coder = coder();
1064         if (coder == sb.getCoder()) {
1065             int n = v1.length;
1066             for (int i = 0; i < n; i++) {
1067                 if (v1[i] != v2[i]) {
1068                     return false;
1069                 }
1070             }
1071         } else {
1072             if (coder != LATIN1) {  // utf16 str and latin1 abs can never be "equal"
1073                 return false;
1074             }
1075             return StringUTF16.contentEquals(v1, v2, len);
1076         }
1077         return true;
1078     }
1079 
1080     /**
1081      * Compares this string to the specified {@code CharSequence}.  The
1082      * result is {@code true} if and only if this {@code String} represents the
1083      * same sequence of char values as the specified sequence. Note that if the
1084      * {@code CharSequence} is a {@code StringBuffer} then the method
1085      * synchronizes on it.
1086      *
1087      * <p>For finer-grained String comparison, refer to
1088      * {@link java.text.Collator}.
1089      *
1090      * @param  cs
1091      *         The sequence to compare this {@code String} against
1092      *
1093      * @return  {@code true} if this {@code String} represents the same
1094      *          sequence of char values as the specified sequence, {@code
1095      *          false} otherwise
1096      *
1097      * @since  1.5
1098      */
1099     public boolean contentEquals(CharSequence cs) {
1100         // Argument is a StringBuffer, StringBuilder
1101         if (cs instanceof AbstractStringBuilder) {
1102             if (cs instanceof StringBuffer) {
1103                 synchronized(cs) {
1104                    return nonSyncContentEquals((AbstractStringBuilder)cs);
1105                 }
1106             } else {
1107                 return nonSyncContentEquals((AbstractStringBuilder)cs);
1108             }
1109         }
1110         // Argument is a String
1111         if (cs instanceof String) {
1112             return equals(cs);
1113         }
1114         // Argument is a generic CharSequence
1115         int n = cs.length();
1116         if (n != length()) {
1117             return false;
1118         }
1119         byte[] val = this.value;
1120         if (isLatin1()) {
1121             for (int i = 0; i < n; i++) {
1122                 if ((val[i] & 0xff) != cs.charAt(i)) {
1123                     return false;
1124                 }
1125             }
1126         } else {
1127             if (!StringUTF16.contentEquals(val, cs, n)) {
1128                 return false;
1129             }
1130         }
1131         return true;
1132     }
1133 
1134     /**
1135      * Compares this {@code String} to another {@code String}, ignoring case
1136      * considerations.  Two strings are considered equal ignoring case if they
1137      * are of the same length and corresponding characters in the two strings
1138      * are equal ignoring case.
1139      *
1140      * <p> Two characters {@code c1} and {@code c2} are considered the same
1141      * ignoring case if at least one of the following is true:
1142      * <ul>
1143      *   <li> The two characters are the same (as compared by the
1144      *        {@code ==} operator)
1145      *   <li> Calling {@code Character.toLowerCase(Character.toUpperCase(char))}
1146      *        on each character produces the same result
1147      * </ul>
1148      *
1149      * <p>Note that this method does <em>not</em> take locale into account, and
1150      * will result in unsatisfactory results for certain locales.  The
1151      * {@link java.text.Collator} class provides locale-sensitive comparison.
1152      *
1153      * @param  anotherString
1154      *         The {@code String} to compare this {@code String} against
1155      *
1156      * @return  {@code true} if the argument is not {@code null} and it
1157      *          represents an equivalent {@code String} ignoring case; {@code
1158      *          false} otherwise
1159      *
1160      * @see  #equals(Object)
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      * {@code compareToIgnoreCase}. This comparator is serializable.
1228      * <p>
1229      * Note that this Comparator does <em>not</em> take locale into account,
1230      * and will result in an unsatisfactory ordering for certain locales.
1231      * The {@link java.text.Collator} class provides locale-sensitive comparison.
1232      *
1233      * @see     java.text.Collator
1234      * @since   1.2
1235      */
1236     public static final Comparator<String> CASE_INSENSITIVE_ORDER
1237                                          = new CaseInsensitiveComparator();
1238     private static class CaseInsensitiveComparator
1239             implements Comparator<String>, java.io.Serializable {
1240         // use serialVersionUID from JDK 1.2.2 for interoperability
1241         @java.io.Serial
1242         private static final long serialVersionUID = 8575799808933029326L;
1243 
1244         public int compare(String s1, String s2) {
1245             byte v1[] = s1.value;
1246             byte v2[] = s2.value;
1247             byte coder = s1.coder();
1248             if (coder == s2.coder()) {
1249                 return coder == LATIN1 ? StringLatin1.compareToCI(v1, v2)
1250                                        : StringUTF16.compareToCI(v1, v2);
1251             }
1252             return coder == LATIN1 ? StringLatin1.compareToCI_UTF16(v1, v2)
1253                                    : StringUTF16.compareToCI_Latin1(v1, v2);
1254         }
1255 
1256         /** Replaces the de-serialized object. */
1257         @java.io.Serial
1258         private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
1259     }
1260 
1261     /**
1262      * Compares two strings lexicographically, ignoring case
1263      * differences. This method returns an integer whose sign is that of
1264      * calling {@code compareTo} with normalized versions of the strings
1265      * where case differences have been eliminated by calling
1266      * {@code Character.toLowerCase(Character.toUpperCase(character))} on
1267      * each character.
1268      * <p>
1269      * Note that this method does <em>not</em> take locale into account,
1270      * and will result in an unsatisfactory ordering for certain locales.
1271      * The {@link java.text.Collator} class provides locale-sensitive comparison.
1272      *
1273      * @param   str   the {@code String} to be compared.
1274      * @return  a negative integer, zero, or a positive integer as the
1275      *          specified String is greater than, equal to, or less
1276      *          than this String, ignoring case considerations.
1277      * @see     java.text.Collator
1278      * @since   1.2
1279      */
1280     public int compareToIgnoreCase(String str) {
1281         return CASE_INSENSITIVE_ORDER.compare(this, str);
1282     }
1283 
1284     /**
1285      * Tests if two string regions are equal.
1286      * <p>
1287      * A substring of this {@code String} object is compared to a substring
1288      * of the argument other. The result is true if these substrings
1289      * represent identical character sequences. The substring of this
1290      * {@code String} object to be compared begins at index {@code toffset}
1291      * and has length {@code len}. The substring of other to be compared
1292      * begins at index {@code ooffset} and has length {@code len}. The
1293      * result is {@code false} if and only if at least one of the following
1294      * is true:
1295      * <ul><li>{@code toffset} is negative.
1296      * <li>{@code ooffset} is negative.
1297      * <li>{@code toffset+len} is greater than the length of this
1298      * {@code String} object.
1299      * <li>{@code ooffset+len} is greater than the length of the other
1300      * argument.
1301      * <li>There is some nonnegative integer <i>k</i> less than {@code len}
1302      * such that:
1303      * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
1304      * <i>k</i>{@code )}
1305      * </ul>
1306      *
1307      * <p>Note that this method does <em>not</em> take locale into account.  The
1308      * {@link java.text.Collator} class provides locale-sensitive comparison.
1309      *
1310      * @param   toffset   the starting offset of the subregion in this string.
1311      * @param   other     the string argument.
1312      * @param   ooffset   the starting offset of the subregion in the string
1313      *                    argument.
1314      * @param   len       the number of characters to compare.
1315      * @return  {@code true} if the specified subregion of this string
1316      *          exactly matches the specified subregion of the string argument;
1317      *          {@code false} otherwise.
1318      */
1319     public boolean regionMatches(int toffset, String other, int ooffset, int len) {
1320         byte tv[] = value;
1321         byte ov[] = other.value;
1322         // Note: toffset, ooffset, or len might be near -1>>>1.
1323         if ((ooffset < 0) || (toffset < 0) ||
1324              (toffset > (long)length() - len) ||
1325              (ooffset > (long)other.length() - len)) {
1326             return false;
1327         }
1328         byte coder = coder();
1329         if (coder == other.coder()) {
1330             if (!isLatin1() && (len > 0)) {
1331                 toffset = toffset << 1;
1332                 ooffset = ooffset << 1;
1333                 len = len << 1;
1334             }
1335             while (len-- > 0) {
1336                 if (tv[toffset++] != ov[ooffset++]) {
1337                     return false;
1338                 }
1339             }
1340         } else {
1341             if (coder == LATIN1) {
1342                 while (len-- > 0) {
1343                     if (StringLatin1.getChar(tv, toffset++) !=
1344                         StringUTF16.getChar(ov, ooffset++)) {
1345                         return false;
1346                     }
1347                 }
1348             } else {
1349                 while (len-- > 0) {
1350                     if (StringUTF16.getChar(tv, toffset++) !=
1351                         StringLatin1.getChar(ov, ooffset++)) {
1352                         return false;
1353                     }
1354                 }
1355             }
1356         }
1357         return true;
1358     }
1359 
1360     /**
1361      * Tests if two string regions are equal.
1362      * <p>
1363      * A substring of this {@code String} object is compared to a substring
1364      * of the argument {@code other}. The result is {@code true} if these
1365      * substrings represent character sequences that are the same, ignoring
1366      * case if and only if {@code ignoreCase} is true. The substring of
1367      * this {@code String} object to be compared begins at index
1368      * {@code toffset} and has length {@code len}. The substring of
1369      * {@code other} to be compared begins at index {@code ooffset} and
1370      * has length {@code len}. The result is {@code false} if and only if
1371      * at least one of the following is true:
1372      * <ul><li>{@code toffset} is negative.
1373      * <li>{@code ooffset} is negative.
1374      * <li>{@code toffset+len} is greater than the length of this
1375      * {@code String} object.
1376      * <li>{@code ooffset+len} is greater than the length of the other
1377      * argument.
1378      * <li>{@code ignoreCase} is {@code false} and there is some nonnegative
1379      * integer <i>k</i> less than {@code len} such that:
1380      * <blockquote><pre>
1381      * this.charAt(toffset+k) != other.charAt(ooffset+k)
1382      * </pre></blockquote>
1383      * <li>{@code ignoreCase} is {@code true} and there is some nonnegative
1384      * integer <i>k</i> less than {@code len} such that:
1385      * <blockquote><pre>
1386      * Character.toLowerCase(Character.toUpperCase(this.charAt(toffset+k))) !=
1387      * Character.toLowerCase(Character.toUpperCase(other.charAt(ooffset+k)))
1388      * </pre></blockquote>
1389      * </ul>
1390      *
1391      * <p>Note that this method does <em>not</em> take locale into account,
1392      * and will result in unsatisfactory results for certain locales when
1393      * {@code ignoreCase} is {@code true}.  The {@link java.text.Collator} class
1394      * provides locale-sensitive comparison.
1395      *
1396      * @param   ignoreCase   if {@code true}, ignore case when comparing
1397      *                       characters.
1398      * @param   toffset      the starting offset of the subregion in this
1399      *                       string.
1400      * @param   other        the string argument.
1401      * @param   ooffset      the starting offset of the subregion in the string
1402      *                       argument.
1403      * @param   len          the number of characters to compare.
1404      * @return  {@code true} if the specified subregion of this string
1405      *          matches the specified subregion of the string argument;
1406      *          {@code false} otherwise. Whether the matching is exact
1407      *          or case insensitive depends on the {@code ignoreCase}
1408      *          argument.
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">\u0130</th>
2507      *   <td>\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">\u0049</th>
2513      *   <td>\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">\u0069</th>
2590      *   <td>\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">\u0131</th>
2596      *   <td>\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">\u00df</th>
2602      *   <td>\u0053 \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&trade; 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&trade; 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 3.10.5 of the
3537      * <cite>The Java&trade; 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      * @jls 3.10.5 String Literals
3542      */
3543     public native String intern();
3544 
3545     /**
3546      * Returns a string whose value is the concatenation of this
3547      * string repeated {@code count} times.
3548      * <p>
3549      * If this string is empty or count is zero then the empty
3550      * string is returned.
3551      *
3552      * @param   count number of times to repeat
3553      *
3554      * @return  A string composed of this string repeated
3555      *          {@code count} times or the empty string if this
3556      *          string is empty or count is zero
3557      *
3558      * @throws  IllegalArgumentException if the {@code count} is
3559      *          negative.
3560      *
3561      * @since 11
3562      */
3563     public String repeat(int count) {
3564         if (count < 0) {
3565             throw new IllegalArgumentException("count is negative: " + count);
3566         }
3567         if (count == 1) {
3568             return this;
3569         }
3570         final int len = value.length;
3571         if (len == 0 || count == 0) {
3572             return "";
3573         }
3574         if (Integer.MAX_VALUE / count < len) {
3575             throw new OutOfMemoryError("Required length exceeds implementation limit");
3576         }
3577         if (len == 1) {
3578             final byte[] single = new byte[count];
3579             Arrays.fill(single, value[0]);
3580             return new String(single, coder);
3581         }
3582         final int limit = len * count;
3583         final byte[] multiple = new byte[limit];
3584         System.arraycopy(value, 0, multiple, 0, len);
3585         int copied = len;
3586         for (; copied < limit - copied; copied <<= 1) {
3587             System.arraycopy(multiple, 0, multiple, copied, copied);
3588         }
3589         System.arraycopy(multiple, 0, multiple, copied, limit - copied);
3590         return new String(multiple, coder);
3591     }
3592 
3593     ////////////////////////////////////////////////////////////////
3594 
3595     /**
3596      * Copy character bytes from this string into dst starting at dstBegin.
3597      * This method doesn't perform any range checking.
3598      *
3599      * Invoker guarantees: dst is in UTF16 (inflate itself for asb), if two
3600      * coders are different, and dst is big enough (range check)
3601      *
3602      * @param dstBegin  the char index, not offset of byte[]
3603      * @param coder     the coder of dst[]
3604      */
3605     void getBytes(byte dst[], int dstBegin, byte coder) {
3606         if (coder() == coder) {
3607             System.arraycopy(value, 0, dst, dstBegin << coder, value.length);
3608         } else {    // this.coder == LATIN && coder == UTF16
3609             StringLatin1.inflate(value, 0, dst, dstBegin, value.length);
3610         }
3611     }
3612 
3613     /*
3614      * Package private constructor. Trailing Void argument is there for
3615      * disambiguating it against other (public) constructors.
3616      *
3617      * Stores the char[] value into a byte[] that each byte represents
3618      * the8 low-order bits of the corresponding character, if the char[]
3619      * contains only latin1 character. Or a byte[] that stores all
3620      * characters in their byte sequences defined by the {@code StringUTF16}.
3621      */
3622     String(char[] value, int off, int len, Void sig) {
3623         if (len == 0) {
3624             this.value = "".value;
3625             this.coder = "".coder;
3626             return;
3627         }
3628         if (COMPACT_STRINGS) {
3629             byte[] val = StringUTF16.compress(value, off, len);
3630             if (val != null) {
3631                 this.value = val;
3632                 this.coder = LATIN1;
3633                 return;
3634             }
3635         }
3636         this.coder = UTF16;
3637         this.value = StringUTF16.toBytes(value, off, len);
3638     }
3639 
3640     /*
3641      * Package private constructor. Trailing Void argument is there for
3642      * disambiguating it against other (public) constructors.
3643      */
3644     String(AbstractStringBuilder asb, Void sig) {
3645         byte[] val = asb.getValue();
3646         int length = asb.length();
3647         if (asb.isLatin1()) {
3648             this.coder = LATIN1;
3649             this.value = Arrays.copyOfRange(val, 0, length);
3650         } else {
3651             if (COMPACT_STRINGS) {
3652                 byte[] buf = StringUTF16.compress(val, 0, length);
3653                 if (buf != null) {
3654                     this.coder = LATIN1;
3655                     this.value = buf;
3656                     return;
3657                 }
3658             }
3659             this.coder = UTF16;
3660             this.value = Arrays.copyOfRange(val, 0, length << 1);
3661         }
3662     }
3663 
3664    /*
3665     * Package private constructor which shares value array for speed.
3666     */
3667     String(byte[] value, byte coder) {
3668         this.value = value;
3669         this.coder = coder;
3670     }
3671 
3672     byte coder() {
3673         return COMPACT_STRINGS ? coder : UTF16;
3674     }
3675 
3676     byte[] value() {
3677         return value;
3678     }
3679 
3680     boolean isLatin1() {
3681         return COMPACT_STRINGS && coder == LATIN1;
3682     }
3683 
3684     @Native static final byte LATIN1 = 0;
3685     @Native static final byte UTF16  = 1;
3686 
3687     /*
3688      * StringIndexOutOfBoundsException  if {@code index} is
3689      * negative or greater than or equal to {@code length}.
3690      */
3691     static void checkIndex(int index, int length) {
3692         if (index < 0 || index >= length) {
3693             throw new StringIndexOutOfBoundsException("index " + index +
3694                                                       ", length " + length);
3695         }
3696     }
3697 
3698     /*
3699      * StringIndexOutOfBoundsException  if {@code offset}
3700      * is negative or greater than {@code length}.
3701      */
3702     static void checkOffset(int offset, int length) {
3703         if (offset < 0 || offset > length) {
3704             throw new StringIndexOutOfBoundsException("offset " + offset +
3705                                                       ", length " + length);
3706         }
3707     }
3708 
3709     /*
3710      * Check {@code offset}, {@code count} against {@code 0} and {@code length}
3711      * bounds.
3712      *
3713      * @throws  StringIndexOutOfBoundsException
3714      *          If {@code offset} is negative, {@code count} is negative,
3715      *          or {@code offset} is greater than {@code length - count}
3716      */
3717     static void checkBoundsOffCount(int offset, int count, int length) {
3718         if (offset < 0 || count < 0 || offset > length - count) {
3719             throw new StringIndexOutOfBoundsException(
3720                 "offset " + offset + ", count " + count + ", length " + length);
3721         }
3722     }
3723 
3724     /*
3725      * Check {@code begin}, {@code end} against {@code 0} and {@code length}
3726      * bounds.
3727      *
3728      * @throws  StringIndexOutOfBoundsException
3729      *          If {@code begin} is negative, {@code begin} is greater than
3730      *          {@code end}, or {@code end} is greater than {@code length}.
3731      */
3732     static void checkBoundsBeginEnd(int begin, int end, int length) {
3733         if (begin < 0 || begin > end || end > length) {
3734             throw new StringIndexOutOfBoundsException(
3735                 "begin " + begin + ", end " + end + ", length " + length);
3736         }
3737     }
3738 
3739     /**
3740      * Returns the string representation of the {@code codePoint}
3741      * argument.
3742      *
3743      * @param   codePoint a {@code codePoint}.
3744      * @return  a string of length {@code 1} or {@code 2} containing
3745      *          as its single character the argument {@code codePoint}.
3746      * @throws IllegalArgumentException if the specified
3747      *          {@code codePoint} is not a {@linkplain Character#isValidCodePoint
3748      *          valid Unicode code point}.
3749      */
3750     static String valueOfCodePoint(int codePoint) {
3751         if (COMPACT_STRINGS && StringLatin1.canEncode(codePoint)) {
3752             return new String(StringLatin1.toBytes((char)codePoint), LATIN1);
3753         } else if (Character.isBmpCodePoint(codePoint)) {
3754             return new String(StringUTF16.toBytes((char)codePoint), UTF16);
3755         } else if (Character.isSupplementaryCodePoint(codePoint)) {
3756             return new String(StringUTF16.toBytesSupplementary(codePoint), UTF16);
3757         }
3758 
3759         throw new IllegalArgumentException(
3760             format("Not a valid Unicode code point: 0x%X", codePoint));
3761     }
3762 
3763     /**
3764      * Returns an {@link Optional} containing the nominal descriptor for this
3765      * instance, which is the instance itself.
3766      *
3767      * @return an {@link Optional} describing the {@linkplain String} instance
3768      * @since 12
3769      */
3770     @Override
3771     public Optional<String> describeConstable() {
3772         return Optional.of(this);
3773     }
3774 
3775     /**
3776      * Resolves this instance as a {@link ConstantDesc}, the result of which is
3777      * the instance itself.
3778      *
3779      * @param lookup ignored
3780      * @return the {@linkplain String} instance
3781      * @since 12
3782      */
3783     @Override
3784     public String resolveConstantDesc(MethodHandles.Lookup lookup) {
3785         return this;
3786     }
3787 
3788 }