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