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