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