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