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