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 <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
 619      *
 620      * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
 621      * <tt>false</tt>
 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 <tt>String</tt> 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      * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
1236      * and has length <tt>len</tt>. The substring of other to be compared
1237      * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
1238      * result is <tt>false</tt> if and only if at least one of the following
1239      * is true:
1240      * <ul><li><tt>toffset</tt> is negative.
1241      * <li><tt>ooffset</tt> is negative.
1242      * <li><tt>toffset+len</tt> is greater than the length of this
1243      * <tt>String</tt> object.
1244      * <li><tt>ooffset+len</tt> is greater than the length of the other
1245      * argument.
1246      * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
1247      * such that:
1248      * <tt>this.charAt(toffset+<i>k</i>)&nbsp;!=&nbsp;other.charAt(ooffset+<i>k</i>)</tt>
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 <tt>String</tt> object is compared to a substring
1284      * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
1285      * substrings represent character sequences that are the same, ignoring
1286      * case if and only if <tt>ignoreCase</tt> is true. The substring of
1287      * this <tt>String</tt> object to be compared begins at index
1288      * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
1289      * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
1290      * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
1291      * at least one of the following is true:
1292      * <ul><li><tt>toffset</tt> is negative.
1293      * <li><tt>ooffset</tt> is negative.
1294      * <li><tt>toffset+len</tt> is greater than the length of this
1295      * <tt>String</tt> object.
1296      * <li><tt>ooffset+len</tt> is greater than the length of the other
1297      * argument.
1298      * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
1299      * integer <i>k</i> less than <tt>len</tt> such that:
1300      * <blockquote><pre>
1301      * this.charAt(toffset+k) != other.charAt(ooffset+k)
1302      * </pre></blockquote>
1303      * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
1304      * integer <i>k</i> less than <tt>len</tt> 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) && (<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) && (<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) && (<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) && (<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 && 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 StringBuffer 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   targetOffset offset of the target string.
1718      * @param   targetCount  count of the target string.
1719      * @param   fromIndex    the index to begin searching from.
1720      */
1721     static int indexOf(char[] source, int sourceOffset, int sourceCount,
1722             char[] target, int targetOffset, int targetCount,
1723             int fromIndex) {
1724         if (fromIndex >= sourceCount) {
1725             return (targetCount == 0 ? sourceCount : -1);
1726         }
1727         if (fromIndex < 0) {
1728             fromIndex = 0;
1729         }
1730         if (targetCount == 0) {
1731             return fromIndex;
1732         }
1733 
1734         char first = target[targetOffset];
1735         int max = sourceOffset + (sourceCount - targetCount);
1736 
1737         for (int i = sourceOffset + fromIndex; i <= max; i++) {
1738             /* Look for first character. */
1739             if (source[i] != first) {
1740                 while (++i <= max && source[i] != first);
1741             }
1742 
1743             /* Found first character, now look at the rest of v2 */
1744             if (i <= max) {
1745                 int j = i + 1;
1746                 int end = j + targetCount - 1;
1747                 for (int k = targetOffset + 1; j < end && source[j]
1748                         == target[k]; j++, k++);
1749 
1750                 if (j == end) {
1751                     /* Found whole string. */
1752                     return i - sourceOffset;
1753                 }
1754             }
1755         }
1756         return -1;
1757     }
1758 
1759     /**
1760      * Returns the index within this string of the last occurrence of the
1761      * specified substring.  The last occurrence of the empty string ""
1762      * is considered to occur at the index value {@code this.length()}.
1763      *
1764      * <p>The returned index is the largest value <i>k</i> for which:
1765      * <blockquote><pre>
1766      * this.startsWith(str, <i>k</i>)
1767      * </pre></blockquote>
1768      * If no such value of <i>k</i> exists, then {@code -1} is returned.
1769      *
1770      * @param   str   the substring to search for.
1771      * @return  the index of the last occurrence of the specified substring,
1772      *          or {@code -1} if there is no such occurrence.
1773      */
1774     public int lastIndexOf(String str) {
1775         return lastIndexOf(str, value.length);
1776     }
1777 
1778     /**
1779      * Returns the index within this string of the last occurrence of the
1780      * specified substring, searching backward starting at the specified index.
1781      *
1782      * <p>The returned index is the largest value <i>k</i> for which:
1783      * <blockquote><pre>
1784      * <i>k</i> &lt;= fromIndex && 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      * @param   fromIndex   the index to start the search from.
1790      * @return  the index of the last occurrence of the specified substring,
1791      *          searching backward from the specified index,
1792      *          or {@code -1} if there is no such occurrence.
1793      */
1794     public int lastIndexOf(String str, int fromIndex) {
1795         return lastIndexOf(value, 0, value.length,
1796                 str.value, 0, str.value.length, fromIndex);
1797     }
1798 
1799     /**
1800      * Code shared by String and StringBuffer to do searches. The
1801      * source is the character array being searched, and the target
1802      * is the string being searched for.
1803      *
1804      * @param   source       the characters being searched.
1805      * @param   sourceOffset offset of the source string.
1806      * @param   sourceCount  count of the source string.
1807      * @param   target       the characters being searched for.
1808      * @param   targetOffset offset of the target string.
1809      * @param   targetCount  count of the target string.
1810      * @param   fromIndex    the index to begin searching from.
1811      */
1812     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
1813             char[] target, int targetOffset, int targetCount,
1814             int fromIndex) {
1815         /*
1816          * Check arguments; return immediately where possible. For
1817          * consistency, don't check for null str.
1818          */
1819         int rightIndex = sourceCount - targetCount;
1820         if (fromIndex < 0) {
1821             return -1;
1822         }
1823         if (fromIndex > rightIndex) {
1824             fromIndex = rightIndex;
1825         }
1826         /* Empty string always matches. */
1827         if (targetCount == 0) {
1828             return fromIndex;
1829         }
1830 
1831         int strLastIndex = targetOffset + targetCount - 1;
1832         char strLastChar = target[strLastIndex];
1833         int min = sourceOffset + targetCount - 1;
1834         int i = min + fromIndex;
1835 
1836         startSearchForLastChar:
1837         while (true) {
1838             while (i >= min && source[i] != strLastChar) {
1839                 i--;
1840             }
1841             if (i < min) {
1842                 return -1;
1843             }
1844             int j = i - 1;
1845             int start = j - (targetCount - 1);
1846             int k = strLastIndex - 1;
1847 
1848             while (j > start) {
1849                 if (source[j--] != target[k--]) {
1850                     i--;
1851                     continue startSearchForLastChar;
1852                 }
1853             }
1854             return start - sourceOffset + 1;
1855         }
1856     }
1857 
1858     /**
1859      * Returns a new string that is a substring of this string. The
1860      * substring begins with the character at the specified index and
1861      * extends to the end of this string. <p>
1862      * Examples:
1863      * <blockquote><pre>
1864      * "unhappy".substring(2) returns "happy"
1865      * "Harbison".substring(3) returns "bison"
1866      * "emptiness".substring(9) returns "" (an empty string)
1867      * </pre></blockquote>
1868      *
1869      * @param      beginIndex   the beginning index, inclusive.
1870      * @return     the specified substring.
1871      * @exception  IndexOutOfBoundsException  if
1872      *             {@code beginIndex} is negative or larger than the
1873      *             length of this {@code String} object.
1874      */
1875     public String substring(int beginIndex) {
1876         if (beginIndex < 0) {
1877             throw new StringIndexOutOfBoundsException(beginIndex);
1878         }
1879         int subLen = value.length - beginIndex;
1880         if (subLen < 0) {
1881             throw new StringIndexOutOfBoundsException(subLen);
1882         }
1883         return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
1884     }
1885 
1886     /**
1887      * Returns a new string that is a substring of this string. The
1888      * substring begins at the specified {@code beginIndex} and
1889      * extends to the character at index {@code endIndex - 1}.
1890      * Thus the length of the substring is {@code endIndex-beginIndex}.
1891      * <p>
1892      * Examples:
1893      * <blockquote><pre>
1894      * "hamburger".substring(4, 8) returns "urge"
1895      * "smiles".substring(1, 5) returns "mile"
1896      * </pre></blockquote>
1897      *
1898      * @param      beginIndex   the beginning index, inclusive.
1899      * @param      endIndex     the ending index, exclusive.
1900      * @return     the specified substring.
1901      * @exception  IndexOutOfBoundsException  if the
1902      *             {@code beginIndex} is negative, or
1903      *             {@code endIndex} is larger than the length of
1904      *             this {@code String} object, or
1905      *             {@code beginIndex} is larger than
1906      *             {@code endIndex}.
1907      */
1908     public String substring(int beginIndex, int endIndex) {
1909         if (beginIndex < 0) {
1910             throw new StringIndexOutOfBoundsException(beginIndex);
1911         }
1912         if (endIndex > value.length) {
1913             throw new StringIndexOutOfBoundsException(endIndex);
1914         }
1915         int subLen = endIndex - beginIndex;
1916         if (subLen < 0) {
1917             throw new StringIndexOutOfBoundsException(subLen);
1918         }
1919         return ((beginIndex == 0) && (endIndex == value.length)) ? this
1920                 : new String(value, beginIndex, subLen);
1921     }
1922 
1923     /**
1924      * Returns a new character sequence that is a subsequence of this sequence.
1925      *
1926      * <p> An invocation of this method of the form
1927      *
1928      * <blockquote><pre>
1929      * str.subSequence(begin,&nbsp;end)</pre></blockquote>
1930      *
1931      * behaves in exactly the same way as the invocation
1932      *
1933      * <blockquote><pre>
1934      * str.substring(begin,&nbsp;end)</pre></blockquote>
1935      *
1936      * This method is defined so that the {@code String} class can implement
1937      * the {@link CharSequence} interface. </p>
1938      *
1939      * @param   beginIndex   the begin index, inclusive.
1940      * @param   endIndex     the end index, exclusive.
1941      * @return  the specified subsequence.
1942      *
1943      * @throws  IndexOutOfBoundsException
1944      *          if {@code beginIndex} or {@code endIndex} is negative,
1945      *          if {@code endIndex} is greater than {@code length()},
1946      *          or if {@code beginIndex} is greater than {@code endIndex}
1947      *
1948      * @since 1.4
1949      * @spec JSR-51
1950      */
1951     public CharSequence subSequence(int beginIndex, int endIndex) {
1952         return this.substring(beginIndex, endIndex);
1953     }
1954 
1955     /**
1956      * Concatenates the specified string to the end of this string.
1957      * <p>
1958      * If the length of the argument string is {@code 0}, then this
1959      * {@code String} object is returned. Otherwise, a new
1960      * {@code String} object is created, representing a character
1961      * sequence that is the concatenation of the character sequence
1962      * represented by this {@code String} object and the character
1963      * sequence represented by the argument string.<p>
1964      * Examples:
1965      * <blockquote><pre>
1966      * "cares".concat("s") returns "caress"
1967      * "to".concat("get").concat("her") returns "together"
1968      * </pre></blockquote>
1969      *
1970      * @param   str   the {@code String} that is concatenated to the end
1971      *                of this {@code String}.
1972      * @return  a string that represents the concatenation of this object's
1973      *          characters followed by the string argument's characters.
1974      */
1975     public String concat(String str) {
1976         int otherLen = str.length();
1977         if (otherLen == 0) {
1978             return this;
1979         }
1980         int len = value.length;
1981         char buf[] = Arrays.copyOf(value, len + otherLen);
1982         str.getChars(buf, len);
1983         return new String(buf, true);
1984     }
1985 
1986     /**
1987      * Returns a new string resulting from replacing all occurrences of
1988      * {@code oldChar} in this string with {@code newChar}.
1989      * <p>
1990      * If the character {@code oldChar} does not occur in the
1991      * character sequence represented by this {@code String} object,
1992      * then a reference to this {@code String} object is returned.
1993      * Otherwise, a new {@code String} object is created that
1994      * represents a character sequence identical to the character sequence
1995      * represented by this {@code String} object, except that every
1996      * occurrence of {@code oldChar} is replaced by an occurrence
1997      * of {@code newChar}.
1998      * <p>
1999      * Examples:
2000      * <blockquote><pre>
2001      * "mesquite in your cellar".replace('e', 'o')
2002      *         returns "mosquito in your collar"
2003      * "the war of baronets".replace('r', 'y')
2004      *         returns "the way of bayonets"
2005      * "sparring with a purple porpoise".replace('p', 't')
2006      *         returns "starring with a turtle tortoise"
2007      * "JonL".replace('q', 'x') returns "JonL" (no change)
2008      * </pre></blockquote>
2009      *
2010      * @param   oldChar   the old character.
2011      * @param   newChar   the new character.
2012      * @return  a string derived from this string by replacing every
2013      *          occurrence of {@code oldChar} with {@code newChar}.
2014      */
2015     public String replace(char oldChar, char newChar) {
2016         if (oldChar != newChar) {
2017             int len = value.length;
2018             int i = -1;
2019             char[] val = value; /* avoid getfield opcode */
2020 
2021             while (++i < len) {
2022                 if (val[i] == oldChar) {
2023                     break;
2024                 }
2025             }
2026             if (i < len) {
2027                 char buf[] = new char[len];
2028                 for (int j = 0; j < i; j++) {
2029                     buf[j] = val[j];
2030                 }
2031                 while (i < len) {
2032                     char c = val[i];
2033                     buf[i] = (c == oldChar) ? newChar : c;
2034                     i++;
2035                 }
2036                 return new String(buf, true);
2037             }
2038         }
2039         return this;
2040     }
2041 
2042     /**
2043      * Tells whether or not this string matches the given <a
2044      * href="../util/regex/Pattern.html#sum">regular expression</a>.
2045      *
2046      * <p> An invocation of this method of the form
2047      * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
2048      * same result as the expression
2049      *
2050      * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
2051      * java.util.regex.Pattern#matches(String,CharSequence)
2052      * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
2053      *
2054      * @param   regex
2055      *          the regular expression to which this string is to be matched
2056      *
2057      * @return  <tt>true</tt> if, and only if, this string matches the
2058      *          given regular expression
2059      *
2060      * @throws  PatternSyntaxException
2061      *          if the regular expression's syntax is invalid
2062      *
2063      * @see java.util.regex.Pattern
2064      *
2065      * @since 1.4
2066      * @spec JSR-51
2067      */
2068     public boolean matches(String regex) {
2069         return Pattern.matches(regex, this);
2070     }
2071 
2072     /**
2073      * Returns true if and only if this string contains the specified
2074      * sequence of char values.
2075      *
2076      * @param s the sequence to search for
2077      * @return true if this string contains {@code s}, false otherwise
2078      * @throws NullPointerException if {@code s} is {@code null}
2079      * @since 1.5
2080      */
2081     public boolean contains(CharSequence s) {
2082         return indexOf(s.toString()) > -1;
2083     }
2084 
2085     /**
2086      * Replaces the first substring of this string that matches the given <a
2087      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2088      * given replacement.
2089      *
2090      * <p> An invocation of this method of the form
2091      * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2092      * yields exactly the same result as the expression
2093      *
2094      * <blockquote><tt>
2095      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2096      * compile}(</tt><i>regex</i><tt>).{@link
2097      * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2098      * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
2099      * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
2100      *
2101      *<p>
2102      * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2103      * replacement string may cause the results to be different than if it were
2104      * being treated as a literal replacement string; see
2105      * {@link java.util.regex.Matcher#replaceFirst}.
2106      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2107      * meaning of these characters, if desired.
2108      *
2109      * @param   regex
2110      *          the regular expression to which this string is to be matched
2111      * @param   replacement
2112      *          the string to be substituted for the first match
2113      *
2114      * @return  The resulting <tt>String</tt>
2115      *
2116      * @throws  PatternSyntaxException
2117      *          if the regular expression's syntax is invalid
2118      *
2119      * @see java.util.regex.Pattern
2120      *
2121      * @since 1.4
2122      * @spec JSR-51
2123      */
2124     public String replaceFirst(String regex, String replacement) {
2125         return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
2126     }
2127 
2128     /**
2129      * Replaces each substring of this string that matches the given <a
2130      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2131      * given replacement.
2132      *
2133      * <p> An invocation of this method of the form
2134      * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
2135      * yields exactly the same result as the expression
2136      *
2137      * <blockquote><tt>
2138      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2139      * compile}(</tt><i>regex</i><tt>).{@link
2140      * java.util.regex.Pattern#matcher(java.lang.CharSequence)
2141      * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
2142      * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
2143      *
2144      *<p>
2145      * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
2146      * replacement string may cause the results to be different than if it were
2147      * being treated as a literal replacement string; see
2148      * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2149      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2150      * meaning of these characters, if desired.
2151      *
2152      * @param   regex
2153      *          the regular expression to which this string is to be matched
2154      * @param   replacement
2155      *          the string to be substituted for each match
2156      *
2157      * @return  The resulting <tt>String</tt>
2158      *
2159      * @throws  PatternSyntaxException
2160      *          if the regular expression's syntax is invalid
2161      *
2162      * @see java.util.regex.Pattern
2163      *
2164      * @since 1.4
2165      * @spec JSR-51
2166      */
2167     public String replaceAll(String regex, String replacement) {
2168         return Pattern.compile(regex).matcher(this).replaceAll(replacement);
2169     }
2170 
2171     /**
2172      * Replaces each substring of this string that matches the literal target
2173      * sequence with the specified literal replacement sequence. The
2174      * replacement proceeds from the beginning of the string to the end, for
2175      * example, replacing "aa" with "b" in the string "aaa" will result in
2176      * "ba" rather than "ab".
2177      *
2178      * @param  target The sequence of char values to be replaced
2179      * @param  replacement The replacement sequence of char values
2180      * @return  The resulting string
2181      * @throws NullPointerException if {@code target} or
2182      *         {@code replacement} is {@code null}.
2183      * @since 1.5
2184      */
2185     public String replace(CharSequence target, CharSequence replacement) {
2186         return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
2187                 this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
2188     }
2189 
2190     /**
2191      * Splits this string around matches of the given
2192      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2193      *
2194      * <p> The array returned by this method contains each substring of this
2195      * string that is terminated by another substring that matches the given
2196      * expression or is terminated by the end of the string.  The substrings in
2197      * the array are in the order in which they occur in this string.  If the
2198      * expression does not match any part of the input then the resulting array
2199      * has just one element, namely this string.
2200      *
2201      * <p> The <tt>limit</tt> parameter controls the number of times the
2202      * pattern is applied and therefore affects the length of the resulting
2203      * array.  If the limit <i>n</i> is greater than zero then the pattern
2204      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
2205      * length will be no greater than <i>n</i>, and the array's last entry
2206      * will contain all input beyond the last matched delimiter.  If <i>n</i>
2207      * is non-positive then the pattern will be applied as many times as
2208      * possible and the array can have any length.  If <i>n</i> is zero then
2209      * the pattern will be applied as many times as possible, the array can
2210      * have any length, and trailing empty strings will be discarded.
2211      *
2212      * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
2213      * following results with these parameters:
2214      *
2215      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
2216      * <tr>
2217      *     <th>Regex</th>
2218      *     <th>Limit</th>
2219      *     <th>Result</th>
2220      * </tr>
2221      * <tr><td align=center>:</td>
2222      *     <td align=center>2</td>
2223      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
2224      * <tr><td align=center>:</td>
2225      *     <td align=center>5</td>
2226      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2227      * <tr><td align=center>:</td>
2228      *     <td align=center>-2</td>
2229      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2230      * <tr><td align=center>o</td>
2231      *     <td align=center>5</td>
2232      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2233      * <tr><td align=center>o</td>
2234      *     <td align=center>-2</td>
2235      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
2236      * <tr><td align=center>o</td>
2237      *     <td align=center>0</td>
2238      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2239      * </table></blockquote>
2240      *
2241      * <p> An invocation of this method of the form
2242      * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
2243      * yields the same result as the expression
2244      *
2245      * <blockquote>
2246      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
2247      * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
2248      * java.util.regex.Pattern#split(java.lang.CharSequence,int)
2249      * split}<tt>(</tt><i>str</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
2250      * </blockquote>
2251      *
2252      *
2253      * @param  regex
2254      *         the delimiting regular expression
2255      *
2256      * @param  limit
2257      *         the result threshold, as described above
2258      *
2259      * @return  the array of strings computed by splitting this string
2260      *          around matches of the given regular expression
2261      *
2262      * @throws  PatternSyntaxException
2263      *          if the regular expression's syntax is invalid
2264      *
2265      * @see java.util.regex.Pattern
2266      *
2267      * @since 1.4
2268      * @spec JSR-51
2269      */
2270     public String[] split(String regex, int limit) {
2271         /* fastpath if the regex is a
2272          (1)one-char String and this character is not one of the
2273             RegEx's meta characters ".$|()[{^?*+\\", or
2274          (2)two-char String and the first char is the backslash and
2275             the second is not the ascii digit or ascii letter.
2276          */
2277         char ch = 0;
2278         if (((regex.value.length == 1 &&
2279              ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
2280              (regex.length() == 2 &&
2281               regex.charAt(0) == '\\' &&
2282               (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
2283               ((ch-'a')|('z'-ch)) < 0 &&
2284               ((ch-'A')|('Z'-ch)) < 0)) &&
2285             (ch < Character.MIN_HIGH_SURROGATE ||
2286              ch > Character.MAX_LOW_SURROGATE))
2287         {
2288             int off = 0;
2289             int next = 0;
2290             boolean limited = limit > 0;
2291             ArrayList<String> list = new ArrayList<>();
2292             while ((next = indexOf(ch, off)) != -1) {
2293                 if (!limited || list.size() < limit - 1) {
2294                     list.add(substring(off, next));
2295                     off = next + 1;
2296                 } else {    // last one
2297                     //assert (list.size() == limit - 1);
2298                     list.add(substring(off, value.length));
2299                     off = value.length;
2300                     break;
2301                 }
2302             }
2303             // If no match was found, return this
2304             if (off == 0)
2305                 return new String[]{this};
2306 
2307             // Add remaining segment
2308             if (!limited || list.size() < limit)
2309                 list.add(substring(off, value.length));
2310 
2311             // Construct result
2312             int resultSize = list.size();
2313             if (limit == 0)
2314                 while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
2315                     resultSize--;
2316             String[] result = new String[resultSize];
2317             return list.subList(0, resultSize).toArray(result);
2318         }
2319         return Pattern.compile(regex).split(this, limit);
2320     }
2321 
2322     /**
2323      * Splits this string around matches of the given <a
2324      * href="../util/regex/Pattern.html#sum">regular expression</a>.
2325      *
2326      * <p> This method works as if by invoking the two-argument {@link
2327      * #split(String, int) split} method with the given expression and a limit
2328      * argument of zero.  Trailing empty strings are therefore not included in
2329      * the resulting array.
2330      *
2331      * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
2332      * results with these expressions:
2333      *
2334      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
2335      * <tr>
2336      *  <th>Regex</th>
2337      *  <th>Result</th>
2338      * </tr>
2339      * <tr><td align=center>:</td>
2340      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
2341      * <tr><td align=center>o</td>
2342      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
2343      * </table></blockquote>
2344      *
2345      *
2346      * @param  regex
2347      *         the delimiting regular expression
2348      *
2349      * @return  the array of strings computed by splitting this string
2350      *          around matches of the given regular expression
2351      *
2352      * @throws  PatternSyntaxException
2353      *          if the regular expression's syntax is invalid
2354      *
2355      * @see java.util.regex.Pattern
2356      *
2357      * @since 1.4
2358      * @spec JSR-51
2359      */
2360     public String[] split(String regex) {
2361         return split(regex, 0);
2362     }
2363 
2364     /**
2365      * Set the value of this {@code String} to {@code n} concatenated copies of the
2366      * current value.  If {@code n == 0}, then set the value to the empty string.
2367      * 
2368      * @param n the number of times to add the current value
2369      * @return a reference to this String
2370      * @throws IllegalArgumentException if n < 0
2371      * @since 1.8
2372      */
2373     public String repeat( int n ) {
2374         if (n < 0) {
2375             throw new IllegalArgumentException( "n < 0");
2376         }
2377         return new StringBuilder().append(n, this).toString();
2378     }
2379 
2380     /**
2381      * Converts all of the characters in this {@code String} to lower
2382      * case using the rules of the given {@code Locale}.  Case mapping is based
2383      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2384      * class. Since case mappings are not always 1:1 char mappings, the resulting
2385      * {@code String} may be a different length than the original {@code String}.
2386      * <p>
2387      * Examples of lowercase  mappings are in the following table:
2388      * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
2389      * <tr>
2390      *   <th>Language Code of Locale</th>
2391      *   <th>Upper Case</th>
2392      *   <th>Lower Case</th>
2393      *   <th>Description</th>
2394      * </tr>
2395      * <tr>
2396      *   <td>tr (Turkish)</td>
2397      *   <td>&#92;u0130</td>
2398      *   <td>&#92;u0069</td>
2399      *   <td>capital letter I with dot above -&gt; small letter i</td>
2400      * </tr>
2401      * <tr>
2402      *   <td>tr (Turkish)</td>
2403      *   <td>&#92;u0049</td>
2404      *   <td>&#92;u0131</td>
2405      *   <td>capital letter I -&gt; small letter dotless i </td>
2406      * </tr>
2407      * <tr>
2408      *   <td>(all)</td>
2409      *   <td>French Fries</td>
2410      *   <td>french fries</td>
2411      *   <td>lowercased all chars in String</td>
2412      * </tr>
2413      * <tr>
2414      *   <td>(all)</td>
2415      *   <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
2416      *       <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
2417      *       <img src="doc-files/capsigma.gif" alt="capsigma"></td>
2418      *   <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
2419      *       <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
2420      *       <img src="doc-files/sigma1.gif" alt="sigma"></td>
2421      *   <td>lowercased all chars in String</td>
2422      * </tr>
2423      * </table>
2424      *
2425      * @param locale use the case transformation rules for this locale
2426      * @return the {@code String}, converted to lowercase.
2427      * @see     java.lang.String#toLowerCase()
2428      * @see     java.lang.String#toUpperCase()
2429      * @see     java.lang.String#toUpperCase(Locale)
2430      * @since   1.1
2431      */
2432     public String toLowerCase(Locale locale) {
2433         if (locale == null) {
2434             throw new NullPointerException();
2435         }
2436 
2437         int firstUpper;
2438         final int len = value.length;
2439 
2440         /* Now check if there are any characters that need to be changed. */
2441         scan: {
2442             for (firstUpper = 0 ; firstUpper < len; ) {
2443                 char c = value[firstUpper];
2444                 if ((c >= Character.MIN_HIGH_SURROGATE)
2445                         && (c <= Character.MAX_HIGH_SURROGATE)) {
2446                     int supplChar = codePointAt(firstUpper);
2447                     if (supplChar != Character.toLowerCase(supplChar)) {
2448                         break scan;
2449                     }
2450                     firstUpper += Character.charCount(supplChar);
2451                 } else {
2452                     if (c != Character.toLowerCase(c)) {
2453                         break scan;
2454                     }
2455                     firstUpper++;
2456                 }
2457             }
2458             return this;
2459         }
2460 
2461         char[] result = new char[len];
2462         int resultOffset = 0;  /* result may grow, so i+resultOffset
2463                                 * is the write location in result */
2464 
2465         /* Just copy the first few lowerCase characters. */
2466         System.arraycopy(value, 0, result, 0, firstUpper);
2467 
2468         String lang = locale.getLanguage();
2469         boolean localeDependent =
2470                 (lang == "tr" || lang == "az" || lang == "lt");
2471         char[] lowerCharArray;
2472         int lowerChar;
2473         int srcChar;
2474         int srcCount;
2475         for (int i = firstUpper; i < len; i += srcCount) {
2476             srcChar = (int)value[i];
2477             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
2478                     && (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2479                 srcChar = codePointAt(i);
2480                 srcCount = Character.charCount(srcChar);
2481             } else {
2482                 srcCount = 1;
2483             }
2484             if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
2485                 lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
2486             } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
2487                 lowerChar = Character.ERROR;
2488             } else {
2489                 lowerChar = Character.toLowerCase(srcChar);
2490             }
2491             if ((lowerChar == Character.ERROR)
2492                     || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2493                 if (lowerChar == Character.ERROR) {
2494                     if (!localeDependent && srcChar == '\u0130') {
2495                         lowerCharArray =
2496                                 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
2497                     } else {
2498                         lowerCharArray =
2499                                 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
2500                     }
2501                 } else if (srcCount == 2) {
2502                     resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
2503                     continue;
2504                 } else {
2505                     lowerCharArray = Character.toChars(lowerChar);
2506                 }
2507 
2508                 /* Grow result if needed */
2509                 int mapLen = lowerCharArray.length;
2510                 if (mapLen > srcCount) {
2511                     char[] result2 = new char[result.length + mapLen - srcCount];
2512                     System.arraycopy(result, 0, result2, 0, i + resultOffset);
2513                     result = result2;
2514                 }
2515                 for (int x = 0; x < mapLen; ++x) {
2516                     result[i + resultOffset + x] = lowerCharArray[x];
2517                 }
2518                 resultOffset += (mapLen - srcCount);
2519             } else {
2520                 result[i + resultOffset] = (char)lowerChar;
2521             }
2522         }
2523         return new String(result, 0, len + resultOffset);
2524     }
2525 
2526     /**
2527      * Converts all of the characters in this {@code String} to lower
2528      * case using the rules of the default locale. This is equivalent to calling
2529      * {@code toLowerCase(Locale.getDefault())}.
2530      * <p>
2531      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2532      * results if used for strings that are intended to be interpreted locale
2533      * independently.
2534      * Examples are programming language identifiers, protocol keys, and HTML
2535      * tags.
2536      * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
2537      * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
2538      * LATIN SMALL LETTER DOTLESS I character.
2539      * To obtain correct results for locale insensitive strings, use
2540      * {@code toLowerCase(Locale.ENGLISH)}.
2541      * <p>
2542      * @return  the {@code String}, converted to lowercase.
2543      * @see     java.lang.String#toLowerCase(Locale)
2544      */
2545     public String toLowerCase() {
2546         return toLowerCase(Locale.getDefault());
2547     }
2548 
2549     /**
2550      * Converts all of the characters in this {@code String} to upper
2551      * case using the rules of the given {@code Locale}. Case mapping is based
2552      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
2553      * class. Since case mappings are not always 1:1 char mappings, the resulting
2554      * {@code String} may be a different length than the original {@code String}.
2555      * <p>
2556      * Examples of locale-sensitive and 1:M case mappings are in the following table.
2557      * <p>
2558      * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
2559      * <tr>
2560      *   <th>Language Code of Locale</th>
2561      *   <th>Lower Case</th>
2562      *   <th>Upper Case</th>
2563      *   <th>Description</th>
2564      * </tr>
2565      * <tr>
2566      *   <td>tr (Turkish)</td>
2567      *   <td>&#92;u0069</td>
2568      *   <td>&#92;u0130</td>
2569      *   <td>small letter i -&gt; capital letter I with dot above</td>
2570      * </tr>
2571      * <tr>
2572      *   <td>tr (Turkish)</td>
2573      *   <td>&#92;u0131</td>
2574      *   <td>&#92;u0049</td>
2575      *   <td>small letter dotless i -&gt; capital letter I</td>
2576      * </tr>
2577      * <tr>
2578      *   <td>(all)</td>
2579      *   <td>&#92;u00df</td>
2580      *   <td>&#92;u0053 &#92;u0053</td>
2581      *   <td>small letter sharp s -&gt; two letters: SS</td>
2582      * </tr>
2583      * <tr>
2584      *   <td>(all)</td>
2585      *   <td>Fahrvergn&uuml;gen</td>
2586      *   <td>FAHRVERGN&Uuml;GEN</td>
2587      *   <td></td>
2588      * </tr>
2589      * </table>
2590      * @param locale use the case transformation rules for this locale
2591      * @return the {@code String}, converted to uppercase.
2592      * @see     java.lang.String#toUpperCase()
2593      * @see     java.lang.String#toLowerCase()
2594      * @see     java.lang.String#toLowerCase(Locale)
2595      * @since   1.1
2596      */
2597     public String toUpperCase(Locale locale) {
2598         if (locale == null) {
2599             throw new NullPointerException();
2600         }
2601 
2602         int firstLower;
2603         final int len = value.length;
2604 
2605         /* Now check if there are any characters that need to be changed. */
2606         scan: {
2607             for (firstLower = 0 ; firstLower < len; ) {
2608                 int c = (int)value[firstLower];
2609                 int srcCount;
2610                 if ((c >= Character.MIN_HIGH_SURROGATE)
2611                         && (c <= Character.MAX_HIGH_SURROGATE)) {
2612                     c = codePointAt(firstLower);
2613                     srcCount = Character.charCount(c);
2614                 } else {
2615                     srcCount = 1;
2616                 }
2617                 int upperCaseChar = Character.toUpperCaseEx(c);
2618                 if ((upperCaseChar == Character.ERROR)
2619                         || (c != upperCaseChar)) {
2620                     break scan;
2621                 }
2622                 firstLower += srcCount;
2623             }
2624             return this;
2625         }
2626 
2627         char[] result = new char[len]; /* may grow */
2628         int resultOffset = 0;  /* result may grow, so i+resultOffset
2629          * is the write location in result */
2630 
2631         /* Just copy the first few upperCase characters. */
2632         System.arraycopy(value, 0, result, 0, firstLower);
2633 
2634         String lang = locale.getLanguage();
2635         boolean localeDependent =
2636                 (lang == "tr" || lang == "az" || lang == "lt");
2637         char[] upperCharArray;
2638         int upperChar;
2639         int srcChar;
2640         int srcCount;
2641         for (int i = firstLower; i < len; i += srcCount) {
2642             srcChar = (int)value[i];
2643             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
2644                 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
2645                 srcChar = codePointAt(i);
2646                 srcCount = Character.charCount(srcChar);
2647             } else {
2648                 srcCount = 1;
2649             }
2650             if (localeDependent) {
2651                 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
2652             } else {
2653                 upperChar = Character.toUpperCaseEx(srcChar);
2654             }
2655             if ((upperChar == Character.ERROR)
2656                     || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
2657                 if (upperChar == Character.ERROR) {
2658                     if (localeDependent) {
2659                         upperCharArray =
2660                                 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
2661                     } else {
2662                         upperCharArray = Character.toUpperCaseCharArray(srcChar);
2663                     }
2664                 } else if (srcCount == 2) {
2665                     resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
2666                     continue;
2667                 } else {
2668                     upperCharArray = Character.toChars(upperChar);
2669                 }
2670 
2671                 /* Grow result if needed */
2672                 int mapLen = upperCharArray.length;
2673                 if (mapLen > srcCount) {
2674                     char[] result2 = new char[result.length + mapLen - srcCount];
2675                     System.arraycopy(result, 0, result2, 0, i + resultOffset);
2676                     result = result2;
2677                 }
2678                 for (int x = 0; x < mapLen; ++x) {
2679                     result[i + resultOffset + x] = upperCharArray[x];
2680                 }
2681                 resultOffset += (mapLen - srcCount);
2682             } else {
2683                 result[i + resultOffset] = (char)upperChar;
2684             }
2685         }
2686         return new String(result, 0, len + resultOffset);
2687     }
2688 
2689     /**
2690      * Converts all of the characters in this {@code String} to upper
2691      * case using the rules of the default locale. This method is equivalent to
2692      * {@code toUpperCase(Locale.getDefault())}.
2693      * <p>
2694      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
2695      * results if used for strings that are intended to be interpreted locale
2696      * independently.
2697      * Examples are programming language identifiers, protocol keys, and HTML
2698      * tags.
2699      * For instance, {@code "title".toUpperCase()} in a Turkish locale
2700      * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
2701      * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
2702      * To obtain correct results for locale insensitive strings, use
2703      * {@code toUpperCase(Locale.ENGLISH)}.
2704      * <p>
2705      * @return  the {@code String}, converted to uppercase.
2706      * @see     java.lang.String#toUpperCase(Locale)
2707      */
2708     public String toUpperCase() {
2709         return toUpperCase(Locale.getDefault());
2710     }
2711 
2712     /**
2713      * Returns a copy of the string, with leading and trailing whitespace
2714      * omitted.
2715      * <p>
2716      * If this {@code String} object represents an empty character
2717      * sequence, or the first and last characters of character sequence
2718      * represented by this {@code String} object both have codes
2719      * greater than {@code '\u005Cu0020'} (the space character), then a
2720      * reference to this {@code String} object is returned.
2721      * <p>
2722      * Otherwise, if there is no character with a code greater than
2723      * {@code '\u005Cu0020'} in the string, then a new
2724      * {@code String} object representing an empty string is created
2725      * and returned.
2726      * <p>
2727      * Otherwise, let <i>k</i> be the index of the first character in the
2728      * string whose code is greater than {@code '\u005Cu0020'}, and let
2729      * <i>m</i> be the index of the last character in the string whose code
2730      * is greater than {@code '\u005Cu0020'}. A new {@code String}
2731      * object is created, representing the substring of this string that
2732      * begins with the character at index <i>k</i> and ends with the
2733      * character at index <i>m</i>-that is, the result of
2734      * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
2735      * <p>
2736      * This method may be used to trim whitespace (as defined above) from
2737      * the beginning and end of a string.
2738      *
2739      * @return  A copy of this string with leading and trailing white
2740      *          space removed, or this string if it has no leading or
2741      *          trailing white space.
2742      */
2743     public String trim() {
2744         int len = value.length;
2745         int st = 0;
2746         char[] val = value;    /* avoid getfield opcode */
2747 
2748         while ((st < len) && (val[st] <= ' ')) {
2749             st++;
2750         }
2751         while ((st < len) && (val[len - 1] <= ' ')) {
2752             len--;
2753         }
2754         return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
2755     }
2756 
2757     /**
2758      * This object (which is already a string!) is itself returned.
2759      *
2760      * @return  the string itself.
2761      */
2762     public String toString() {
2763         return this;
2764     }
2765 
2766     /**
2767      * Converts this string to a new character array.
2768      *
2769      * @return  a newly allocated character array whose length is the length
2770      *          of this string and whose contents are initialized to contain
2771      *          the character sequence represented by this string.
2772      */
2773     public char[] toCharArray() {
2774         // Cannot use Arrays.copyOf because of class initialization order issues
2775         char result[] = new char[value.length];
2776         System.arraycopy(value, 0, result, 0, value.length);
2777         return result;
2778     }
2779 
2780     /**
2781      * Returns a formatted string using the specified format string and
2782      * arguments.
2783      *
2784      * <p> The locale always used is the one returned by {@link
2785      * java.util.Locale#getDefault() Locale.getDefault()}.
2786      *
2787      * @param  format
2788      *         A <a href="../util/Formatter.html#syntax">format string</a>
2789      *
2790      * @param  args
2791      *         Arguments referenced by the format specifiers in the format
2792      *         string.  If there are more arguments than format specifiers, the
2793      *         extra arguments are ignored.  The number of arguments is
2794      *         variable and may be zero.  The maximum number of arguments is
2795      *         limited by the maximum dimension of a Java array as defined by
2796      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
2797      *         The behaviour on a
2798      *         <tt>null</tt> argument depends on the <a
2799      *         href="../util/Formatter.html#syntax">conversion</a>.
2800      *
2801      * @throws  IllegalFormatException
2802      *          If a format string contains an illegal syntax, a format
2803      *          specifier that is incompatible with the given arguments,
2804      *          insufficient arguments given the format string, or other
2805      *          illegal conditions.  For specification of all possible
2806      *          formatting errors, see the <a
2807      *          href="../util/Formatter.html#detail">Details</a> section of the
2808      *          formatter class specification.
2809      *
2810      * @throws  NullPointerException
2811      *          If the <tt>format</tt> is <tt>null</tt>
2812      *
2813      * @return  A formatted string
2814      *
2815      * @see  java.util.Formatter
2816      * @since  1.5
2817      */
2818     public static String format(String format, Object... args) {
2819         return new Formatter().format(format, args).toString();
2820     }
2821 
2822     /**
2823      * Returns a formatted string using the specified locale, format string,
2824      * and arguments.
2825      *
2826      * @param  l
2827      *         The {@linkplain java.util.Locale locale} to apply during
2828      *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
2829      *         is applied.
2830      *
2831      * @param  format
2832      *         A <a href="../util/Formatter.html#syntax">format string</a>
2833      *
2834      * @param  args
2835      *         Arguments referenced by the format specifiers in the format
2836      *         string.  If there are more arguments than format specifiers, the
2837      *         extra arguments are ignored.  The number of arguments is
2838      *         variable and may be zero.  The maximum number of arguments is
2839      *         limited by the maximum dimension of a Java array as defined by
2840      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
2841      *         The behaviour on a
2842      *         <tt>null</tt> argument depends on the <a
2843      *         href="../util/Formatter.html#syntax">conversion</a>.
2844      *
2845      * @throws  IllegalFormatException
2846      *          If a format string contains an illegal syntax, a format
2847      *          specifier that is incompatible with the given arguments,
2848      *          insufficient arguments given the format string, or other
2849      *          illegal conditions.  For specification of all possible
2850      *          formatting errors, see the <a
2851      *          href="../util/Formatter.html#detail">Details</a> section of the
2852      *          formatter class specification
2853      *
2854      * @throws  NullPointerException
2855      *          If the <tt>format</tt> is <tt>null</tt>
2856      *
2857      * @return  A formatted string
2858      *
2859      * @see  java.util.Formatter
2860      * @since  1.5
2861      */
2862     public static String format(Locale l, String format, Object... args) {
2863         return new Formatter(l).format(format, args).toString();
2864     }
2865 
2866     /**
2867      * Returns the string representation of the {@code Object} argument.
2868      *
2869      * @param   obj   an {@code Object}.
2870      * @return  if the argument is {@code null}, then a string equal to
2871      *          {@code "null"}; otherwise, the value of
2872      *          {@code obj.toString()} is returned.
2873      * @see     java.lang.Object#toString()
2874      */
2875     public static String valueOf(Object obj) {
2876         return (obj == null) ? "null" : obj.toString();
2877     }
2878 
2879     /**
2880      * Returns the string representation of the {@code char} array
2881      * argument. The contents of the character array are copied; subsequent
2882      * modification of the character array does not affect the newly
2883      * created string.
2884      *
2885      * @param   data   a {@code char} array.
2886      * @return  a newly allocated string representing the same sequence of
2887      *          characters contained in the character array argument.
2888      */
2889     public static String valueOf(char data[]) {
2890         return new String(data);
2891     }
2892 
2893     /**
2894      * Returns the string representation of a specific subarray of the
2895      * {@code char} array argument.
2896      * <p>
2897      * The {@code offset} argument is the index of the first
2898      * character of the subarray. The {@code count} argument
2899      * specifies the length of the subarray. The contents of the subarray
2900      * are copied; subsequent modification of the character array does not
2901      * affect the newly created string.
2902      *
2903      * @param   data     the character array.
2904      * @param   offset   the initial offset into the value of the
2905      *                  {@code String}.
2906      * @param   count    the length of the value of the {@code String}.
2907      * @return  a string representing the sequence of characters contained
2908      *          in the subarray of the character array argument.
2909      * @exception IndexOutOfBoundsException if {@code offset} is
2910      *          negative, or {@code count} is negative, or
2911      *          {@code offset+count} is larger than
2912      *          {@code data.length}.
2913      */
2914     public static String valueOf(char data[], int offset, int count) {
2915         return new String(data, offset, count);
2916     }
2917 
2918     /**
2919      * Returns a String that represents the character sequence in the
2920      * array specified.
2921      *
2922      * @param   data     the character array.
2923      * @param   offset   initial offset of the subarray.
2924      * @param   count    length of the subarray.
2925      * @return  a {@code String} that contains the characters of the
2926      *          specified subarray of the character array.
2927      */
2928     public static String copyValueOf(char data[], int offset, int count) {
2929         // All public String constructors now copy the data.
2930         return new String(data, offset, count);
2931     }
2932 
2933     /**
2934      * Returns a String that represents the character sequence in the
2935      * array specified.
2936      *
2937      * @param   data   the character array.
2938      * @return  a {@code String} that contains the characters of the
2939      *          character array.
2940      */
2941     public static String copyValueOf(char data[]) {
2942         return new String(data);
2943     }
2944 
2945     /**
2946      * Returns the string representation of the {@code boolean} argument.
2947      *
2948      * @param   b   a {@code boolean}.
2949      * @return  if the argument is {@code true}, a string equal to
2950      *          {@code "true"} is returned; otherwise, a string equal to
2951      *          {@code "false"} is returned.
2952      */
2953     public static String valueOf(boolean b) {
2954         return b ? "true" : "false";
2955     }
2956 
2957     /**
2958      * Returns the string representation of the {@code char}
2959      * argument.
2960      *
2961      * @param   c   a {@code char}.
2962      * @return  a string of length {@code 1} containing
2963      *          as its single character the argument {@code c}.
2964      */
2965     public static String valueOf(char c) {
2966         char data[] = {c};
2967         return new String(data, true);
2968     }
2969 
2970     /**
2971      * Returns the string representation of the {@code int} argument.
2972      * <p>
2973      * The representation is exactly the one returned by the
2974      * {@code Integer.toString} method of one argument.
2975      *
2976      * @param   i   an {@code int}.
2977      * @return  a string representation of the {@code int} argument.
2978      * @see     java.lang.Integer#toString(int, int)
2979      */
2980     public static String valueOf(int i) {
2981         return Integer.toString(i);
2982     }
2983 
2984     /**
2985      * Returns the string representation of the {@code long} argument.
2986      * <p>
2987      * The representation is exactly the one returned by the
2988      * {@code Long.toString} method of one argument.
2989      *
2990      * @param   l   a {@code long}.
2991      * @return  a string representation of the {@code long} argument.
2992      * @see     java.lang.Long#toString(long)
2993      */
2994     public static String valueOf(long l) {
2995         return Long.toString(l);
2996     }
2997 
2998     /**
2999      * Returns the string representation of the {@code float} argument.
3000      * <p>
3001      * The representation is exactly the one returned by the
3002      * {@code Float.toString} method of one argument.
3003      *
3004      * @param   f   a {@code float}.
3005      * @return  a string representation of the {@code float} argument.
3006      * @see     java.lang.Float#toString(float)
3007      */
3008     public static String valueOf(float f) {
3009         return Float.toString(f);
3010     }
3011 
3012     /**
3013      * Returns the string representation of the {@code double} argument.
3014      * <p>
3015      * The representation is exactly the one returned by the
3016      * {@code Double.toString} method of one argument.
3017      *
3018      * @param   d   a {@code double}.
3019      * @return  a  string representation of the {@code double} argument.
3020      * @see     java.lang.Double#toString(double)
3021      */
3022     public static String valueOf(double d) {
3023         return Double.toString(d);
3024     }
3025 
3026     /**
3027      * Returns a canonical representation for the string object.
3028      * <p>
3029      * A pool of strings, initially empty, is maintained privately by the
3030      * class {@code String}.
3031      * <p>
3032      * When the intern method is invoked, if the pool already contains a
3033      * string equal to this {@code String} object as determined by
3034      * the {@link #equals(Object)} method, then the string from the pool is
3035      * returned. Otherwise, this {@code String} object is added to the
3036      * pool and a reference to this {@code String} object is returned.
3037      * <p>
3038      * It follows that for any two strings {@code s} and {@code t},
3039      * {@code s.intern() == t.intern()} is {@code true}
3040      * if and only if {@code s.equals(t)} is {@code true}.
3041      * <p>
3042      * All literal strings and string-valued constant expressions are
3043      * interned. String literals are defined in section 3.10.5 of the
3044      * <cite>The Java&trade; Language Specification</cite>.
3045      *
3046      * @return  a string that has the same contents as this string, but is
3047      *          guaranteed to be from a pool of unique strings.
3048      */
3049     public native String intern();
3050 
3051     /**
3052      * Seed value used for each alternative hash calculated.
3053      */
3054     private static final int HASHING_SEED;
3055 
3056     static {
3057         long nanos = System.nanoTime();
3058         long now = System.currentTimeMillis();
3059         int SEED_MATERIAL[] = {
3060                 System.identityHashCode(String.class),
3061                 System.identityHashCode(System.class),
3062                 (int) (nanos >>> 32),
3063                 (int) nanos,
3064                 (int) (now >>> 32),
3065                 (int) now,
3066                 (int) (System.nanoTime() >>> 2)
3067         };
3068 
3069         // Use murmur3 to scramble the seeding material.
3070         // Inline implementation to avoid loading classes
3071         int h1 = 0;
3072 
3073         // body
3074         for(int k1 : SEED_MATERIAL) {
3075             k1 *= 0xcc9e2d51;
3076             k1 = (k1 << 15) | (k1 >>> 17);
3077             k1 *= 0x1b873593;
3078 
3079             h1 ^= k1;
3080             h1 = (h1 << 13) | (h1 >>> 19);
3081             h1 = h1 * 5 + 0xe6546b64;
3082         }
3083 
3084         // tail (always empty, as body is always 32-bit chunks)
3085 
3086         // finalization
3087 
3088         h1 ^= SEED_MATERIAL.length * 4;
3089 
3090         // finalization mix force all bits of a hash block to avalanche
3091         h1 ^= h1 >>> 16;
3092         h1 *= 0x85ebca6b;
3093         h1 ^= h1 >>> 13;
3094         h1 *= 0xc2b2ae35;
3095         h1 ^= h1 >>> 16;
3096 
3097         HASHING_SEED = h1;
3098     }
3099 
3100     /**
3101      * Cached value of the hashing algorithm result
3102      */
3103     private transient int hash32 = 0;
3104 
3105     /**
3106     * Return a 32-bit hash code value for this object.
3107     * <p>
3108     * The general contract of {@code hash32} is:
3109     * <ul>
3110     * <li>Whenever it is invoked on the same object more than once during
3111     *     an execution of a Java application, the {@code hash32} method
3112     *     must consistently return the same integer, provided no information
3113     *     used in {@code equals} comparisons on the object is modified.
3114     *     This integer need not remain consistent from one execution of an
3115     *     application to another execution of the same application.
3116     * <li>If two objects are equal according to the {@code equals(Object)}
3117     *     method, then calling the {@code hash32} method on each of
3118     *     the two objects must produce the same integer result.
3119     * <li>It is <em>not</em> required that if two objects are unequal
3120     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
3121     *     method, then calling the {@code hash32} method on each of the
3122     *     two objects must produce distinct integer results.  However, the
3123     *     programmer should be aware that producing distinct integer results
3124     *     for unequal objects may improve the performance of hash tables.
3125     * </ul>
3126     * <p/>
3127      * The hash value will never be zero.
3128     *
3129     * @return  a hash code value for this object.
3130     * @see     java.lang.Object#equals(java.lang.Object)
3131     */
3132     public int hash32() {
3133         int h = hash32;
3134         if (0 == h) {
3135            // harmless data race on hash32 here.
3136            h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length);
3137 
3138            // ensure result is not zero to avoid recalcing
3139            h = (0 != h) ? h : 1;
3140 
3141            hash32 = h;
3142         }
3143 
3144         return h;
3145     }
3146 
3147 }