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