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