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