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