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