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