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