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