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} class represents character strings. All
  42  * string literals in Java programs, such as {@code "abc"}, are
  43  * implemented as instances of this class.
  44  * <p>
  45  * Strings are constant; their values cannot be changed after they
  46  * are created. String buffers support mutable strings.
  47  * Because String objects are immutable they can be shared. For example:
  48  * <p><blockquote><pre>
  49  *     String str = "abc";
  50  * </pre></blockquote><p>
  51  * is equivalent to:
  52  * <p><blockquote><pre>
  53  *     char data[] = {'a', 'b', 'c'};
  54  *     String str = new String(data);
  55  * </pre></blockquote><p>
  56  * Here are some more examples of how strings can be used:
  57  * <p><blockquote><pre>
  58  *     System.out.println("abc");
  59  *     String cde = "cde";
  60  *     System.out.println("abc" + cde);
  61  *     String c = "abc".substring(2,3);
  62  *     String d = cde.substring(1, 2);
  63  * </pre></blockquote>
  64  * <p>
  65  * The class {@code String} includes methods for examining
  66  * individual characters of the sequence, for comparing strings, for
  67  * searching strings, for extracting substrings, and for creating a
  68  * copy of a string with all characters translated to uppercase or to
  69  * lowercase. Case mapping is based on the Unicode Standard version
  70  * specified by the {@link java.lang.Character Character} class.
  71  * <p>
  72  * The Java language provides special support for the string
  73  * concatenation operator (&nbsp;+&nbsp;), and for conversion of
  74  * other objects to strings. String concatenation is implemented
  75  * through the {@code StringBuilder}(or {@code StringBuffer})
  76  * class and its {@code append} method.
  77  * String conversions are implemented through the method
  78  * {@code toString}, defined by {@code Object} and
  79  * inherited by all classes in Java. For additional information on
  80  * string concatenation and conversion, see Gosling, Joy, and Steele,
  81  * <i>The Java Language Specification</i>.
  82  *
  83  * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
  84  * or method in this class will cause a {@link NullPointerException} to be
  85  * thrown.
  86  *
  87  * <p>A {@code String} represents a string in the UTF-16 format
  88  * in which <em>supplementary characters</em> are represented by <em>surrogate
  89  * pairs</em> (see the section <a href="Character.html#unicode">Unicode
  90  * Character Representations</a> in the {@code Character} class for
  91  * more information).
  92  * Index values refer to {@code char} code units, so a supplementary
  93  * character uses two positions in a {@code String}.
  94  * <p>The {@code String} class provides methods for dealing with
  95  * Unicode code points (i.e., characters), in addition to those for
  96  * dealing with Unicode code units (i.e., {@code char} values).
  97  *
  98  * @author  Lee Boynton
  99  * @author  Arthur van Hoff
 100  * @author  Martin Buchholz
 101  * @author  Ulf Zibis
 102  * @see     java.lang.Object#toString()
 103  * @see     java.lang.StringBuffer
 104  * @see     java.lang.StringBuilder
 105  * @see     java.nio.charset.Charset
 106  * @since   JDK1.0
 107  */
 108 
 109 public final class String
 110     implements java.io.Serializable, Comparable<String>, CharSequence {

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