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