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