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