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         int thisLen = length();
2164         String tgtStr = target.toString();
2165         int tgtLen = tgtStr.length();
2166         String replStr = replacement.toString();
2167         int replLen = replStr.length();
2168         if (tgtLen > 0) {
2169             if (tgtLen == 1 && replLen == 1) {
2170                 return replace(tgtStr.charAt(0), replStr.charAt(0));
2171             }
2172             if (this.isLatin1() && tgtStr.isLatin1() && replStr.isLatin1()) {
2173                 String ret = StringLatin1.replace(value, thisLen, tgtStr.value,
2174                                                   tgtLen, replStr.value, replLen);
2175                 if (ret != null) {
2176                     return ret;
2177                 }
2178                 return this;
2179             }
2180         }
2181 
2182         int j = indexOf(tgtStr);
2183         if (j < 0) {
2184             return this;
2185         }
2186         int tgtLen1 = tgtLen > 0 ? tgtLen : 1;
2187 
2188         int newLenHint = thisLen - tgtLen + replLen;
2189         if (newLenHint < 0) {
2190             throw new OutOfMemoryError();
2191         }
2192         StringBuilder sb = new StringBuilder(newLenHint);
2193         int i = 0;
2194         do {
2195             sb.append(this, i, j).append(replStr);
2196             i = j + tgtLen;
2197         } while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
2198         return sb.append(this, i, thisLen).toString();
2199     }
2200 
2201     /**
2202      * Splits this string around matches of the given
2203      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2204      *
2205      * <p> The array returned by this method contains each substring of this
2206      * string that is terminated by another substring that matches the given
2207      * expression or is terminated by the end of the string.  The substrings in
2208      * the array are in the order in which they occur in this string.  If the
2209      * expression does not match any part of the input then the resulting array
2210      * has just one element, namely this string.
2211      *
2212      * <p> When there is a positive-width match at the beginning of this
2213      * string then an empty leading substring is included at the beginning
2214      * of the resulting array. A zero-width match at the beginning however
2215      * never produces such empty leading substring.
2216      *
2217      * <p> The {@code limit} parameter controls the number of times the
2218      * pattern is applied and therefore affects the length of the resulting
2219      * array.
2220      * <ul>
2221      *    <li><p>
2222      *    If the <i>limit</i> is positive then the pattern will be applied
2223      *    at most <i>limit</i>&nbsp;-&nbsp;1 times, the array's length will be
2224      *    no greater than <i>limit</i>, and the array's last entry will contain
2225      *    all input beyond the last matched delimiter.</p></li>
2226      *
2227      *    <li><p>
2228      *    If the <i>limit</i> is zero then the pattern will be applied as
2229      *    many times as possible, the array can have any length, and trailing
2230      *    empty strings will be discarded.</p></li>
2231      *
2232      *    <li><p>
2233      *    If the <i>limit</i> is negative then the pattern will be applied
2234      *    as many times as possible and the array can have any length.</p></li>
2235      * </ul>
2236      *
2237      * <p> The string {@code "boo:and:foo"}, for example, yields the
2238      * following results with these parameters:
2239      *
2240      * <blockquote><table class="plain">
2241      * <caption style="display:none">Split example showing regex, limit, and result</caption>
2242      * <thead>
2243      * <tr>
2244      *     <th scope="col">Regex</th>
2245      *     <th scope="col">Limit</th>
2246      *     <th scope="col">Result</th>
2247      * </tr>
2248      * </thead>
2249      * <tbody>
2250      * <tr><th scope="row" rowspan="3" style="font-weight:normal">:</th>
2251      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">2</th>
2252      *     <td>{@code { "boo", "and:foo" }}</td></tr>
2253      * <tr><!-- : -->
2254      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
2255      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
2256      * <tr><!-- : -->
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><th scope="row" rowspan="3" style="font-weight:normal">o</th>
2260      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
2261      *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
2262      * <tr><!-- o -->
2263      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
2264      *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
2265      * <tr><!-- o -->
2266      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">0</th>
2267      *     <td>{@code { "b", "", ":and:f" }}</td></tr>
2268      * </tbody>
2269      * </table></blockquote>
2270      *
2271      * <p> An invocation of this method of the form
2272      * <i>str.</i>{@code split(}<i>regex</i>{@code ,}&nbsp;<i>n</i>{@code )}
2273      * yields the same result as the expression
2274      *
2275      * <blockquote>
2276      * <code>
2277      * {@link java.util.regex.Pattern}.{@link
2278      * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
2279      * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>,&nbsp;<i>n</i>)
2280      * </code>
2281      * </blockquote>
2282      *
2283      *
2284      * @param  regex
2285      *         the delimiting regular expression
2286      *
2287      * @param  limit
2288      *         the result threshold, as described above
2289      *
2290      * @return  the array of strings computed by splitting this string
2291      *          around matches of the given regular expression
2292      *
2293      * @throws  PatternSyntaxException
2294      *          if the regular expression's syntax is invalid
2295      *
2296      * @see java.util.regex.Pattern
2297      *
2298      * @since 1.4
2299      * @spec JSR-51
2300      */
2301     public String[] split(String regex, int limit) {
2302         /* fastpath if the regex is a
2303          (1)one-char String and this character is not one of the
2304             RegEx's meta characters ".$|()[{^?*+\\", or
2305          (2)two-char String and the first char is the backslash and
2306             the second is not the ascii digit or ascii letter.
2307          */
2308         char ch = 0;
2309         if (((regex.length() == 1 &&
2310              ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
2311              (regex.length() == 2 &&
2312               regex.charAt(0) == '\\' &&
2313               (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
2314               ((ch-'a')|('z'-ch)) < 0 &&
2315               ((ch-'A')|('Z'-ch)) < 0)) &&
2316             (ch < Character.MIN_HIGH_SURROGATE ||
2317              ch > Character.MAX_LOW_SURROGATE))
2318         {
2319             int off = 0;
2320             int next = 0;
2321             boolean limited = limit > 0;
2322             ArrayList<String> list = new ArrayList<>();
2323             while ((next = indexOf(ch, off)) != -1) {
2324                 if (!limited || list.size() < limit - 1) {
2325                     list.add(substring(off, next));
2326                     off = next + 1;
2327                 } else {    // last one
2328                     //assert (list.size() == limit - 1);
2329                     int last = length();
2330                     list.add(substring(off, last));
2331                     off = last;
2332                     break;
2333                 }
2334             }
2335             // If no match was found, return this
2336             if (off == 0)
2337                 return new String[]{this};
2338 
2339             // Add remaining segment
2340             if (!limited || list.size() < limit)
2341                 list.add(substring(off, length()));
2342 
2343             // Construct result
2344             int resultSize = list.size();
2345             if (limit == 0) {
2346                 while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {
2347                     resultSize--;
2348                 }
2349             }
2350             String[] result = new String[resultSize];
2351             return list.subList(0, resultSize).toArray(result);
2352         }
2353         return Pattern.compile(regex).split(this, limit);
2354     }
2355 
2356     /**
2357      * Splits this string around matches of the given <a
2358      * href="../util/regex/Pattern.html#sum">regular expression</a>.
2359      *
2360      * <p> This method works as if by invoking the two-argument {@link
2361      * #split(String, int) split} method with the given expression and a limit
2362      * argument of zero.  Trailing empty strings are therefore not included in
2363      * the resulting array.
2364      *
2365      * <p> The string {@code "boo:and:foo"}, for example, yields the following
2366      * results with these expressions:
2367      *
2368      * <blockquote><table class="plain">
2369      * <caption style="display:none">Split examples showing regex and result</caption>
2370      * <thead>
2371      * <tr>
2372      *  <th scope="col">Regex</th>
2373      *  <th scope="col">Result</th>
2374      * </tr>
2375      * </thead>
2376      * <tbody>
2377      * <tr><th scope="row" style="text-weight:normal">:</th>
2378      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
2379      * <tr><th scope="row" style="text-weight:normal">o</th>
2380      *     <td>{@code { "b", "", ":and:f" }}</td></tr>
2381      * </tbody>
2382      * </table></blockquote>
2383      *
2384      *
2385      * @param  regex
2386      *         the delimiting regular expression
2387      *
2388      * @return  the array of strings computed by splitting this string
2389      *          around matches of the given regular expression
2390      *
2391      * @throws  PatternSyntaxException
2392      *          if the regular expression's syntax is invalid
2393      *
2394      * @see java.util.regex.Pattern
2395      *
2396      * @since 1.4
2397      * @spec JSR-51
2398      */
2399     public String[] split(String regex) {
2400         return split(regex, 0);
2401     }
2402 
2403     /**
2404      * Returns a new String composed of copies of the
2405      * {@code CharSequence elements} joined together with a copy of
2406      * the specified {@code delimiter}.
2407      *
2408      * <blockquote>For example,
2409      * <pre>{@code
2410      *     String message = String.join("-", "Java", "is", "cool");
2411      *     // message returned is: "Java-is-cool"
2412      * }</pre></blockquote>
2413      *
2414      * Note that if an element is null, then {@code "null"} is added.
2415      *
2416      * @param  delimiter the delimiter that separates each element
2417      * @param  elements the elements to join together.
2418      *
2419      * @return a new {@code String} that is composed of the {@code elements}
2420      *         separated by the {@code delimiter}
2421      *
2422      * @throws NullPointerException If {@code delimiter} or {@code elements}
2423      *         is {@code null}
2424      *
2425      * @see java.util.StringJoiner
2426      * @since 1.8
2427      */
2428     public static String join(CharSequence delimiter, CharSequence... elements) {
2429         Objects.requireNonNull(delimiter);
2430         Objects.requireNonNull(elements);
2431         // Number of elements not likely worth Arrays.stream overhead.
2432         StringJoiner joiner = new StringJoiner(delimiter);
2433         for (CharSequence cs: elements) {
2434             joiner.add(cs);
2435         }
2436         return joiner.toString();
2437     }
2438 
2439     /**
2440      * Returns a new {@code String} composed of copies of the
2441      * {@code CharSequence elements} joined together with a copy of the
2442      * specified {@code delimiter}.
2443      *
2444      * <blockquote>For example,
2445      * <pre>{@code
2446      *     List<String> strings = List.of("Java", "is", "cool");
2447      *     String message = String.join(" ", strings);
2448      *     //message returned is: "Java is cool"
2449      *
2450      *     Set<String> strings =
2451      *         new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
2452      *     String message = String.join("-", strings);
2453      *     //message returned is: "Java-is-very-cool"
2454      * }</pre></blockquote>
2455      *
2456      * Note that if an individual element is {@code null}, then {@code "null"} is added.
2457      *
2458      * @param  delimiter a sequence of characters that is used to separate each
2459      *         of the {@code elements} in the resulting {@code String}
2460      * @param  elements an {@code Iterable} that will have its {@code elements}
2461      *         joined together.
2462      *
2463      * @return a new {@code String} that is composed from the {@code elements}
2464      *         argument
2465      *
2466      * @throws NullPointerException If {@code delimiter} or {@code elements}
2467      *         is {@code null}
2468      *
2469      * @see    #join(CharSequence,CharSequence...)
2470      * @see    java.util.StringJoiner
2471      * @since 1.8
2472      */
2473     public static String join(CharSequence delimiter,
2474             Iterable<? extends CharSequence> elements) {
2475         Objects.requireNonNull(delimiter);
2476         Objects.requireNonNull(elements);
2477         StringJoiner joiner = new StringJoiner(delimiter);
2478         for (CharSequence cs: elements) {
2479             joiner.add(cs);
2480         }
2481         return joiner.toString();
2482     }
2483 
2484     /**
2485      * Converts all of the characters in this {@code String} to lower
2486      * case using the rules of the given {@code Locale}.  Case mapping is based
2487      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2488      * class. Since case mappings are not always 1:1 char mappings, the resulting
2489      * {@code String} may be a different length than the original {@code String}.
2490      * <p>
2491      * Examples of lowercase  mappings are in the following table:
2492      * <table class="plain">
2493      * <caption style="display:none">Lowercase mapping examples showing language code of locale, upper case, lower case, and description</caption>
2494      * <thead>
2495      * <tr>
2496      *   <th scope="col">Language Code of Locale</th>
2497      *   <th scope="col">Upper Case</th>
2498      *   <th scope="col">Lower Case</th>
2499      *   <th scope="col">Description</th>
2500      * </tr>
2501      * </thead>
2502      * <tbody>
2503      * <tr>
2504      *   <td>tr (Turkish)</td>
2505      *   <th scope="row" style="font-weight:normal; text-align:left">\u0130</th>
2506      *   <td>\u0069</td>
2507      *   <td>capital letter I with dot above -&gt; small letter i</td>
2508      * </tr>
2509      * <tr>
2510      *   <td>tr (Turkish)</td>
2511      *   <th scope="row" style="font-weight:normal; text-align:left">\u0049</th>
2512      *   <td>\u0131</td>
2513      *   <td>capital letter I -&gt; small letter dotless i </td>
2514      * </tr>
2515      * <tr>
2516      *   <td>(all)</td>
2517      *   <th scope="row" style="font-weight:normal; text-align:left">French Fries</th>
2518      *   <td>french fries</td>
2519      *   <td>lowercased all chars in String</td>
2520      * </tr>
2521      * <tr>
2522      *   <td>(all)</td>
2523      *   <th scope="row" style="font-weight:normal; text-align:left">
2524      *       &Iota;&Chi;&Theta;&Upsilon;&Sigma;</th>
2525      *   <td>&iota;&chi;&theta;&upsilon;&sigma;</td>
2526      *   <td>lowercased all chars in String</td>
2527      * </tr>
2528      * </tbody>
2529      * </table>
2530      *
2531      * @param locale use the case transformation rules for this locale
2532      * @return the {@code String}, converted to lowercase.
2533      * @see     java.lang.String#toLowerCase()
2534      * @see     java.lang.String#toUpperCase()
2535      * @see     java.lang.String#toUpperCase(Locale)
2536      * @since   1.1
2537      */
2538     public String toLowerCase(Locale locale) {
2539         return isLatin1() ? StringLatin1.toLowerCase(this, value, locale)
2540                           : StringUTF16.toLowerCase(this, value, locale);
2541     }
2542 
2543     /**
2544      * Converts all of the characters in this {@code String} to lower
2545      * case using the rules of the default locale. This is equivalent to calling
2546      * {@code toLowerCase(Locale.getDefault())}.
2547      * <p>
2548      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2549      * results if used for strings that are intended to be interpreted locale
2550      * independently.
2551      * Examples are programming language identifiers, protocol keys, and HTML
2552      * tags.
2553      * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
2554      * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
2555      * LATIN SMALL LETTER DOTLESS I character.
2556      * To obtain correct results for locale insensitive strings, use
2557      * {@code toLowerCase(Locale.ROOT)}.
2558      *
2559      * @return  the {@code String}, converted to lowercase.
2560      * @see     java.lang.String#toLowerCase(Locale)
2561      */
2562     public String toLowerCase() {
2563         return toLowerCase(Locale.getDefault());
2564     }
2565 
2566     /**
2567      * Converts all of the characters in this {@code String} to upper
2568      * case using the rules of the given {@code Locale}. Case mapping is based
2569      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2570      * class. Since case mappings are not always 1:1 char mappings, the resulting
2571      * {@code String} may be a different length than the original {@code String}.
2572      * <p>
2573      * Examples of locale-sensitive and 1:M case mappings are in the following table.
2574      *
2575      * <table class="plain">
2576      * <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>
2577      * <thead>
2578      * <tr>
2579      *   <th scope="col">Language Code of Locale</th>
2580      *   <th scope="col">Lower Case</th>
2581      *   <th scope="col">Upper Case</th>
2582      *   <th scope="col">Description</th>
2583      * </tr>
2584      * </thead>
2585      * <tbody>
2586      * <tr>
2587      *   <td>tr (Turkish)</td>
2588      *   <th scope="row" style="font-weight:normal; text-align:left">\u0069</th>
2589      *   <td>\u0130</td>
2590      *   <td>small letter i -&gt; capital letter I with dot above</td>
2591      * </tr>
2592      * <tr>
2593      *   <td>tr (Turkish)</td>
2594      *   <th scope="row" style="font-weight:normal; text-align:left">\u0131</th>
2595      *   <td>\u0049</td>
2596      *   <td>small letter dotless i -&gt; capital letter I</td>
2597      * </tr>
2598      * <tr>
2599      *   <td>(all)</td>
2600      *   <th scope="row" style="font-weight:normal; text-align:left">\u00df</th>
2601      *   <td>\u0053 \u0053</td>
2602      *   <td>small letter sharp s -&gt; two letters: SS</td>
2603      * </tr>
2604      * <tr>
2605      *   <td>(all)</td>
2606      *   <th scope="row" style="font-weight:normal; text-align:left">Fahrvergn&uuml;gen</th>
2607      *   <td>FAHRVERGN&Uuml;GEN</td>
2608      *   <td></td>
2609      * </tr>
2610      * </tbody>
2611      * </table>
2612      * @param locale use the case transformation rules for this locale
2613      * @return the {@code String}, converted to uppercase.
2614      * @see     java.lang.String#toUpperCase()
2615      * @see     java.lang.String#toLowerCase()
2616      * @see     java.lang.String#toLowerCase(Locale)
2617      * @since   1.1
2618      */
2619     public String toUpperCase(Locale locale) {
2620         return isLatin1() ? StringLatin1.toUpperCase(this, value, locale)
2621                           : StringUTF16.toUpperCase(this, value, locale);
2622     }
2623 
2624     /**
2625      * Converts all of the characters in this {@code String} to upper
2626      * case using the rules of the default locale. This method is equivalent to
2627      * {@code toUpperCase(Locale.getDefault())}.
2628      * <p>
2629      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2630      * results if used for strings that are intended to be interpreted locale
2631      * independently.
2632      * Examples are programming language identifiers, protocol keys, and HTML
2633      * tags.
2634      * For instance, {@code "title".toUpperCase()} in a Turkish locale
2635      * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
2636      * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2637      * To obtain correct results for locale insensitive strings, use
2638      * {@code toUpperCase(Locale.ROOT)}.
2639      *
2640      * @return  the {@code String}, converted to uppercase.
2641      * @see     java.lang.String#toUpperCase(Locale)
2642      */
2643     public String toUpperCase() {
2644         return toUpperCase(Locale.getDefault());
2645     }
2646 
2647     /**
2648      * Returns a string whose value is this string, with all leading
2649      * and trailing space removed, where space is defined
2650      * as any character whose codepoint is less than or equal to
2651      * {@code 'U+0020'} (the space character).
2652      * <p>
2653      * If this {@code String} object represents an empty character
2654      * sequence, or the first and last characters of character sequence
2655      * represented by this {@code String} object both have codes
2656      * that are not space (as defined above), then a
2657      * reference to this {@code String} object is returned.
2658      * <p>
2659      * Otherwise, if all characters in this string are space (as
2660      * defined above), then a  {@code String} object representing an
2661      * empty string is returned.
2662      * <p>
2663      * Otherwise, let <i>k</i> be the index of the first character in the
2664      * string whose code is not a space (as defined above) and let
2665      * <i>m</i> be the index of the last character in the string whose code
2666      * is not a space (as defined above). A {@code String}
2667      * object is returned, representing the substring of this string that
2668      * begins with the character at index <i>k</i> and ends with the
2669      * character at index <i>m</i>-that is, the result of
2670      * {@code this.substring(k, m + 1)}.
2671      * <p>
2672      * This method may be used to trim space (as defined above) from
2673      * the beginning and end of a string.
2674      *
2675      * @return  a string whose value is this string, with all leading
2676      *          and trailing space removed, or this string if it
2677      *          has no leading or trailing space.
2678      */
2679     public String trim() {
2680         String ret = isLatin1() ? StringLatin1.trim(value)
2681                                 : StringUTF16.trim(value);
2682         return ret == null ? this : ret;
2683     }
2684 
2685     /**
2686      * Returns a string whose value is this string, with all leading
2687      * and trailing {@link Character#isWhitespace(int) white space}
2688      * removed.
2689      * <p>
2690      * If this {@code String} object represents an empty string,
2691      * or if all code points in this string are
2692      * {@link Character#isWhitespace(int) white space}, then an empty string
2693      * is returned.
2694      * <p>
2695      * Otherwise, returns a substring of this string beginning with the first
2696      * code point that is not a {@link Character#isWhitespace(int) white space}
2697      * up to and including the last code point that is not a
2698      * {@link Character#isWhitespace(int) white space}.
2699      * <p>
2700      * This method may be used to strip
2701      * {@link Character#isWhitespace(int) white space} from
2702      * the beginning and end of a string.
2703      *
2704      * @return  a string whose value is this string, with all leading
2705      *          and trailing white space removed
2706      *
2707      * @see Character#isWhitespace(int)
2708      *
2709      * @since 11
2710      */
2711     public String strip() {
2712         String ret = isLatin1() ? StringLatin1.strip(value)
2713                                 : StringUTF16.strip(value);
2714         return ret == null ? this : ret;
2715     }
2716 
2717     /**
2718      * Returns a string whose value is this string, with all leading
2719      * {@link Character#isWhitespace(int) white space} removed.
2720      * <p>
2721      * If this {@code String} object represents an empty string,
2722      * or if all code points in this string are
2723      * {@link Character#isWhitespace(int) white space}, then an empty string
2724      * is returned.
2725      * <p>
2726      * Otherwise, returns a substring of this string beginning with the first
2727      * code point that is not a {@link Character#isWhitespace(int) white space}
2728      * up to and including the last code point of this string.
2729      * <p>
2730      * This method may be used to trim
2731      * {@link Character#isWhitespace(int) white space} from
2732      * the beginning of a string.
2733      *
2734      * @return  a string whose value is this string, with all leading white
2735      *          space removed
2736      *
2737      * @see Character#isWhitespace(int)
2738      *
2739      * @since 11
2740      */
2741     public String stripLeading() {
2742         String ret = isLatin1() ? StringLatin1.stripLeading(value)
2743                                 : StringUTF16.stripLeading(value);
2744         return ret == null ? this : ret;
2745     }
2746 
2747     /**
2748      * Returns a string whose value is this string, with all trailing
2749      * {@link Character#isWhitespace(int) white space} removed.
2750      * <p>
2751      * If this {@code String} object represents an empty string,
2752      * or if all characters in this string are
2753      * {@link Character#isWhitespace(int) white space}, then an empty string
2754      * is returned.
2755      * <p>
2756      * Otherwise, returns a substring of this string beginning with the first
2757      * code point of this string up to and including the last code point
2758      * that is not a {@link Character#isWhitespace(int) white space}.
2759      * <p>
2760      * This method may be used to trim
2761      * {@link Character#isWhitespace(int) white space} from
2762      * the end of a string.
2763      *
2764      * @return  a string whose value is this string, with all trailing white
2765      *          space removed
2766      *
2767      * @see Character#isWhitespace(int)
2768      *
2769      * @since 11
2770      */
2771     public String stripTrailing() {
2772         String ret = isLatin1() ? StringLatin1.stripTrailing(value)
2773                                 : StringUTF16.stripTrailing(value);
2774         return ret == null ? this : ret;
2775     }
2776 
2777     /**
2778      * Returns {@code true} if the string is empty or contains only
2779      * {@link Character#isWhitespace(int) white space} codepoints,
2780      * otherwise {@code false}.
2781      *
2782      * @return {@code true} if the string is empty or contains only
2783      *         {@link Character#isWhitespace(int) white space} codepoints,
2784      *         otherwise {@code false}
2785      *
2786      * @see Character#isWhitespace(int)
2787      *
2788      * @since 11
2789      */
2790     public boolean isBlank() {
2791         return indexOfNonWhitespace() == length();
2792     }
2793 
2794     private Stream<String> lines(int maxLeading, int maxTrailing) {
2795         return isLatin1() ? StringLatin1.lines(value, maxLeading, maxTrailing)
2796                           : StringUTF16.lines(value, maxLeading, maxTrailing);
2797     }
2798 
2799     /**
2800      * Returns a stream of lines extracted from this string,
2801      * separated by line terminators.
2802      * <p>
2803      * A <i>line terminator</i> is one of the following:
2804      * a line feed character {@code "\n"} (U+000A),
2805      * a carriage return character {@code "\r"} (U+000D),
2806      * or a carriage return followed immediately by a line feed
2807      * {@code "\r\n"} (U+000D U+000A).
2808      * <p>
2809      * A <i>line</i> is either a sequence of zero or more characters
2810      * followed by a line terminator, or it is a sequence of one or
2811      * more characters followed by the end of the string. A
2812      * line does not include the line terminator.
2813      * <p>
2814      * The stream returned by this method contains the lines from
2815      * this string in the order in which they occur.
2816      *
2817      * @apiNote This definition of <i>line</i> implies that an empty
2818      *          string has zero lines and that there is no empty line
2819      *          following a line terminator at the end of a string.
2820      *
2821      * @implNote This method provides better performance than
2822      *           split("\R") by supplying elements lazily and
2823      *           by faster search of new line terminators.
2824      *
2825      * @return  the stream of lines extracted from this string
2826      *
2827      * @since 11
2828      */
2829     public Stream<String> lines() {
2830         return lines(0, 0);
2831     }
2832 
2833     /**
2834      * Adjusts the indentation of each line of this string based on the value of
2835      * {@code n}, and normalizes line termination characters.
2836      * <p>
2837      * This string is conceptually separated into lines using
2838      * {@link String#lines()}. Each line is then adjusted as described below
2839      * and then suffixed with a line feed {@code "\n"} (U+000A). The resulting
2840      * lines are then concatenated and returned.
2841      * <p>
2842      * If {@code n > 0} then {@code n} spaces (U+0020) are inserted at the
2843      * beginning of each line.
2844      * <p>
2845      * If {@code n < 0} then up to {@code n}
2846      * {@link Character#isWhitespace(int) white space characters} are removed
2847      * from the beginning of each line. If a given line does not contain
2848      * sufficient white space then all leading
2849      * {@link Character#isWhitespace(int) white space characters} are removed.
2850      * Each white space character is treated as a single character. In
2851      * particular, the tab character {@code "\t"} (U+0009) is considered a
2852      * single character; it is not expanded.
2853      * <p>
2854      * If {@code n == 0} then the line remains unchanged. However, line
2855      * terminators are still normalized.
2856      *
2857      * @param n  number of leading
2858      *           {@link Character#isWhitespace(int) white space characters}
2859      *           to add or remove
2860      *
2861      * @return string with indentation adjusted and line endings normalized
2862      *
2863      * @see String#lines()
2864      * @see String#isBlank()
2865      * @see Character#isWhitespace(int)
2866      *
2867      * @since 12
2868      */
2869     public String indent(int n) {
2870         return isEmpty() ? "" :  indent(n, false);
2871     }
2872 
2873     private String indent(int n, boolean removeBlanks) {
2874         Stream<String> stream = removeBlanks ? lines(Integer.MAX_VALUE, Integer.MAX_VALUE)
2875                                              : lines();
2876         if (n > 0) {
2877             final String spaces = " ".repeat(n);
2878             stream = stream.map(s -> spaces + s);
2879         } else if (n == Integer.MIN_VALUE) {
2880             stream = stream.map(s -> s.stripLeading());
2881         } else if (n < 0) {
2882             stream = stream.map(s -> s.substring(Math.min(-n, s.indexOfNonWhitespace())));
2883         }
2884         return stream.collect(Collectors.joining("\n", "", "\n"));
2885     }
2886 
2887     private int indexOfNonWhitespace() {
2888         return isLatin1() ? StringLatin1.indexOfNonWhitespace(value)
2889                           : StringUTF16.indexOfNonWhitespace(value);
2890     }
2891 
2892     private int lastIndexOfNonWhitespace() {
2893         return isLatin1() ? StringLatin1.lastIndexOfNonWhitespace(value)
2894                           : StringUTF16.lastIndexOfNonWhitespace(value);
2895     }
2896 
2897     /**
2898      * This method allows the application of a function to {@code this}
2899      * string. The function should expect a single String argument
2900      * and produce an {@code R} result.
2901      * <p>
2902      * Any exception thrown by {@code f()} will be propagated to the
2903      * caller.
2904      *
2905      * @param f    functional interface to a apply
2906      *
2907      * @param <R>  class of the result
2908      *
2909      * @return     the result of applying the function to this string
2910      *
2911      * @see java.util.function.Function
2912      *
2913      * @since 12
2914      */
2915     public <R> R transform(Function<? super String, ? extends R> f) {
2916         return f.apply(this);
2917     }
2918 
2919     /**
2920      * This object (which is already a string!) is itself returned.
2921      *
2922      * @return  the string itself.
2923      */
2924     public String toString() {
2925         return this;
2926     }
2927 
2928     /**
2929      * Returns a stream of {@code int} zero-extending the {@code char} values
2930      * from this sequence.  Any char which maps to a <a
2931      * href="{@docRoot}/java.base/java/lang/Character.html#unicode">surrogate code
2932      * point</a> is passed through uninterpreted.
2933      *
2934      * @return an IntStream of char values from this sequence
2935      * @since 9
2936      */
2937     @Override
2938     public IntStream chars() {
2939         return StreamSupport.intStream(
2940             isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
2941                        : new StringUTF16.CharsSpliterator(value, Spliterator.IMMUTABLE),
2942             false);
2943     }
2944 
2945 
2946     /**
2947      * Returns a stream of code point values from this sequence.  Any surrogate
2948      * pairs encountered in the sequence are combined as if by {@linkplain
2949      * Character#toCodePoint Character.toCodePoint} and the result is passed
2950      * to the stream. Any other code units, including ordinary BMP characters,
2951      * unpaired surrogates, and undefined code units, are zero-extended to
2952      * {@code int} values which are then passed to the stream.
2953      *
2954      * @return an IntStream of Unicode code points from this sequence
2955      * @since 9
2956      */
2957     @Override
2958     public IntStream codePoints() {
2959         return StreamSupport.intStream(
2960             isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
2961                        : new StringUTF16.CodePointsSpliterator(value, Spliterator.IMMUTABLE),
2962             false);
2963     }
2964 
2965     /**
2966      * Converts this string to a new character array.
2967      *
2968      * @return  a newly allocated character array whose length is the length
2969      *          of this string and whose contents are initialized to contain
2970      *          the character sequence represented by this string.
2971      */
2972     public char[] toCharArray() {
2973         return isLatin1() ? StringLatin1.toChars(value)
2974                           : StringUTF16.toChars(value);
2975     }
2976 
2977     /**
2978      * Returns a formatted string using the specified format string and
2979      * arguments.
2980      *
2981      * <p> The locale always used is the one returned by {@link
2982      * java.util.Locale#getDefault(java.util.Locale.Category)
2983      * Locale.getDefault(Locale.Category)} with
2984      * {@link java.util.Locale.Category#FORMAT FORMAT} category specified.
2985      *
2986      * @param  format
2987      *         A <a href="../util/Formatter.html#syntax">format string</a>
2988      *
2989      * @param  args
2990      *         Arguments referenced by the format specifiers in the format
2991      *         string.  If there are more arguments than format specifiers, the
2992      *         extra arguments are ignored.  The number of arguments is
2993      *         variable and may be zero.  The maximum number of arguments is
2994      *         limited by the maximum dimension of a Java array as defined by
2995      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
2996      *         The behaviour on a
2997      *         {@code null} argument depends on the <a
2998      *         href="../util/Formatter.html#syntax">conversion</a>.
2999      *
3000      * @throws  java.util.IllegalFormatException
3001      *          If a format string contains an illegal syntax, a format
3002      *          specifier that is incompatible with the given arguments,
3003      *          insufficient arguments given the format string, or other
3004      *          illegal conditions.  For specification of all possible
3005      *          formatting errors, see the <a
3006      *          href="../util/Formatter.html#detail">Details</a> section of the
3007      *          formatter class specification.
3008      *
3009      * @return  A formatted string
3010      *
3011      * @see  java.util.Formatter
3012      * @since  1.5
3013      */
3014     public static String format(String format, Object... args) {
3015         return new Formatter().format(format, args).toString();
3016     }
3017 
3018     /**
3019      * Returns a formatted string using the specified locale, format string,
3020      * and arguments.
3021      *
3022      * @param  l
3023      *         The {@linkplain java.util.Locale locale} to apply during
3024      *         formatting.  If {@code l} is {@code null} then no localization
3025      *         is applied.
3026      *
3027      * @param  format
3028      *         A <a href="../util/Formatter.html#syntax">format string</a>
3029      *
3030      * @param  args
3031      *         Arguments referenced by the format specifiers in the format
3032      *         string.  If there are more arguments than format specifiers, the
3033      *         extra arguments are ignored.  The number of arguments is
3034      *         variable and may be zero.  The maximum number of arguments is
3035      *         limited by the maximum dimension of a Java array as defined by
3036      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
3037      *         The behaviour on a
3038      *         {@code null} argument depends on the
3039      *         <a href="../util/Formatter.html#syntax">conversion</a>.
3040      *
3041      * @throws  java.util.IllegalFormatException
3042      *          If a format string contains an illegal syntax, a format
3043      *          specifier that is incompatible with the given arguments,
3044      *          insufficient arguments given the format string, or other
3045      *          illegal conditions.  For specification of all possible
3046      *          formatting errors, see the <a
3047      *          href="../util/Formatter.html#detail">Details</a> section of the
3048      *          formatter class specification
3049      *
3050      * @return  A formatted string
3051      *
3052      * @see  java.util.Formatter
3053      * @since  1.5
3054      */
3055     public static String format(Locale l, String format, Object... args) {
3056         return new Formatter(l).format(format, args).toString();
3057     }
3058 
3059     /**
3060      * Returns the string representation of the {@code Object} argument.
3061      *
3062      * @param   obj   an {@code Object}.
3063      * @return  if the argument is {@code null}, then a string equal to
3064      *          {@code "null"}; otherwise, the value of
3065      *          {@code obj.toString()} is returned.
3066      * @see     java.lang.Object#toString()
3067      */
3068     public static String valueOf(Object obj) {
3069         return (obj == null) ? "null" : obj.toString();
3070     }
3071 
3072     /**
3073      * Returns the string representation of the {@code char} array
3074      * argument. The contents of the character array are copied; subsequent
3075      * modification of the character array does not affect the returned
3076      * string.
3077      *
3078      * @param   data     the character array.
3079      * @return  a {@code String} that contains the characters of the
3080      *          character array.
3081      */
3082     public static String valueOf(char data[]) {
3083         return new String(data);
3084     }
3085 
3086     /**
3087      * Returns the string representation of a specific subarray of the
3088      * {@code char} array argument.
3089      * <p>
3090      * The {@code offset} argument is the index of the first
3091      * character of the subarray. The {@code count} argument
3092      * specifies the length of the subarray. The contents of the subarray
3093      * are copied; subsequent modification of the character array does not
3094      * affect the returned string.
3095      *
3096      * @param   data     the character array.
3097      * @param   offset   initial offset of the subarray.
3098      * @param   count    length of the subarray.
3099      * @return  a {@code String} that contains the characters of the
3100      *          specified subarray of the character array.
3101      * @exception IndexOutOfBoundsException if {@code offset} is
3102      *          negative, or {@code count} is negative, or
3103      *          {@code offset+count} is larger than
3104      *          {@code data.length}.
3105      */
3106     public static String valueOf(char data[], int offset, int count) {
3107         return new String(data, offset, count);
3108     }
3109 
3110     /**
3111      * Equivalent to {@link #valueOf(char[], int, int)}.
3112      *
3113      * @param   data     the character array.
3114      * @param   offset   initial offset of the subarray.
3115      * @param   count    length of the subarray.
3116      * @return  a {@code String} that contains the characters of the
3117      *          specified subarray of the character array.
3118      * @exception IndexOutOfBoundsException if {@code offset} is
3119      *          negative, or {@code count} is negative, or
3120      *          {@code offset+count} is larger than
3121      *          {@code data.length}.
3122      */
3123     public static String copyValueOf(char data[], int offset, int count) {
3124         return new String(data, offset, count);
3125     }
3126 
3127     /**
3128      * Equivalent to {@link #valueOf(char[])}.
3129      *
3130      * @param   data   the character array.
3131      * @return  a {@code String} that contains the characters of the
3132      *          character array.
3133      */
3134     public static String copyValueOf(char data[]) {
3135         return new String(data);
3136     }
3137 
3138     /**
3139      * Returns the string representation of the {@code boolean} argument.
3140      *
3141      * @param   b   a {@code boolean}.
3142      * @return  if the argument is {@code true}, a string equal to
3143      *          {@code "true"} is returned; otherwise, a string equal to
3144      *          {@code "false"} is returned.
3145      */
3146     public static String valueOf(boolean b) {
3147         return b ? "true" : "false";
3148     }
3149 
3150     /**
3151      * Returns the string representation of the {@code char}
3152      * argument.
3153      *
3154      * @param   c   a {@code char}.
3155      * @return  a string of length {@code 1} containing
3156      *          as its single character the argument {@code c}.
3157      */
3158     public static String valueOf(char c) {
3159         if (COMPACT_STRINGS && StringLatin1.canEncode(c)) {
3160             return new String(StringLatin1.toBytes(c), LATIN1);
3161         }
3162         return new String(StringUTF16.toBytes(c), UTF16);
3163     }
3164 
3165     /**
3166      * Returns the string representation of the {@code int} argument.
3167      * <p>
3168      * The representation is exactly the one returned by the
3169      * {@code Integer.toString} method of one argument.
3170      *
3171      * @param   i   an {@code int}.
3172      * @return  a string representation of the {@code int} argument.
3173      * @see     java.lang.Integer#toString(int, int)
3174      */
3175     public static String valueOf(int i) {
3176         return Integer.toString(i);
3177     }
3178 
3179     /**
3180      * Returns the string representation of the {@code long} argument.
3181      * <p>
3182      * The representation is exactly the one returned by the
3183      * {@code Long.toString} method of one argument.
3184      *
3185      * @param   l   a {@code long}.
3186      * @return  a string representation of the {@code long} argument.
3187      * @see     java.lang.Long#toString(long)
3188      */
3189     public static String valueOf(long l) {
3190         return Long.toString(l);
3191     }
3192 
3193     /**
3194      * Returns the string representation of the {@code float} argument.
3195      * <p>
3196      * The representation is exactly the one returned by the
3197      * {@code Float.toString} method of one argument.
3198      *
3199      * @param   f   a {@code float}.
3200      * @return  a string representation of the {@code float} argument.
3201      * @see     java.lang.Float#toString(float)
3202      */
3203     public static String valueOf(float f) {
3204         return Float.toString(f);
3205     }
3206 
3207     /**
3208      * Returns the string representation of the {@code double} argument.
3209      * <p>
3210      * The representation is exactly the one returned by the
3211      * {@code Double.toString} method of one argument.
3212      *
3213      * @param   d   a {@code double}.
3214      * @return  a  string representation of the {@code double} argument.
3215      * @see     java.lang.Double#toString(double)
3216      */
3217     public static String valueOf(double d) {
3218         return Double.toString(d);
3219     }
3220 
3221     /**
3222      * Returns a canonical representation for the string object.
3223      * <p>
3224      * A pool of strings, initially empty, is maintained privately by the
3225      * class {@code String}.
3226      * <p>
3227      * When the intern method is invoked, if the pool already contains a
3228      * string equal to this {@code String} object as determined by
3229      * the {@link #equals(Object)} method, then the string from the pool is
3230      * returned. Otherwise, this {@code String} object is added to the
3231      * pool and a reference to this {@code String} object is returned.
3232      * <p>
3233      * It follows that for any two strings {@code s} and {@code t},
3234      * {@code s.intern() == t.intern()} is {@code true}
3235      * if and only if {@code s.equals(t)} is {@code true}.
3236      * <p>
3237      * All literal strings and string-valued constant expressions are
3238      * interned. String literals are defined in section 3.10.5 of the
3239      * <cite>The Java&trade; Language Specification</cite>.
3240      *
3241      * @return  a string that has the same contents as this string, but is
3242      *          guaranteed to be from a pool of unique strings.
3243      * @jls 3.10.5 String Literals
3244      */
3245     public native String intern();
3246 
3247     /**
3248      * Returns a string whose value is the concatenation of this
3249      * string repeated {@code count} times.
3250      * <p>
3251      * If this string is empty or count is zero then the empty
3252      * string is returned.
3253      *
3254      * @param   count number of times to repeat
3255      *
3256      * @return  A string composed of this string repeated
3257      *          {@code count} times or the empty string if this
3258      *          string is empty or count is zero
3259      *
3260      * @throws  IllegalArgumentException if the {@code count} is
3261      *          negative.
3262      *
3263      * @since 11
3264      */
3265     public String repeat(int count) {
3266         if (count < 0) {
3267             throw new IllegalArgumentException("count is negative: " + count);
3268         }
3269         if (count == 1) {
3270             return this;
3271         }
3272         final int len = value.length;
3273         if (len == 0 || count == 0) {
3274             return "";
3275         }
3276         if (len == 1) {
3277             final byte[] single = new byte[count];
3278             Arrays.fill(single, value[0]);
3279             return new String(single, coder);
3280         }
3281         if (Integer.MAX_VALUE / count < len) {
3282             throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
3283                     " times will produce a String exceeding maximum size.");
3284         }
3285         final int limit = len * count;
3286         final byte[] multiple = new byte[limit];
3287         System.arraycopy(value, 0, multiple, 0, len);
3288         int copied = len;
3289         for (; copied < limit - copied; copied <<= 1) {
3290             System.arraycopy(multiple, 0, multiple, copied, copied);
3291         }
3292         System.arraycopy(multiple, 0, multiple, copied, limit - copied);
3293         return new String(multiple, coder);
3294     }
3295 
3296     ////////////////////////////////////////////////////////////////
3297 
3298     /**
3299      * Copy character bytes from this string into dst starting at dstBegin.
3300      * This method doesn't perform any range checking.
3301      *
3302      * Invoker guarantees: dst is in UTF16 (inflate itself for asb), if two
3303      * coders are different, and dst is big enough (range check)
3304      *
3305      * @param dstBegin  the char index, not offset of byte[]
3306      * @param coder     the coder of dst[]
3307      */
3308     void getBytes(byte dst[], int dstBegin, byte coder) {
3309         if (coder() == coder) {
3310             System.arraycopy(value, 0, dst, dstBegin << coder, value.length);
3311         } else {    // this.coder == LATIN && coder == UTF16
3312             StringLatin1.inflate(value, 0, dst, dstBegin, value.length);
3313         }
3314     }
3315 
3316     /*
3317      * Package private constructor. Trailing Void argument is there for
3318      * disambiguating it against other (public) constructors.
3319      *
3320      * Stores the char[] value into a byte[] that each byte represents
3321      * the8 low-order bits of the corresponding character, if the char[]
3322      * contains only latin1 character. Or a byte[] that stores all
3323      * characters in their byte sequences defined by the {@code StringUTF16}.
3324      */
3325     String(char[] value, int off, int len, Void sig) {
3326         if (len == 0) {
3327             this.value = "".value;
3328             this.coder = "".coder;
3329             return;
3330         }
3331         if (COMPACT_STRINGS) {
3332             byte[] val = StringUTF16.compress(value, off, len);
3333             if (val != null) {
3334                 this.value = val;
3335                 this.coder = LATIN1;
3336                 return;
3337             }
3338         }
3339         this.coder = UTF16;
3340         this.value = StringUTF16.toBytes(value, off, len);
3341     }
3342 
3343     /*
3344      * Package private constructor. Trailing Void argument is there for
3345      * disambiguating it against other (public) constructors.
3346      */
3347     String(AbstractStringBuilder asb, Void sig) {
3348         byte[] val = asb.getValue();
3349         int length = asb.length();
3350         if (asb.isLatin1()) {
3351             this.coder = LATIN1;
3352             this.value = Arrays.copyOfRange(val, 0, length);
3353         } else {
3354             if (COMPACT_STRINGS) {
3355                 byte[] buf = StringUTF16.compress(val, 0, length);
3356                 if (buf != null) {
3357                     this.coder = LATIN1;
3358                     this.value = buf;
3359                     return;
3360                 }
3361             }
3362             this.coder = UTF16;
3363             this.value = Arrays.copyOfRange(val, 0, length << 1);
3364         }
3365     }
3366 
3367    /*
3368     * Package private constructor which shares value array for speed.
3369     */
3370     String(byte[] value, byte coder) {
3371         this.value = value;
3372         this.coder = coder;
3373     }
3374 
3375     byte coder() {
3376         return COMPACT_STRINGS ? coder : UTF16;
3377     }
3378 
3379     byte[] value() {
3380         return value;
3381     }
3382 
3383     private boolean isLatin1() {
3384         return COMPACT_STRINGS && coder == LATIN1;
3385     }
3386 
3387     @Native static final byte LATIN1 = 0;
3388     @Native static final byte UTF16  = 1;
3389 
3390     /*
3391      * StringIndexOutOfBoundsException  if {@code index} is
3392      * negative or greater than or equal to {@code length}.
3393      */
3394     static void checkIndex(int index, int length) {
3395         if (index < 0 || index >= length) {
3396             throw new StringIndexOutOfBoundsException("index " + index +
3397                                                       ",length " + length);
3398         }
3399     }
3400 
3401     /*
3402      * StringIndexOutOfBoundsException  if {@code offset}
3403      * is negative or greater than {@code length}.
3404      */
3405     static void checkOffset(int offset, int length) {
3406         if (offset < 0 || offset > length) {
3407             throw new StringIndexOutOfBoundsException("offset " + offset +
3408                                                       ",length " + length);
3409         }
3410     }
3411 
3412     /*
3413      * Check {@code offset}, {@code count} against {@code 0} and {@code length}
3414      * bounds.
3415      *
3416      * @throws  StringIndexOutOfBoundsException
3417      *          If {@code offset} is negative, {@code count} is negative,
3418      *          or {@code offset} is greater than {@code length - count}
3419      */
3420     static void checkBoundsOffCount(int offset, int count, int length) {
3421         if (offset < 0 || count < 0 || offset > length - count) {
3422             throw new StringIndexOutOfBoundsException(
3423                 "offset " + offset + ", count " + count + ", length " + length);
3424         }
3425     }
3426 
3427     /*
3428      * Check {@code begin}, {@code end} against {@code 0} and {@code length}
3429      * bounds.
3430      *
3431      * @throws  StringIndexOutOfBoundsException
3432      *          If {@code begin} is negative, {@code begin} is greater than
3433      *          {@code end}, or {@code end} is greater than {@code length}.
3434      */
3435     static void checkBoundsBeginEnd(int begin, int end, int length) {
3436         if (begin < 0 || begin > end || end > length) {
3437             throw new StringIndexOutOfBoundsException(
3438                 "begin " + begin + ", end " + end + ", length " + length);
3439         }
3440     }
3441 
3442     /**
3443      * Returns the string representation of the {@code codePoint}
3444      * argument.
3445      *
3446      * @param   codePoint a {@code codePoint}.
3447      * @return  a string of length {@code 1} or {@code 2} containing
3448      *          as its single character the argument {@code codePoint}.
3449      * @throws IllegalArgumentException if the specified
3450      *          {@code codePoint} is not a {@linkplain Character#isValidCodePoint
3451      *          valid Unicode code point}.
3452      */
3453     static String valueOfCodePoint(int codePoint) {
3454         if (COMPACT_STRINGS && StringLatin1.canEncode(codePoint)) {
3455             return new String(StringLatin1.toBytes((char)codePoint), LATIN1);
3456         } else if (Character.isBmpCodePoint(codePoint)) {
3457             return new String(StringUTF16.toBytes((char)codePoint), UTF16);
3458         } else if (Character.isSupplementaryCodePoint(codePoint)) {
3459             return new String(StringUTF16.toBytesSupplementary(codePoint), UTF16);
3460         }
3461 
3462         throw new IllegalArgumentException(
3463             format("Not a valid Unicode code point: 0x%X", codePoint));
3464     }
3465 
3466     /**
3467      * Returns an {@link Optional} containing the nominal descriptor for this
3468      * instance, which is the instance itself.
3469      *
3470      * @return an {@link Optional} describing the {@linkplain String} instance
3471      * @since 12
3472      */
3473     @Override
3474     public Optional<String> describeConstable() {
3475         return Optional.of(this);
3476     }
3477 
3478     /**
3479      * Resolves this instance as a {@link ConstantDesc}, the result of which is
3480      * the instance itself.
3481      *
3482      * @param lookup ignored
3483      * @return the {@linkplain String} instance
3484      * @since 12
3485      */
3486     @Override
3487     public String resolveConstantDesc(MethodHandles.Lookup lookup) {
3488         return this;
3489     }
3490 
3491 }