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