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