rt/emul/mini/src/main/java/java/lang/String.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 07 May 2014 11:39:31 +0200
branchclosure
changeset 1546 0d62e32b04b2
parent 1513 ba912ef24b27
child 1548 225ba1d7bdc9
permissions -rw-r--r--
Copying to char array is expensive operation avoid it
     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.lang.reflect.InvocationTargetException;
    30 import java.lang.reflect.Method;
    31 import java.util.Comparator;
    32 import java.util.Locale;
    33 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
    34 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    35 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
    36 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
    37 import org.apidesign.bck2brwsr.emul.lang.System;
    38 
    39 /**
    40  * The <code>String</code> class represents character strings. All
    41  * string literals in Java programs, such as <code>"abc"</code>, are
    42  * implemented as instances of this class.
    43  * <p>
    44  * Strings are constant; their values cannot be changed after they
    45  * are created. String buffers support mutable strings.
    46  * Because String objects are immutable they can be shared. For example:
    47  * <p><blockquote><pre>
    48  *     String str = "abc";
    49  * </pre></blockquote><p>
    50  * is equivalent to:
    51  * <p><blockquote><pre>
    52  *     char data[] = {'a', 'b', 'c'};
    53  *     String str = new String(data);
    54  * </pre></blockquote><p>
    55  * Here are some more examples of how strings can be used:
    56  * <p><blockquote><pre>
    57  *     System.out.println("abc");
    58  *     String cde = "cde";
    59  *     System.out.println("abc" + cde);
    60  *     String c = "abc".substring(2,3);
    61  *     String d = cde.substring(1, 2);
    62  * </pre></blockquote>
    63  * <p>
    64  * The class <code>String</code> includes methods for examining
    65  * individual characters of the sequence, for comparing strings, for
    66  * searching strings, for extracting substrings, and for creating a
    67  * copy of a string with all characters translated to uppercase or to
    68  * lowercase. Case mapping is based on the Unicode Standard version
    69  * specified by the {@link java.lang.Character Character} class.
    70  * <p>
    71  * The Java language provides special support for the string
    72  * concatenation operator (&nbsp;+&nbsp;), and for conversion of
    73  * other objects to strings. String concatenation is implemented
    74  * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
    75  * class and its <code>append</code> method.
    76  * String conversions are implemented through the method
    77  * <code>toString</code>, defined by <code>Object</code> and
    78  * inherited by all classes in Java. For additional information on
    79  * string concatenation and conversion, see Gosling, Joy, and Steele,
    80  * <i>The Java Language Specification</i>.
    81  *
    82  * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
    83  * or method in this class will cause a {@link NullPointerException} to be
    84  * thrown.
    85  *
    86  * <p>A <code>String</code> represents a string in the UTF-16 format
    87  * in which <em>supplementary characters</em> are represented by <em>surrogate
    88  * pairs</em> (see the section <a href="Character.html#unicode">Unicode
    89  * Character Representations</a> in the <code>Character</code> class for
    90  * more information).
    91  * Index values refer to <code>char</code> code units, so a supplementary
    92  * character uses two positions in a <code>String</code>.
    93  * <p>The <code>String</code> class provides methods for dealing with
    94  * Unicode code points (i.e., characters), in addition to those for
    95  * dealing with Unicode code units (i.e., <code>char</code> values).
    96  *
    97  * @author  Lee Boynton
    98  * @author  Arthur van Hoff
    99  * @author  Martin Buchholz
   100  * @author  Ulf Zibis
   101  * @see     java.lang.Object#toString()
   102  * @see     java.lang.StringBuffer
   103  * @see     java.lang.StringBuilder
   104  * @see     java.nio.charset.Charset
   105  * @since   JDK1.0
   106  */
   107 
   108 @ExtraJavaScript(
   109     resource="/org/apidesign/vm4brwsr/emul/lang/java_lang_String.js",
   110     processByteCode=true
   111 )
   112 @JavaScriptPrototype(container = "String.prototype", prototype = "new String")
   113 public final class String
   114     implements java.io.Serializable, Comparable<String>, CharSequence
   115 {
   116     /** real string to delegate to */
   117     private Object r;
   118 
   119     /** use serialVersionUID from JDK 1.0.2 for interoperability */
   120     private static final long serialVersionUID = -6849794470754667710L;
   121 
   122     static {
   123         registerToString();
   124     }
   125     @JavaScriptBody(args = {}, body = 
   126           "var p = vm.java_lang_String(false);\n"
   127         + "p.toString = function() {\nreturn this._r().toString();\n};\n"
   128         + "p.valueOf = function() {\nreturn this._r().valueOf();\n}\n"
   129     )
   130     private static native void registerToString();
   131     
   132     /**
   133      * Class String is special cased within the Serialization Stream Protocol.
   134      *
   135      * A String instance is written initially into an ObjectOutputStream in the
   136      * following format:
   137      * <pre>
   138      *      <code>TC_STRING</code> (utf String)
   139      * </pre>
   140      * The String is written by method <code>DataOutput.writeUTF</code>.
   141      * A new handle is generated to  refer to all future references to the
   142      * string instance within the stream.
   143      */
   144 //    private static final ObjectStreamField[] serialPersistentFields =
   145 //        new ObjectStreamField[0];
   146 
   147     /**
   148      * Initializes a newly created {@code String} object so that it represents
   149      * an empty character sequence.  Note that use of this constructor is
   150      * unnecessary since Strings are immutable.
   151      */
   152     public String() {
   153         this.r = "";
   154     }
   155 
   156     /**
   157      * Initializes a newly created {@code String} object so that it represents
   158      * the same sequence of characters as the argument; in other words, the
   159      * newly created string is a copy of the argument string. Unless an
   160      * explicit copy of {@code original} is needed, use of this constructor is
   161      * unnecessary since Strings are immutable.
   162      *
   163      * @param  original
   164      *         A {@code String}
   165      */
   166     public String(String original) {
   167         this.r = original.toString();
   168     }
   169 
   170     /**
   171      * Allocates a new {@code String} so that it represents the sequence of
   172      * characters currently contained in the character array argument. The
   173      * contents of the character array are copied; subsequent modification of
   174      * the character array does not affect the newly created string.
   175      *
   176      * @param  value
   177      *         The initial value of the string
   178      */
   179     @JavaScriptBody(args = { "charArr" }, body=
   180         "for (var i = 0; i < charArr.length; i++) {\n"
   181       + "  if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n"
   182       + "}\n"
   183       + "this._r(charArr.join(''));\n"
   184     )
   185     public String(char value[]) {
   186     }
   187 
   188     /**
   189      * Allocates a new {@code String} that contains characters from a subarray
   190      * of the character array argument. The {@code offset} argument is the
   191      * index of the first character of the subarray and the {@code count}
   192      * argument specifies the length of the subarray. The contents of the
   193      * subarray are copied; subsequent modification of the character array does
   194      * not affect the newly created string.
   195      *
   196      * @param  value
   197      *         Array that is the source of characters
   198      *
   199      * @param  offset
   200      *         The initial offset
   201      *
   202      * @param  count
   203      *         The length
   204      *
   205      * @throws  IndexOutOfBoundsException
   206      *          If the {@code offset} and {@code count} arguments index
   207      *          characters outside the bounds of the {@code value} array
   208      */
   209     public String(char value[], int offset, int count) {
   210         initFromCharArray(value, offset, count);
   211     }
   212     
   213     @JavaScriptBody(args = { "charArr", "off", "cnt" }, body =
   214         "var up = off + cnt;\n" +
   215         "for (var i = off; i < up; i++) {\n" +
   216         "  if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" +
   217         "}\n" +
   218         "this._r(charArr.slice(off, up).join(\"\"));\n"
   219     )
   220     private native void initFromCharArray(char value[], int offset, int count);
   221 
   222     /**
   223      * Allocates a new {@code String} that contains characters from a subarray
   224      * of the <a href="Character.html#unicode">Unicode code point</a> array
   225      * argument.  The {@code offset} argument is the index of the first code
   226      * point of the subarray and the {@code count} argument specifies the
   227      * length of the subarray.  The contents of the subarray are converted to
   228      * {@code char}s; subsequent modification of the {@code int} array does not
   229      * affect the newly created string.
   230      *
   231      * @param  codePoints
   232      *         Array that is the source of Unicode code points
   233      *
   234      * @param  offset
   235      *         The initial offset
   236      *
   237      * @param  count
   238      *         The length
   239      *
   240      * @throws  IllegalArgumentException
   241      *          If any invalid Unicode code point is found in {@code
   242      *          codePoints}
   243      *
   244      * @throws  IndexOutOfBoundsException
   245      *          If the {@code offset} and {@code count} arguments index
   246      *          characters outside the bounds of the {@code codePoints} array
   247      *
   248      * @since  1.5
   249      */
   250     public String(int[] codePoints, int offset, int count) {
   251         if (offset < 0) {
   252             throw new StringIndexOutOfBoundsException(offset);
   253         }
   254         if (count < 0) {
   255             throw new StringIndexOutOfBoundsException(count);
   256         }
   257         // Note: offset or count might be near -1>>>1.
   258         if (offset > codePoints.length - count) {
   259             throw new StringIndexOutOfBoundsException(offset + count);
   260         }
   261 
   262         final int end = offset + count;
   263 
   264         // Pass 1: Compute precise size of char[]
   265         int n = count;
   266         for (int i = offset; i < end; i++) {
   267             int c = codePoints[i];
   268             if (Character.isBmpCodePoint(c))
   269                 continue;
   270             else if (Character.isValidCodePoint(c))
   271                 n++;
   272             else throw new IllegalArgumentException(Integer.toString(c));
   273         }
   274 
   275         // Pass 2: Allocate and fill in char[]
   276         final char[] v = new char[n];
   277 
   278         for (int i = offset, j = 0; i < end; i++, j++) {
   279             int c = codePoints[i];
   280             if (Character.isBmpCodePoint(c))
   281                 v[j] = (char) c;
   282             else
   283                 Character.toSurrogates(c, v, j++);
   284         }
   285 
   286         this.r = new String(v, 0, n);
   287     }
   288 
   289     /**
   290      * Allocates a new {@code String} constructed from a subarray of an array
   291      * of 8-bit integer values.
   292      *
   293      * <p> The {@code offset} argument is the index of the first byte of the
   294      * subarray, and the {@code count} argument specifies the length of the
   295      * subarray.
   296      *
   297      * <p> Each {@code byte} in the subarray is converted to a {@code char} as
   298      * specified in the method above.
   299      *
   300      * @deprecated This method does not properly convert bytes into characters.
   301      * As of JDK&nbsp;1.1, the preferred way to do this is via the
   302      * {@code String} constructors that take a {@link
   303      * java.nio.charset.Charset}, charset name, or that use the platform's
   304      * default charset.
   305      *
   306      * @param  ascii
   307      *         The bytes to be converted to characters
   308      *
   309      * @param  hibyte
   310      *         The top 8 bits of each 16-bit Unicode code unit
   311      *
   312      * @param  offset
   313      *         The initial offset
   314      * @param  count
   315      *         The length
   316      *
   317      * @throws  IndexOutOfBoundsException
   318      *          If the {@code offset} or {@code count} argument is invalid
   319      *
   320      * @see  #String(byte[], int)
   321      * @see  #String(byte[], int, int, java.lang.String)
   322      * @see  #String(byte[], int, int, java.nio.charset.Charset)
   323      * @see  #String(byte[], int, int)
   324      * @see  #String(byte[], java.lang.String)
   325      * @see  #String(byte[], java.nio.charset.Charset)
   326      * @see  #String(byte[])
   327      */
   328     @Deprecated
   329     public String(byte ascii[], int hibyte, int offset, int count) {
   330         checkBounds(ascii, offset, count);
   331         char value[] = new char[count];
   332 
   333         if (hibyte == 0) {
   334             for (int i = count ; i-- > 0 ;) {
   335                 value[i] = (char) (ascii[i + offset] & 0xff);
   336             }
   337         } else {
   338             hibyte <<= 8;
   339             for (int i = count ; i-- > 0 ;) {
   340                 value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
   341             }
   342         }
   343         initFromCharArray(value, offset, count);
   344     }
   345 
   346     /**
   347      * Allocates a new {@code String} containing characters constructed from
   348      * an array of 8-bit integer values. Each character <i>c</i>in the
   349      * resulting string is constructed from the corresponding component
   350      * <i>b</i> in the byte array such that:
   351      *
   352      * <blockquote><pre>
   353      *     <b><i>c</i></b> == (char)(((hibyte &amp; 0xff) &lt;&lt; 8)
   354      *                         | (<b><i>b</i></b> &amp; 0xff))
   355      * </pre></blockquote>
   356      *
   357      * @deprecated  This method does not properly convert bytes into
   358      * characters.  As of JDK&nbsp;1.1, the preferred way to do this is via the
   359      * {@code String} constructors that take a {@link
   360      * java.nio.charset.Charset}, charset name, or that use the platform's
   361      * default charset.
   362      *
   363      * @param  ascii
   364      *         The bytes to be converted to characters
   365      *
   366      * @param  hibyte
   367      *         The top 8 bits of each 16-bit Unicode code unit
   368      *
   369      * @see  #String(byte[], int, int, java.lang.String)
   370      * @see  #String(byte[], int, int, java.nio.charset.Charset)
   371      * @see  #String(byte[], int, int)
   372      * @see  #String(byte[], java.lang.String)
   373      * @see  #String(byte[], java.nio.charset.Charset)
   374      * @see  #String(byte[])
   375      */
   376     @Deprecated
   377     public String(byte ascii[], int hibyte) {
   378         this(ascii, hibyte, 0, ascii.length);
   379     }
   380 
   381     /* Common private utility method used to bounds check the byte array
   382      * and requested offset & length values used by the String(byte[],..)
   383      * constructors.
   384      */
   385     private static void checkBounds(byte[] bytes, int offset, int length) {
   386         if (length < 0)
   387             throw new StringIndexOutOfBoundsException(length);
   388         if (offset < 0)
   389             throw new StringIndexOutOfBoundsException(offset);
   390         if (offset > bytes.length - length)
   391             throw new StringIndexOutOfBoundsException(offset + length);
   392     }
   393 
   394     /**
   395      * Constructs a new {@code String} by decoding the specified subarray of
   396      * bytes using the specified charset.  The length of the new {@code String}
   397      * is a function of the charset, and hence may not be equal to the length
   398      * of the subarray.
   399      *
   400      * <p> The behavior of this constructor when the given bytes are not valid
   401      * in the given charset is unspecified.  The {@link
   402      * java.nio.charset.CharsetDecoder} class should be used when more control
   403      * over the decoding process is required.
   404      *
   405      * @param  bytes
   406      *         The bytes to be decoded into characters
   407      *
   408      * @param  offset
   409      *         The index of the first byte to decode
   410      *
   411      * @param  length
   412      *         The number of bytes to decode
   413 
   414      * @param  charsetName
   415      *         The name of a supported {@linkplain java.nio.charset.Charset
   416      *         charset}
   417      *
   418      * @throws  UnsupportedEncodingException
   419      *          If the named charset is not supported
   420      *
   421      * @throws  IndexOutOfBoundsException
   422      *          If the {@code offset} and {@code length} arguments index
   423      *          characters outside the bounds of the {@code bytes} array
   424      *
   425      * @since  JDK1.1
   426      */
   427     public String(byte bytes[], int offset, int length, String charsetName)
   428         throws UnsupportedEncodingException
   429     {
   430         this(checkUTF8(bytes, charsetName), offset, length);
   431     }
   432 
   433     /**
   434      * Constructs a new {@code String} by decoding the specified subarray of
   435      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
   436      * The length of the new {@code String} is a function of the charset, and
   437      * hence may not be equal to the length of the subarray.
   438      *
   439      * <p> This method always replaces malformed-input and unmappable-character
   440      * sequences with this charset's default replacement string.  The {@link
   441      * java.nio.charset.CharsetDecoder} class should be used when more control
   442      * over the decoding process is required.
   443      *
   444      * @param  bytes
   445      *         The bytes to be decoded into characters
   446      *
   447      * @param  offset
   448      *         The index of the first byte to decode
   449      *
   450      * @param  length
   451      *         The number of bytes to decode
   452      *
   453      * @param  charset
   454      *         The {@linkplain java.nio.charset.Charset charset} to be used to
   455      *         decode the {@code bytes}
   456      *
   457      * @throws  IndexOutOfBoundsException
   458      *          If the {@code offset} and {@code length} arguments index
   459      *          characters outside the bounds of the {@code bytes} array
   460      *
   461      * @since  1.6
   462      */
   463     /* don't want dependnecy on Charset
   464     public String(byte bytes[], int offset, int length, Charset charset) {
   465         if (charset == null)
   466             throw new NullPointerException("charset");
   467         checkBounds(bytes, offset, length);
   468         char[] v = StringCoding.decode(charset, bytes, offset, length);
   469         this.offset = 0;
   470         this.count = v.length;
   471         this.value = v;
   472     }
   473     */
   474 
   475     /**
   476      * Constructs a new {@code String} by decoding the specified array of bytes
   477      * using the specified {@linkplain java.nio.charset.Charset charset}.  The
   478      * length of the new {@code String} is a function of the charset, and hence
   479      * may not be equal to the length of the byte array.
   480      *
   481      * <p> The behavior of this constructor when the given bytes are not valid
   482      * in the given charset is unspecified.  The {@link
   483      * java.nio.charset.CharsetDecoder} class should be used when more control
   484      * over the decoding process is required.
   485      *
   486      * @param  bytes
   487      *         The bytes to be decoded into characters
   488      *
   489      * @param  charsetName
   490      *         The name of a supported {@linkplain java.nio.charset.Charset
   491      *         charset}
   492      *
   493      * @throws  UnsupportedEncodingException
   494      *          If the named charset is not supported
   495      *
   496      * @since  JDK1.1
   497      */
   498     public String(byte bytes[], String charsetName)
   499         throws UnsupportedEncodingException
   500     {
   501         this(bytes, 0, bytes.length, charsetName);
   502     }
   503 
   504     /**
   505      * Constructs a new {@code String} by decoding the specified array of
   506      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
   507      * The length of the new {@code String} is a function of the charset, and
   508      * hence may not be equal to the length of the byte array.
   509      *
   510      * <p> This method always replaces malformed-input and unmappable-character
   511      * sequences with this charset's default replacement string.  The {@link
   512      * java.nio.charset.CharsetDecoder} class should be used when more control
   513      * over the decoding process is required.
   514      *
   515      * @param  bytes
   516      *         The bytes to be decoded into characters
   517      *
   518      * @param  charset
   519      *         The {@linkplain java.nio.charset.Charset charset} to be used to
   520      *         decode the {@code bytes}
   521      *
   522      * @since  1.6
   523      */
   524     /* don't want dep on Charset
   525     public String(byte bytes[], Charset charset) {
   526         this(bytes, 0, bytes.length, charset);
   527     }
   528     */
   529 
   530     /**
   531      * Constructs a new {@code String} by decoding the specified subarray of
   532      * bytes using the platform's default charset.  The length of the new
   533      * {@code String} is a function of the charset, and hence may not be equal
   534      * to the length of the subarray.
   535      *
   536      * <p> The behavior of this constructor when the given bytes are not valid
   537      * in the default charset is unspecified.  The {@link
   538      * java.nio.charset.CharsetDecoder} class should be used when more control
   539      * over the decoding process is required.
   540      *
   541      * @param  bytes
   542      *         The bytes to be decoded into characters
   543      *
   544      * @param  offset
   545      *         The index of the first byte to decode
   546      *
   547      * @param  length
   548      *         The number of bytes to decode
   549      *
   550      * @throws  IndexOutOfBoundsException
   551      *          If the {@code offset} and the {@code length} arguments index
   552      *          characters outside the bounds of the {@code bytes} array
   553      *
   554      * @since  JDK1.1
   555      */
   556     public String(byte bytes[], int offset, int length) {
   557         checkBounds(bytes, offset, length);
   558         char[] v  = new char[length];
   559         int[] at = { offset };
   560         int end = offset + length;
   561         int chlen = 0;
   562         while (at[0] < end) {
   563             int ch = nextChar(bytes, at);
   564             v[chlen++] = (char)ch;
   565         }
   566         initFromCharArray(v, 0, chlen);
   567     }
   568 
   569     /**
   570      * Constructs a new {@code String} by decoding the specified array of bytes
   571      * using the platform's default charset.  The length of the new {@code
   572      * String} is a function of the charset, and hence may not be equal to the
   573      * length of the byte array.
   574      *
   575      * <p> The behavior of this constructor when the given bytes are not valid
   576      * in the default charset is unspecified.  The {@link
   577      * java.nio.charset.CharsetDecoder} class should be used when more control
   578      * over the decoding process is required.
   579      *
   580      * @param  bytes
   581      *         The bytes to be decoded into characters
   582      *
   583      * @since  JDK1.1
   584      */
   585     public String(byte bytes[]) {
   586         this(bytes, 0, bytes.length);
   587     }
   588 
   589     /**
   590      * Allocates a new string that contains the sequence of characters
   591      * currently contained in the string buffer argument. The contents of the
   592      * string buffer are copied; subsequent modification of the string buffer
   593      * does not affect the newly created string.
   594      *
   595      * @param  buffer
   596      *         A {@code StringBuffer}
   597      */
   598     public String(StringBuffer buffer) {
   599         this.r = buffer.toString();
   600     }
   601 
   602     /**
   603      * Allocates a new string that contains the sequence of characters
   604      * currently contained in the string builder argument. The contents of the
   605      * string builder are copied; subsequent modification of the string builder
   606      * does not affect the newly created string.
   607      *
   608      * <p> This constructor is provided to ease migration to {@code
   609      * StringBuilder}. Obtaining a string from a string builder via the {@code
   610      * toString} method is likely to run faster and is generally preferred.
   611      *
   612      * @param   builder
   613      *          A {@code StringBuilder}
   614      *
   615      * @since  1.5
   616      */
   617     public String(StringBuilder builder) {
   618         this.r = builder.toString();
   619     }
   620 
   621     /**
   622      * Returns the length of this string.
   623      * The length is equal to the number of <a href="Character.html#unicode">Unicode
   624      * code units</a> in the string.
   625      *
   626      * @return  the length of the sequence of characters represented by this
   627      *          object.
   628      */
   629     @JavaScriptBody(args = {}, body = "return this.toString().length;")
   630     public int length() {
   631         throw new UnsupportedOperationException();
   632     }
   633 
   634     /**
   635      * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
   636      *
   637      * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
   638      * <tt>false</tt>
   639      *
   640      * @since 1.6
   641      */
   642     @JavaScriptBody(args = {}, body="return this.toString().length === 0;")
   643     public boolean isEmpty() {
   644         return length() == 0;
   645     }
   646 
   647     /**
   648      * Returns the <code>char</code> value at the
   649      * specified index. An index ranges from <code>0</code> to
   650      * <code>length() - 1</code>. The first <code>char</code> value of the sequence
   651      * is at index <code>0</code>, the next at index <code>1</code>,
   652      * and so on, as for array indexing.
   653      *
   654      * <p>If the <code>char</code> value specified by the index is a
   655      * <a href="Character.html#unicode">surrogate</a>, the surrogate
   656      * value is returned.
   657      *
   658      * @param      index   the index of the <code>char</code> value.
   659      * @return     the <code>char</code> value at the specified index of this string.
   660      *             The first <code>char</code> value is at index <code>0</code>.
   661      * @exception  IndexOutOfBoundsException  if the <code>index</code>
   662      *             argument is negative or not less than the length of this
   663      *             string.
   664      */
   665     @JavaScriptBody(args = { "index" }, 
   666         body = "return this.toString().charCodeAt(index);"
   667     )
   668     public char charAt(int index) {
   669         throw new UnsupportedOperationException();
   670     }
   671 
   672     /**
   673      * Returns the character (Unicode code point) at the specified
   674      * index. The index refers to <code>char</code> values
   675      * (Unicode code units) and ranges from <code>0</code> to
   676      * {@link #length()}<code> - 1</code>.
   677      *
   678      * <p> If the <code>char</code> value specified at the given index
   679      * is in the high-surrogate range, the following index is less
   680      * than the length of this <code>String</code>, and the
   681      * <code>char</code> value at the following index is in the
   682      * low-surrogate range, then the supplementary code point
   683      * corresponding to this surrogate pair is returned. Otherwise,
   684      * the <code>char</code> value at the given index is returned.
   685      *
   686      * @param      index the index to the <code>char</code> values
   687      * @return     the code point value of the character at the
   688      *             <code>index</code>
   689      * @exception  IndexOutOfBoundsException  if the <code>index</code>
   690      *             argument is negative or not less than the length of this
   691      *             string.
   692      * @since      1.5
   693      */
   694     public int codePointAt(int index) {
   695         if ((index < 0) || (index >= length())) {
   696             throw new StringIndexOutOfBoundsException(index);
   697         }
   698         return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length());
   699     }
   700 
   701     /**
   702      * Returns the character (Unicode code point) before the specified
   703      * index. The index refers to <code>char</code> values
   704      * (Unicode code units) and ranges from <code>1</code> to {@link
   705      * CharSequence#length() length}.
   706      *
   707      * <p> If the <code>char</code> value at <code>(index - 1)</code>
   708      * is in the low-surrogate range, <code>(index - 2)</code> is not
   709      * negative, and the <code>char</code> value at <code>(index -
   710      * 2)</code> is in the high-surrogate range, then the
   711      * supplementary code point value of the surrogate pair is
   712      * returned. If the <code>char</code> value at <code>index -
   713      * 1</code> is an unpaired low-surrogate or a high-surrogate, the
   714      * surrogate value is returned.
   715      *
   716      * @param     index the index following the code point that should be returned
   717      * @return    the Unicode code point value before the given index.
   718      * @exception IndexOutOfBoundsException if the <code>index</code>
   719      *            argument is less than 1 or greater than the length
   720      *            of this string.
   721      * @since     1.5
   722      */
   723     public int codePointBefore(int index) {
   724         int i = index - 1;
   725         if ((i < 0) || (i >= length())) {
   726             throw new StringIndexOutOfBoundsException(index);
   727         }
   728         return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset());
   729     }
   730 
   731     /**
   732      * Returns the number of Unicode code points in the specified text
   733      * range of this <code>String</code>. The text range begins at the
   734      * specified <code>beginIndex</code> and extends to the
   735      * <code>char</code> at index <code>endIndex - 1</code>. Thus the
   736      * length (in <code>char</code>s) of the text range is
   737      * <code>endIndex-beginIndex</code>. Unpaired surrogates within
   738      * the text range count as one code point each.
   739      *
   740      * @param beginIndex the index to the first <code>char</code> of
   741      * the text range.
   742      * @param endIndex the index after the last <code>char</code> of
   743      * the text range.
   744      * @return the number of Unicode code points in the specified text
   745      * range
   746      * @exception IndexOutOfBoundsException if the
   747      * <code>beginIndex</code> is negative, or <code>endIndex</code>
   748      * is larger than the length of this <code>String</code>, or
   749      * <code>beginIndex</code> is larger than <code>endIndex</code>.
   750      * @since  1.5
   751      */
   752     public int codePointCount(int beginIndex, int endIndex) {
   753         if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) {
   754             throw new IndexOutOfBoundsException();
   755         }
   756         return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex);
   757     }
   758 
   759     /**
   760      * Returns the index within this <code>String</code> that is
   761      * offset from the given <code>index</code> by
   762      * <code>codePointOffset</code> code points. Unpaired surrogates
   763      * within the text range given by <code>index</code> and
   764      * <code>codePointOffset</code> count as one code point each.
   765      *
   766      * @param index the index to be offset
   767      * @param codePointOffset the offset in code points
   768      * @return the index within this <code>String</code>
   769      * @exception IndexOutOfBoundsException if <code>index</code>
   770      *   is negative or larger then the length of this
   771      *   <code>String</code>, or if <code>codePointOffset</code> is positive
   772      *   and the substring starting with <code>index</code> has fewer
   773      *   than <code>codePointOffset</code> code points,
   774      *   or if <code>codePointOffset</code> is negative and the substring
   775      *   before <code>index</code> has fewer than the absolute value
   776      *   of <code>codePointOffset</code> code points.
   777      * @since 1.5
   778      */
   779     public int offsetByCodePoints(int index, int codePointOffset) {
   780         if (index < 0 || index > length()) {
   781             throw new IndexOutOfBoundsException();
   782         }
   783         return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(),
   784                                                 offset()+index, codePointOffset) - offset();
   785     }
   786 
   787     /**
   788      * Copy characters from this string into dst starting at dstBegin.
   789      * This method doesn't perform any range checking.
   790      */
   791     @JavaScriptBody(args = { "arr", "to" }, body = 
   792         "var s = this.toString();\n" +
   793         "for (var i = 0; i < s.length; i++) {\n" +
   794         "   arr[to++] = s[i];\n" +
   795         "}"
   796     )
   797     void getChars(char dst[], int dstBegin) {
   798         System.arraycopy(toCharArray(), offset(), dst, dstBegin, length());
   799     }
   800 
   801     /**
   802      * Copies characters from this string into the destination character
   803      * array.
   804      * <p>
   805      * The first character to be copied is at index <code>srcBegin</code>;
   806      * the last character to be copied is at index <code>srcEnd-1</code>
   807      * (thus the total number of characters to be copied is
   808      * <code>srcEnd-srcBegin</code>). The characters are copied into the
   809      * subarray of <code>dst</code> starting at index <code>dstBegin</code>
   810      * and ending at index:
   811      * <p><blockquote><pre>
   812      *     dstbegin + (srcEnd-srcBegin) - 1
   813      * </pre></blockquote>
   814      *
   815      * @param      srcBegin   index of the first character in the string
   816      *                        to copy.
   817      * @param      srcEnd     index after the last character in the string
   818      *                        to copy.
   819      * @param      dst        the destination array.
   820      * @param      dstBegin   the start offset in the destination array.
   821      * @exception IndexOutOfBoundsException If any of the following
   822      *            is true:
   823      *            <ul><li><code>srcBegin</code> is negative.
   824      *            <li><code>srcBegin</code> is greater than <code>srcEnd</code>
   825      *            <li><code>srcEnd</code> is greater than the length of this
   826      *                string
   827      *            <li><code>dstBegin</code> is negative
   828      *            <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
   829      *                <code>dst.length</code></ul>
   830      */
   831     @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body=
   832         "var s = this.toString();\n" +
   833         "while (beg < end) {\n" +
   834         "  arr[dst++] = s.charCodeAt(beg++);\n" +
   835         "}\n"
   836     )
   837     public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
   838         if (srcBegin < 0) {
   839             throw new StringIndexOutOfBoundsException(srcBegin);
   840         }
   841         if (srcEnd > length()) {
   842             throw new StringIndexOutOfBoundsException(srcEnd);
   843         }
   844         if (srcBegin > srcEnd) {
   845             throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
   846         }
   847         System.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin,
   848              srcEnd - srcBegin);
   849     }
   850 
   851     /**
   852      * Copies characters from this string into the destination byte array. Each
   853      * byte receives the 8 low-order bits of the corresponding character. The
   854      * eight high-order bits of each character are not copied and do not
   855      * participate in the transfer in any way.
   856      *
   857      * <p> The first character to be copied is at index {@code srcBegin}; the
   858      * last character to be copied is at index {@code srcEnd-1}.  The total
   859      * number of characters to be copied is {@code srcEnd-srcBegin}. The
   860      * characters, converted to bytes, are copied into the subarray of {@code
   861      * dst} starting at index {@code dstBegin} and ending at index:
   862      *
   863      * <blockquote><pre>
   864      *     dstbegin + (srcEnd-srcBegin) - 1
   865      * </pre></blockquote>
   866      *
   867      * @deprecated  This method does not properly convert characters into
   868      * bytes.  As of JDK&nbsp;1.1, the preferred way to do this is via the
   869      * {@link #getBytes()} method, which uses the platform's default charset.
   870      *
   871      * @param  srcBegin
   872      *         Index of the first character in the string to copy
   873      *
   874      * @param  srcEnd
   875      *         Index after the last character in the string to copy
   876      *
   877      * @param  dst
   878      *         The destination array
   879      *
   880      * @param  dstBegin
   881      *         The start offset in the destination array
   882      *
   883      * @throws  IndexOutOfBoundsException
   884      *          If any of the following is true:
   885      *          <ul>
   886      *            <li> {@code srcBegin} is negative
   887      *            <li> {@code srcBegin} is greater than {@code srcEnd}
   888      *            <li> {@code srcEnd} is greater than the length of this String
   889      *            <li> {@code dstBegin} is negative
   890      *            <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
   891      *                 dst.length}
   892      *          </ul>
   893      */
   894     @Deprecated
   895     public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
   896         if (srcBegin < 0) {
   897             throw new StringIndexOutOfBoundsException(srcBegin);
   898         }
   899         if (srcEnd > length()) {
   900             throw new StringIndexOutOfBoundsException(srcEnd);
   901         }
   902         if (srcBegin > srcEnd) {
   903             throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
   904         }
   905         int j = dstBegin;
   906         int n = offset() + srcEnd;
   907         int i = offset() + srcBegin;
   908         char[] val = toCharArray();   /* avoid getfield opcode */
   909 
   910         while (i < n) {
   911             dst[j++] = (byte)val[i++];
   912         }
   913     }
   914 
   915     /**
   916      * Encodes this {@code String} into a sequence of bytes using the named
   917      * charset, storing the result into a new byte array.
   918      *
   919      * <p> The behavior of this method when this string cannot be encoded in
   920      * the given charset is unspecified.  The {@link
   921      * java.nio.charset.CharsetEncoder} class should be used when more control
   922      * over the encoding process is required.
   923      *
   924      * @param  charsetName
   925      *         The name of a supported {@linkplain java.nio.charset.Charset
   926      *         charset}
   927      *
   928      * @return  The resultant byte array
   929      *
   930      * @throws  UnsupportedEncodingException
   931      *          If the named charset is not supported
   932      *
   933      * @since  JDK1.1
   934      */
   935     public byte[] getBytes(String charsetName)
   936         throws UnsupportedEncodingException
   937     {
   938         checkUTF8(null, charsetName);
   939         return getBytes();
   940     }
   941 
   942     /**
   943      * Encodes this {@code String} into a sequence of bytes using the given
   944      * {@linkplain java.nio.charset.Charset charset}, storing the result into a
   945      * new byte array.
   946      *
   947      * <p> This method always replaces malformed-input and unmappable-character
   948      * sequences with this charset's default replacement byte array.  The
   949      * {@link java.nio.charset.CharsetEncoder} class should be used when more
   950      * control over the encoding process is required.
   951      *
   952      * @param  charset
   953      *         The {@linkplain java.nio.charset.Charset} to be used to encode
   954      *         the {@code String}
   955      *
   956      * @return  The resultant byte array
   957      *
   958      * @since  1.6
   959      */
   960     /* don't want dep on Charset
   961     public byte[] getBytes(Charset charset) {
   962         if (charset == null) throw new NullPointerException();
   963         return StringCoding.encode(charset, value, offset, count);
   964     }
   965     */
   966 
   967     /**
   968      * Encodes this {@code String} into a sequence of bytes using the
   969      * platform's default charset, storing the result into a new byte array.
   970      *
   971      * <p> The behavior of this method when this string cannot be encoded in
   972      * the default charset is unspecified.  The {@link
   973      * java.nio.charset.CharsetEncoder} class should be used when more control
   974      * over the encoding process is required.
   975      *
   976      * @return  The resultant byte array
   977      *
   978      * @since      JDK1.1
   979      */
   980     public byte[] getBytes() {
   981         int len = length();
   982         byte[] arr = new byte[len];
   983         for (int i = 0, j = 0; j < len; j++) {
   984             final int v = charAt(j);
   985             if (v < 128) {
   986                 arr[i++] = (byte) v;
   987                 continue;
   988             }
   989             if (v < 0x0800) {
   990                 arr = System.expandArray(arr, arr.length + 1);
   991                 arr[i++] = (byte) (0xC0 | (v >> 6));
   992                 arr[i++] = (byte) (0x80 | (0x3F & v));
   993                 continue;
   994             }
   995             arr = System.expandArray(arr, arr.length + 2);
   996             arr[i++] = (byte) (0xE0 | (v >> 12));
   997             arr[i++] = (byte) (0x80 | ((v >> 6) & 0x7F));
   998             arr[i++] = (byte) (0x80 | (0x3F & v));
   999         }
  1000         return arr;
  1001     }
  1002 
  1003     /**
  1004      * Compares this string to the specified object.  The result is {@code
  1005      * true} if and only if the argument is not {@code null} and is a {@code
  1006      * String} object that represents the same sequence of characters as this
  1007      * object.
  1008      *
  1009      * @param  anObject
  1010      *         The object to compare this {@code String} against
  1011      *
  1012      * @return  {@code true} if the given object represents a {@code String}
  1013      *          equivalent to this string, {@code false} otherwise
  1014      *
  1015      * @see  #compareTo(String)
  1016      * @see  #equalsIgnoreCase(String)
  1017      */
  1018     @JavaScriptBody(args = { "obj" }, body = 
  1019         "return obj != null && obj['$instOf_java_lang_String'] && "
  1020         + "this.toString() === obj.toString();"
  1021     )
  1022     public boolean equals(Object anObject) {
  1023         if (this == anObject) {
  1024             return true;
  1025         }
  1026         if (anObject instanceof String) {
  1027             String anotherString = (String)anObject;
  1028             int n = length();
  1029             if (n == anotherString.length()) {
  1030                 char v1[] = toCharArray();
  1031                 char v2[] = anotherString.toCharArray();
  1032                 int i = offset();
  1033                 int j = anotherString.offset();
  1034                 while (n-- != 0) {
  1035                     if (v1[i++] != v2[j++])
  1036                         return false;
  1037                 }
  1038                 return true;
  1039             }
  1040         }
  1041         return false;
  1042     }
  1043 
  1044     /**
  1045      * Compares this string to the specified {@code StringBuffer}.  The result
  1046      * is {@code true} if and only if this {@code String} represents the same
  1047      * sequence of characters as the specified {@code StringBuffer}.
  1048      *
  1049      * @param  sb
  1050      *         The {@code StringBuffer} to compare this {@code String} against
  1051      *
  1052      * @return  {@code true} if this {@code String} represents the same
  1053      *          sequence of characters as the specified {@code StringBuffer},
  1054      *          {@code false} otherwise
  1055      *
  1056      * @since  1.4
  1057      */
  1058     public boolean contentEquals(StringBuffer sb) {
  1059         synchronized(sb) {
  1060             return contentEquals((CharSequence)sb);
  1061         }
  1062     }
  1063 
  1064     /**
  1065      * Compares this string to the specified {@code CharSequence}.  The result
  1066      * is {@code true} if and only if this {@code String} represents the same
  1067      * sequence of char values as the specified sequence.
  1068      *
  1069      * @param  cs
  1070      *         The sequence to compare this {@code String} against
  1071      *
  1072      * @return  {@code true} if this {@code String} represents the same
  1073      *          sequence of char values as the specified sequence, {@code
  1074      *          false} otherwise
  1075      *
  1076      * @since  1.5
  1077      */
  1078     public boolean contentEquals(CharSequence cs) {
  1079         if (length() != cs.length())
  1080             return false;
  1081         // Argument is a StringBuffer, StringBuilder
  1082         if (cs instanceof AbstractStringBuilder) {
  1083             char v1[] = toCharArray();
  1084             char v2[] = ((AbstractStringBuilder)cs).getValue();
  1085             int i = offset();
  1086             int j = 0;
  1087             int n = length();
  1088             while (n-- != 0) {
  1089                 if (v1[i++] != v2[j++])
  1090                     return false;
  1091             }
  1092             return true;
  1093         }
  1094         // Argument is a String
  1095         if (cs.equals(this))
  1096             return true;
  1097         // Argument is a generic CharSequence
  1098         char v1[] = toCharArray();
  1099         int i = offset();
  1100         int j = 0;
  1101         int n = length();
  1102         while (n-- != 0) {
  1103             if (v1[i++] != cs.charAt(j++))
  1104                 return false;
  1105         }
  1106         return true;
  1107     }
  1108 
  1109     /**
  1110      * Compares this {@code String} to another {@code String}, ignoring case
  1111      * considerations.  Two strings are considered equal ignoring case if they
  1112      * are of the same length and corresponding characters in the two strings
  1113      * are equal ignoring case.
  1114      *
  1115      * <p> Two characters {@code c1} and {@code c2} are considered the same
  1116      * ignoring case if at least one of the following is true:
  1117      * <ul>
  1118      *   <li> The two characters are the same (as compared by the
  1119      *        {@code ==} operator)
  1120      *   <li> Applying the method {@link
  1121      *        java.lang.Character#toUpperCase(char)} to each character
  1122      *        produces the same result
  1123      *   <li> Applying the method {@link
  1124      *        java.lang.Character#toLowerCase(char)} to each character
  1125      *        produces the same result
  1126      * </ul>
  1127      *
  1128      * @param  anotherString
  1129      *         The {@code String} to compare this {@code String} against
  1130      *
  1131      * @return  {@code true} if the argument is not {@code null} and it
  1132      *          represents an equivalent {@code String} ignoring case; {@code
  1133      *          false} otherwise
  1134      *
  1135      * @see  #equals(Object)
  1136      */
  1137     public boolean equalsIgnoreCase(String anotherString) {
  1138         return (this == anotherString) ? true :
  1139                (anotherString != null) && (anotherString.length() == length()) &&
  1140                regionMatches(true, 0, anotherString, 0, length());
  1141     }
  1142 
  1143     /**
  1144      * Compares two strings lexicographically.
  1145      * The comparison is based on the Unicode value of each character in
  1146      * the strings. The character sequence represented by this
  1147      * <code>String</code> object is compared lexicographically to the
  1148      * character sequence represented by the argument string. The result is
  1149      * a negative integer if this <code>String</code> object
  1150      * lexicographically precedes the argument string. The result is a
  1151      * positive integer if this <code>String</code> object lexicographically
  1152      * follows the argument string. The result is zero if the strings
  1153      * are equal; <code>compareTo</code> returns <code>0</code> exactly when
  1154      * the {@link #equals(Object)} method would return <code>true</code>.
  1155      * <p>
  1156      * This is the definition of lexicographic ordering. If two strings are
  1157      * different, then either they have different characters at some index
  1158      * that is a valid index for both strings, or their lengths are different,
  1159      * or both. If they have different characters at one or more index
  1160      * positions, let <i>k</i> be the smallest such index; then the string
  1161      * whose character at position <i>k</i> has the smaller value, as
  1162      * determined by using the &lt; operator, lexicographically precedes the
  1163      * other string. In this case, <code>compareTo</code> returns the
  1164      * difference of the two character values at position <code>k</code> in
  1165      * the two string -- that is, the value:
  1166      * <blockquote><pre>
  1167      * this.charAt(k)-anotherString.charAt(k)
  1168      * </pre></blockquote>
  1169      * If there is no index position at which they differ, then the shorter
  1170      * string lexicographically precedes the longer string. In this case,
  1171      * <code>compareTo</code> returns the difference of the lengths of the
  1172      * strings -- that is, the value:
  1173      * <blockquote><pre>
  1174      * this.length()-anotherString.length()
  1175      * </pre></blockquote>
  1176      *
  1177      * @param   anotherString   the <code>String</code> to be compared.
  1178      * @return  the value <code>0</code> if the argument string is equal to
  1179      *          this string; a value less than <code>0</code> if this string
  1180      *          is lexicographically less than the string argument; and a
  1181      *          value greater than <code>0</code> if this string is
  1182      *          lexicographically greater than the string argument.
  1183      */
  1184     public int compareTo(String anotherString) {
  1185         int len1 = length();
  1186         int len2 = anotherString.length();
  1187         int n = Math.min(len1, len2);
  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 = this.charAt(k);
  1196                 char c2 = anotherString.charAt(k);
  1197                 if (c1 != c2) {
  1198                     return c1 - c2;
  1199                 }
  1200                 k++;
  1201             }
  1202         } else {
  1203             while (n-- != 0) {
  1204                 char c1 = this.charAt(i++);
  1205                 char c2 = anotherString.charAt(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     public boolean matches(String regex) {
  2102         try {
  2103             return matchesViaJS(regex);
  2104         } catch (Throwable t) {
  2105             // fallback to classical behavior
  2106             try {
  2107                 Method m = Class.forName("java.util.regex.Pattern").getMethod("matches", String.class, CharSequence.class);
  2108                 return (Boolean)m.invoke(null, regex, this);
  2109             } catch (InvocationTargetException ex) {
  2110                 if (ex.getTargetException() instanceof RuntimeException) {
  2111                     throw (RuntimeException)ex.getTargetException();
  2112                 }
  2113             } catch (Throwable another) {
  2114                 // will report the old one
  2115             }
  2116             throw new RuntimeException(t);
  2117         }
  2118     }
  2119     @JavaScriptBody(args = { "regex" }, body = 
  2120           "var self = this.toString();\n"
  2121         + "var re = new RegExp(regex.toString());\n"
  2122         + "var r = re.exec(self);\n"
  2123         + "return r != null && r.length > 0 && self.length == r[0].length;"
  2124     )
  2125     private boolean matchesViaJS(String regex) {
  2126         throw new UnsupportedOperationException();
  2127     }
  2128 
  2129     /**
  2130      * Returns true if and only if this string contains the specified
  2131      * sequence of char values.
  2132      *
  2133      * @param s the sequence to search for
  2134      * @return true if this string contains <code>s</code>, false otherwise
  2135      * @throws NullPointerException if <code>s</code> is <code>null</code>
  2136      * @since 1.5
  2137      */
  2138     public boolean contains(CharSequence s) {
  2139         return indexOf(s.toString()) > -1;
  2140     }
  2141 
  2142     /**
  2143      * Replaces the first substring of this string that matches the given <a
  2144      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
  2145      * given replacement.
  2146      *
  2147      * <p> An invocation of this method of the form
  2148      * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
  2149      * yields exactly the same result as the expression
  2150      *
  2151      * <blockquote><tt>
  2152      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
  2153      * compile}(</tt><i>regex</i><tt>).{@link
  2154      * java.util.regex.Pattern#matcher(java.lang.CharSequence)
  2155      * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
  2156      * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
  2157      *
  2158      *<p>
  2159      * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
  2160      * replacement string may cause the results to be different than if it were
  2161      * being treated as a literal replacement string; see
  2162      * {@link java.util.regex.Matcher#replaceFirst}.
  2163      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
  2164      * meaning of these characters, if desired.
  2165      *
  2166      * @param   regex
  2167      *          the regular expression to which this string is to be matched
  2168      * @param   replacement
  2169      *          the string to be substituted for the first match
  2170      *
  2171      * @return  The resulting <tt>String</tt>
  2172      *
  2173      * @throws  PatternSyntaxException
  2174      *          if the regular expression's syntax is invalid
  2175      *
  2176      * @see java.util.regex.Pattern
  2177      *
  2178      * @since 1.4
  2179      * @spec JSR-51
  2180      */
  2181     @JavaScriptBody(args = { "regex", "newText" }, body = 
  2182           "var self = this.toString();\n"
  2183         + "var re = new RegExp(regex.toString());\n"
  2184         + "var r = re.exec(self);\n"
  2185         + "if (r === null || r.length === 0) return this;\n"
  2186         + "var from = self.indexOf(r[0]);\n"
  2187         + "return this.substring(0, from) + newText + this.substring(from + r[0].length);\n"
  2188     )
  2189     public String replaceFirst(String regex, String replacement) {
  2190         throw new UnsupportedOperationException();
  2191     }
  2192 
  2193     /**
  2194      * Replaces each substring of this string that matches the given <a
  2195      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
  2196      * given replacement.
  2197      *
  2198      * <p> An invocation of this method of the form
  2199      * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
  2200      * yields exactly the same result as the expression
  2201      *
  2202      * <blockquote><tt>
  2203      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
  2204      * compile}(</tt><i>regex</i><tt>).{@link
  2205      * java.util.regex.Pattern#matcher(java.lang.CharSequence)
  2206      * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
  2207      * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
  2208      *
  2209      *<p>
  2210      * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
  2211      * replacement string may cause the results to be different than if it were
  2212      * being treated as a literal replacement string; see
  2213      * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
  2214      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
  2215      * meaning of these characters, if desired.
  2216      *
  2217      * @param   regex
  2218      *          the regular expression to which this string is to be matched
  2219      * @param   replacement
  2220      *          the string to be substituted for each match
  2221      *
  2222      * @return  The resulting <tt>String</tt>
  2223      *
  2224      * @throws  PatternSyntaxException
  2225      *          if the regular expression's syntax is invalid
  2226      *
  2227      * @see java.util.regex.Pattern
  2228      *
  2229      * @since 1.4
  2230      * @spec JSR-51
  2231      */
  2232     public String replaceAll(String regex, String replacement) {
  2233         String p = this;
  2234         for (;;) {
  2235             String n = p.replaceFirst(regex, replacement);
  2236             if (n == p) {
  2237                 return n;
  2238             }
  2239             p = n;
  2240         }
  2241     }
  2242 
  2243     /**
  2244      * Replaces each substring of this string that matches the literal target
  2245      * sequence with the specified literal replacement sequence. The
  2246      * replacement proceeds from the beginning of the string to the end, for
  2247      * example, replacing "aa" with "b" in the string "aaa" will result in
  2248      * "ba" rather than "ab".
  2249      *
  2250      * @param  target The sequence of char values to be replaced
  2251      * @param  replacement The replacement sequence of char values
  2252      * @return  The resulting string
  2253      * @throws NullPointerException if <code>target</code> or
  2254      *         <code>replacement</code> is <code>null</code>.
  2255      * @since 1.5
  2256      */
  2257     @JavaScriptBody(args = { "target", "replacement" }, body = 
  2258           "var s = this.toString();\n"
  2259         + "target = target.toString();\n"
  2260         + "replacement = replacement.toString();\n"
  2261         + "var pos = 0;\n"
  2262         + "for (;;) {\n"
  2263         + "  var indx = s.indexOf(target, pos);\n"
  2264         + "  if (indx === -1) {\n"
  2265         + "    return s;\n"
  2266         + "  }\n"
  2267         + "  pos = indx + replacement.length;\n"
  2268         + "  s = s.substring(0, indx) + replacement + s.substring(indx + target.length);\n"
  2269         + "}"
  2270     )
  2271     public native String replace(CharSequence target, CharSequence replacement);
  2272 
  2273     /**
  2274      * Splits this string around matches of the given
  2275      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
  2276      *
  2277      * <p> The array returned by this method contains each substring of this
  2278      * string that is terminated by another substring that matches the given
  2279      * expression or is terminated by the end of the string.  The substrings in
  2280      * the array are in the order in which they occur in this string.  If the
  2281      * expression does not match any part of the input then the resulting array
  2282      * has just one element, namely this string.
  2283      *
  2284      * <p> The <tt>limit</tt> parameter controls the number of times the
  2285      * pattern is applied and therefore affects the length of the resulting
  2286      * array.  If the limit <i>n</i> is greater than zero then the pattern
  2287      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
  2288      * length will be no greater than <i>n</i>, and the array's last entry
  2289      * will contain all input beyond the last matched delimiter.  If <i>n</i>
  2290      * is non-positive then the pattern will be applied as many times as
  2291      * possible and the array can have any length.  If <i>n</i> is zero then
  2292      * the pattern will be applied as many times as possible, the array can
  2293      * have any length, and trailing empty strings will be discarded.
  2294      *
  2295      * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
  2296      * following results with these parameters:
  2297      *
  2298      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
  2299      * <tr>
  2300      *     <th>Regex</th>
  2301      *     <th>Limit</th>
  2302      *     <th>Result</th>
  2303      * </tr>
  2304      * <tr><td align=center>:</td>
  2305      *     <td align=center>2</td>
  2306      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
  2307      * <tr><td align=center>:</td>
  2308      *     <td align=center>5</td>
  2309      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  2310      * <tr><td align=center>:</td>
  2311      *     <td align=center>-2</td>
  2312      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  2313      * <tr><td align=center>o</td>
  2314      *     <td align=center>5</td>
  2315      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  2316      * <tr><td align=center>o</td>
  2317      *     <td align=center>-2</td>
  2318      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  2319      * <tr><td align=center>o</td>
  2320      *     <td align=center>0</td>
  2321      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  2322      * </table></blockquote>
  2323      *
  2324      * <p> An invocation of this method of the form
  2325      * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
  2326      * yields the same result as the expression
  2327      *
  2328      * <blockquote>
  2329      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
  2330      * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
  2331      * java.util.regex.Pattern#split(java.lang.CharSequence,int)
  2332      * split}<tt>(</tt><i>str</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
  2333      * </blockquote>
  2334      *
  2335      *
  2336      * @param  regex
  2337      *         the delimiting regular expression
  2338      *
  2339      * @param  limit
  2340      *         the result threshold, as described above
  2341      *
  2342      * @return  the array of strings computed by splitting this string
  2343      *          around matches of the given regular expression
  2344      *
  2345      * @throws  PatternSyntaxException
  2346      *          if the regular expression's syntax is invalid
  2347      *
  2348      * @see java.util.regex.Pattern
  2349      *
  2350      * @since 1.4
  2351      * @spec JSR-51
  2352      */
  2353     public String[] split(String regex, int limit) {
  2354         if (limit <= 0) {
  2355             Object[] arr = splitImpl(this, regex, Integer.MAX_VALUE);
  2356             int to = arr.length;
  2357             if (limit == 0 && to > 0) {
  2358                 while (to > 0 && ((String)arr[--to]).isEmpty()) {
  2359                 }
  2360                 to++;
  2361             }
  2362             String[] ret = new String[to];
  2363             System.arraycopy(arr, 0, ret, 0, to);
  2364             return ret;
  2365         } else {
  2366             Object[] arr = splitImpl(this, regex, limit);
  2367             String[] ret = new String[arr.length];
  2368             int pos = 0;
  2369             for (int i = 0; i < arr.length; i++) {
  2370                 final String s = (String)arr[i];
  2371                 ret[i] = s;
  2372                 pos = indexOf(s, pos) + s.length();
  2373             }
  2374             ret[arr.length - 1] += substring(pos);
  2375             return ret;
  2376         }
  2377     }
  2378     
  2379     @JavaScriptBody(args = { "str", "regex", "limit"}, body = 
  2380         "return str.split(new RegExp(regex), limit);"
  2381     )
  2382     private static native Object[] splitImpl(String str, String regex, int limit);
  2383 
  2384     /**
  2385      * Splits this string around matches of the given <a
  2386      * href="../util/regex/Pattern.html#sum">regular expression</a>.
  2387      *
  2388      * <p> This method works as if by invoking the two-argument {@link
  2389      * #split(String, int) split} method with the given expression and a limit
  2390      * argument of zero.  Trailing empty strings are therefore not included in
  2391      * the resulting array.
  2392      *
  2393      * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
  2394      * results with these expressions:
  2395      *
  2396      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
  2397      * <tr>
  2398      *  <th>Regex</th>
  2399      *  <th>Result</th>
  2400      * </tr>
  2401      * <tr><td align=center>:</td>
  2402      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  2403      * <tr><td align=center>o</td>
  2404      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  2405      * </table></blockquote>
  2406      *
  2407      *
  2408      * @param  regex
  2409      *         the delimiting regular expression
  2410      *
  2411      * @return  the array of strings computed by splitting this string
  2412      *          around matches of the given regular expression
  2413      *
  2414      * @throws  PatternSyntaxException
  2415      *          if the regular expression's syntax is invalid
  2416      *
  2417      * @see java.util.regex.Pattern
  2418      *
  2419      * @since 1.4
  2420      * @spec JSR-51
  2421      */
  2422     public String[] split(String regex) {
  2423         return split(regex, 0);
  2424     }
  2425 
  2426     /**
  2427      * Converts all of the characters in this <code>String</code> to lower
  2428      * case using the rules of the given <code>Locale</code>.  Case mapping is based
  2429      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
  2430      * class. Since case mappings are not always 1:1 char mappings, the resulting
  2431      * <code>String</code> may be a different length than the original <code>String</code>.
  2432      * <p>
  2433      * Examples of lowercase  mappings are in the following table:
  2434      * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
  2435      * <tr>
  2436      *   <th>Language Code of Locale</th>
  2437      *   <th>Upper Case</th>
  2438      *   <th>Lower Case</th>
  2439      *   <th>Description</th>
  2440      * </tr>
  2441      * <tr>
  2442      *   <td>tr (Turkish)</td>
  2443      *   <td>&#92;u0130</td>
  2444      *   <td>&#92;u0069</td>
  2445      *   <td>capital letter I with dot above -&gt; small letter i</td>
  2446      * </tr>
  2447      * <tr>
  2448      *   <td>tr (Turkish)</td>
  2449      *   <td>&#92;u0049</td>
  2450      *   <td>&#92;u0131</td>
  2451      *   <td>capital letter I -&gt; small letter dotless i </td>
  2452      * </tr>
  2453      * <tr>
  2454      *   <td>(all)</td>
  2455      *   <td>French Fries</td>
  2456      *   <td>french fries</td>
  2457      *   <td>lowercased all chars in String</td>
  2458      * </tr>
  2459      * <tr>
  2460      *   <td>(all)</td>
  2461      *   <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
  2462      *       <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
  2463      *       <img src="doc-files/capsigma.gif" alt="capsigma"></td>
  2464      *   <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
  2465      *       <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
  2466      *       <img src="doc-files/sigma1.gif" alt="sigma"></td>
  2467      *   <td>lowercased all chars in String</td>
  2468      * </tr>
  2469      * </table>
  2470      *
  2471      * @param locale use the case transformation rules for this locale
  2472      * @return the <code>String</code>, converted to lowercase.
  2473      * @see     java.lang.String#toLowerCase()
  2474      * @see     java.lang.String#toUpperCase()
  2475      * @see     java.lang.String#toUpperCase(Locale)
  2476      * @since   1.1
  2477      */
  2478     public String toLowerCase(java.util.Locale locale) {
  2479         return toLowerCase();
  2480     }
  2481 //        if (locale == null) {
  2482 //            throw new NullPointerException();
  2483 //        }
  2484 //
  2485 //        int     firstUpper;
  2486 //
  2487 //        /* Now check if there are any characters that need to be changed. */
  2488 //        scan: {
  2489 //            for (firstUpper = 0 ; firstUpper < count; ) {
  2490 //                char c = value[offset+firstUpper];
  2491 //                if ((c >= Character.MIN_HIGH_SURROGATE) &&
  2492 //                    (c <= Character.MAX_HIGH_SURROGATE)) {
  2493 //                    int supplChar = codePointAt(firstUpper);
  2494 //                    if (supplChar != Character.toLowerCase(supplChar)) {
  2495 //                        break scan;
  2496 //                    }
  2497 //                    firstUpper += Character.charCount(supplChar);
  2498 //                } else {
  2499 //                    if (c != Character.toLowerCase(c)) {
  2500 //                        break scan;
  2501 //                    }
  2502 //                    firstUpper++;
  2503 //                }
  2504 //            }
  2505 //            return this;
  2506 //        }
  2507 //
  2508 //        char[]  result = new char[count];
  2509 //        int     resultOffset = 0;  /* result may grow, so i+resultOffset
  2510 //                                    * is the write location in result */
  2511 //
  2512 //        /* Just copy the first few lowerCase characters. */
  2513 //        System.arraycopy(value, offset, result, 0, firstUpper);
  2514 //
  2515 //        String lang = locale.getLanguage();
  2516 //        boolean localeDependent =
  2517 //            (lang == "tr" || lang == "az" || lang == "lt");
  2518 //        char[] lowerCharArray;
  2519 //        int lowerChar;
  2520 //        int srcChar;
  2521 //        int srcCount;
  2522 //        for (int i = firstUpper; i < count; i += srcCount) {
  2523 //            srcChar = (int)value[offset+i];
  2524 //            if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
  2525 //                (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
  2526 //                srcChar = codePointAt(i);
  2527 //                srcCount = Character.charCount(srcChar);
  2528 //            } else {
  2529 //                srcCount = 1;
  2530 //            }
  2531 //            if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
  2532 //                lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
  2533 //            } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
  2534 //                lowerChar = Character.ERROR;
  2535 //            } else {
  2536 //                lowerChar = Character.toLowerCase(srcChar);
  2537 //            }
  2538 //            if ((lowerChar == Character.ERROR) ||
  2539 //                (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
  2540 //                if (lowerChar == Character.ERROR) {
  2541 //                     if (!localeDependent && srcChar == '\u0130') {
  2542 //                         lowerCharArray =
  2543 //                             ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
  2544 //                     } else {
  2545 //                        lowerCharArray =
  2546 //                            ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
  2547 //                     }
  2548 //                } else if (srcCount == 2) {
  2549 //                    resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
  2550 //                    continue;
  2551 //                } else {
  2552 //                    lowerCharArray = Character.toChars(lowerChar);
  2553 //                }
  2554 //
  2555 //                /* Grow result if needed */
  2556 //                int mapLen = lowerCharArray.length;
  2557 //                if (mapLen > srcCount) {
  2558 //                    char[] result2 = new char[result.length + mapLen - srcCount];
  2559 //                    System.arraycopy(result, 0, result2, 0,
  2560 //                        i + resultOffset);
  2561 //                    result = result2;
  2562 //                }
  2563 //                for (int x=0; x<mapLen; ++x) {
  2564 //                    result[i+resultOffset+x] = lowerCharArray[x];
  2565 //                }
  2566 //                resultOffset += (mapLen - srcCount);
  2567 //            } else {
  2568 //                result[i+resultOffset] = (char)lowerChar;
  2569 //            }
  2570 //        }
  2571 //        return new String(0, count+resultOffset, result);
  2572 //    }
  2573 
  2574     /**
  2575      * Converts all of the characters in this <code>String</code> to lower
  2576      * case using the rules of the default locale. This is equivalent to calling
  2577      * <code>toLowerCase(Locale.getDefault())</code>.
  2578      * <p>
  2579      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
  2580      * results if used for strings that are intended to be interpreted locale
  2581      * independently.
  2582      * Examples are programming language identifiers, protocol keys, and HTML
  2583      * tags.
  2584      * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
  2585      * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
  2586      * LATIN SMALL LETTER DOTLESS I character.
  2587      * To obtain correct results for locale insensitive strings, use
  2588      * <code>toLowerCase(Locale.ENGLISH)</code>.
  2589      * <p>
  2590      * @return  the <code>String</code>, converted to lowercase.
  2591      * @see     java.lang.String#toLowerCase(Locale)
  2592      */
  2593     @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
  2594     public String toLowerCase() {
  2595         return null;
  2596     }
  2597 
  2598     /**
  2599      * Converts all of the characters in this <code>String</code> to upper
  2600      * case using the rules of the given <code>Locale</code>. Case mapping is based
  2601      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
  2602      * class. Since case mappings are not always 1:1 char mappings, the resulting
  2603      * <code>String</code> may be a different length than the original <code>String</code>.
  2604      * <p>
  2605      * Examples of locale-sensitive and 1:M case mappings are in the following table.
  2606      * <p>
  2607      * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
  2608      * <tr>
  2609      *   <th>Language Code of Locale</th>
  2610      *   <th>Lower Case</th>
  2611      *   <th>Upper Case</th>
  2612      *   <th>Description</th>
  2613      * </tr>
  2614      * <tr>
  2615      *   <td>tr (Turkish)</td>
  2616      *   <td>&#92;u0069</td>
  2617      *   <td>&#92;u0130</td>
  2618      *   <td>small letter i -&gt; capital letter I with dot above</td>
  2619      * </tr>
  2620      * <tr>
  2621      *   <td>tr (Turkish)</td>
  2622      *   <td>&#92;u0131</td>
  2623      *   <td>&#92;u0049</td>
  2624      *   <td>small letter dotless i -&gt; capital letter I</td>
  2625      * </tr>
  2626      * <tr>
  2627      *   <td>(all)</td>
  2628      *   <td>&#92;u00df</td>
  2629      *   <td>&#92;u0053 &#92;u0053</td>
  2630      *   <td>small letter sharp s -&gt; two letters: SS</td>
  2631      * </tr>
  2632      * <tr>
  2633      *   <td>(all)</td>
  2634      *   <td>Fahrvergn&uuml;gen</td>
  2635      *   <td>FAHRVERGN&Uuml;GEN</td>
  2636      *   <td></td>
  2637      * </tr>
  2638      * </table>
  2639      * @param locale use the case transformation rules for this locale
  2640      * @return the <code>String</code>, converted to uppercase.
  2641      * @see     java.lang.String#toUpperCase()
  2642      * @see     java.lang.String#toLowerCase()
  2643      * @see     java.lang.String#toLowerCase(Locale)
  2644      * @since   1.1
  2645      */
  2646     public String toUpperCase(Locale locale) {
  2647         return toUpperCase();
  2648     }
  2649     /* not for javascript 
  2650         if (locale == null) {
  2651             throw new NullPointerException();
  2652         }
  2653 
  2654         int     firstLower;
  2655 
  2656         // Now check if there are any characters that need to be changed. 
  2657         scan: {
  2658             for (firstLower = 0 ; firstLower < count; ) {
  2659                 int c = (int)value[offset+firstLower];
  2660                 int srcCount;
  2661                 if ((c >= Character.MIN_HIGH_SURROGATE) &&
  2662                     (c <= Character.MAX_HIGH_SURROGATE)) {
  2663                     c = codePointAt(firstLower);
  2664                     srcCount = Character.charCount(c);
  2665                 } else {
  2666                     srcCount = 1;
  2667                 }
  2668                 int upperCaseChar = Character.toUpperCaseEx(c);
  2669                 if ((upperCaseChar == Character.ERROR) ||
  2670                     (c != upperCaseChar)) {
  2671                     break scan;
  2672                 }
  2673                 firstLower += srcCount;
  2674             }
  2675             return this;
  2676         }
  2677 
  2678         char[]  result       = new char[count]; /* may grow *
  2679         int     resultOffset = 0;  /* result may grow, so i+resultOffset
  2680                                     * is the write location in result *
  2681 
  2682         /* Just copy the first few upperCase characters. *
  2683         System.arraycopy(value, offset, result, 0, firstLower);
  2684 
  2685         String lang = locale.getLanguage();
  2686         boolean localeDependent =
  2687             (lang == "tr" || lang == "az" || lang == "lt");
  2688         char[] upperCharArray;
  2689         int upperChar;
  2690         int srcChar;
  2691         int srcCount;
  2692         for (int i = firstLower; i < count; i += srcCount) {
  2693             srcChar = (int)value[offset+i];
  2694             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
  2695                 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
  2696                 srcChar = codePointAt(i);
  2697                 srcCount = Character.charCount(srcChar);
  2698             } else {
  2699                 srcCount = 1;
  2700             }
  2701             if (localeDependent) {
  2702                 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
  2703             } else {
  2704                 upperChar = Character.toUpperCaseEx(srcChar);
  2705             }
  2706             if ((upperChar == Character.ERROR) ||
  2707                 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
  2708                 if (upperChar == Character.ERROR) {
  2709                     if (localeDependent) {
  2710                         upperCharArray =
  2711                             ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
  2712                     } else {
  2713                         upperCharArray = Character.toUpperCaseCharArray(srcChar);
  2714                     }
  2715                 } else if (srcCount == 2) {
  2716                     resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
  2717                     continue;
  2718                 } else {
  2719                     upperCharArray = Character.toChars(upperChar);
  2720                 }
  2721 
  2722                 /* Grow result if needed *
  2723                 int mapLen = upperCharArray.length;
  2724                 if (mapLen > srcCount) {
  2725                     char[] result2 = new char[result.length + mapLen - srcCount];
  2726                     System.arraycopy(result, 0, result2, 0,
  2727                         i + resultOffset);
  2728                     result = result2;
  2729                 }
  2730                 for (int x=0; x<mapLen; ++x) {
  2731                     result[i+resultOffset+x] = upperCharArray[x];
  2732                 }
  2733                 resultOffset += (mapLen - srcCount);
  2734             } else {
  2735                 result[i+resultOffset] = (char)upperChar;
  2736             }
  2737         }
  2738         return new String(0, count+resultOffset, result);
  2739     }
  2740     */
  2741 
  2742     /**
  2743      * Converts all of the characters in this <code>String</code> to upper
  2744      * case using the rules of the default locale. This method is equivalent to
  2745      * <code>toUpperCase(Locale.getDefault())</code>.
  2746      * <p>
  2747      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
  2748      * results if used for strings that are intended to be interpreted locale
  2749      * independently.
  2750      * Examples are programming language identifiers, protocol keys, and HTML
  2751      * tags.
  2752      * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
  2753      * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
  2754      * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
  2755      * To obtain correct results for locale insensitive strings, use
  2756      * <code>toUpperCase(Locale.ENGLISH)</code>.
  2757      * <p>
  2758      * @return  the <code>String</code>, converted to uppercase.
  2759      * @see     java.lang.String#toUpperCase(Locale)
  2760      */
  2761     @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
  2762     public String toUpperCase() {
  2763         return null;
  2764     }
  2765 
  2766     /**
  2767      * Returns a copy of the string, with leading and trailing whitespace
  2768      * omitted.
  2769      * <p>
  2770      * If this <code>String</code> object represents an empty character
  2771      * sequence, or the first and last characters of character sequence
  2772      * represented by this <code>String</code> object both have codes
  2773      * greater than <code>'&#92;u0020'</code> (the space character), then a
  2774      * reference to this <code>String</code> object is returned.
  2775      * <p>
  2776      * Otherwise, if there is no character with a code greater than
  2777      * <code>'&#92;u0020'</code> in the string, then a new
  2778      * <code>String</code> object representing an empty string is created
  2779      * and returned.
  2780      * <p>
  2781      * Otherwise, let <i>k</i> be the index of the first character in the
  2782      * string whose code is greater than <code>'&#92;u0020'</code>, and let
  2783      * <i>m</i> be the index of the last character in the string whose code
  2784      * is greater than <code>'&#92;u0020'</code>. A new <code>String</code>
  2785      * object is created, representing the substring of this string that
  2786      * begins with the character at index <i>k</i> and ends with the
  2787      * character at index <i>m</i>-that is, the result of
  2788      * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
  2789      * <p>
  2790      * This method may be used to trim whitespace (as defined above) from
  2791      * the beginning and end of a string.
  2792      *
  2793      * @return  A copy of this string with leading and trailing white
  2794      *          space removed, or this string if it has no leading or
  2795      *          trailing white space.
  2796      */
  2797     public String trim() {
  2798         int len = length();
  2799         int st = 0;
  2800         int off = offset();      /* avoid getfield opcode */
  2801         char[] val = toCharArray();    /* avoid getfield opcode */
  2802 
  2803         while ((st < len) && (val[off + st] <= ' ')) {
  2804             st++;
  2805         }
  2806         while ((st < len) && (val[off + len - 1] <= ' ')) {
  2807             len--;
  2808         }
  2809         return ((st > 0) || (len < length())) ? substring(st, len) : this;
  2810     }
  2811 
  2812     /**
  2813      * This object (which is already a string!) is itself returned.
  2814      *
  2815      * @return  the string itself.
  2816      */
  2817     @JavaScriptBody(args = {}, body = "return this.toString();")
  2818     public String toString() {
  2819         return this;
  2820     }
  2821 
  2822     /**
  2823      * Converts this string to a new character array.
  2824      *
  2825      * @return  a newly allocated character array whose length is the length
  2826      *          of this string and whose contents are initialized to contain
  2827      *          the character sequence represented by this string.
  2828      */
  2829     public char[] toCharArray() {
  2830         char result[] = new char[length()];
  2831         getChars(0, length(), result, 0);
  2832         return result;
  2833     }
  2834 
  2835     /**
  2836      * Returns a formatted string using the specified format string and
  2837      * arguments.
  2838      *
  2839      * <p> The locale always used is the one returned by {@link
  2840      * java.util.Locale#getDefault() Locale.getDefault()}.
  2841      *
  2842      * @param  format
  2843      *         A <a href="../util/Formatter.html#syntax">format string</a>
  2844      *
  2845      * @param  args
  2846      *         Arguments referenced by the format specifiers in the format
  2847      *         string.  If there are more arguments than format specifiers, the
  2848      *         extra arguments are ignored.  The number of arguments is
  2849      *         variable and may be zero.  The maximum number of arguments is
  2850      *         limited by the maximum dimension of a Java array as defined by
  2851      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
  2852      *         The behaviour on a
  2853      *         <tt>null</tt> argument depends on the <a
  2854      *         href="../util/Formatter.html#syntax">conversion</a>.
  2855      *
  2856      * @throws  IllegalFormatException
  2857      *          If a format string contains an illegal syntax, a format
  2858      *          specifier that is incompatible with the given arguments,
  2859      *          insufficient arguments given the format string, or other
  2860      *          illegal conditions.  For specification of all possible
  2861      *          formatting errors, see the <a
  2862      *          href="../util/Formatter.html#detail">Details</a> section of the
  2863      *          formatter class specification.
  2864      *
  2865      * @throws  NullPointerException
  2866      *          If the <tt>format</tt> is <tt>null</tt>
  2867      *
  2868      * @return  A formatted string
  2869      *
  2870      * @see  java.util.Formatter
  2871      * @since  1.5
  2872      */
  2873     public static String format(String format, Object ... args) {
  2874         return format((Locale)null, format, args);
  2875     }
  2876 
  2877     /**
  2878      * Returns a formatted string using the specified locale, format string,
  2879      * and arguments.
  2880      *
  2881      * @param  l
  2882      *         The {@linkplain java.util.Locale locale} to apply during
  2883      *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
  2884      *         is applied.
  2885      *
  2886      * @param  format
  2887      *         A <a href="../util/Formatter.html#syntax">format string</a>
  2888      *
  2889      * @param  args
  2890      *         Arguments referenced by the format specifiers in the format
  2891      *         string.  If there are more arguments than format specifiers, the
  2892      *         extra arguments are ignored.  The number of arguments is
  2893      *         variable and may be zero.  The maximum number of arguments is
  2894      *         limited by the maximum dimension of a Java array as defined by
  2895      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
  2896      *         The behaviour on a
  2897      *         <tt>null</tt> argument depends on the <a
  2898      *         href="../util/Formatter.html#syntax">conversion</a>.
  2899      *
  2900      * @throws  IllegalFormatException
  2901      *          If a format string contains an illegal syntax, a format
  2902      *          specifier that is incompatible with the given arguments,
  2903      *          insufficient arguments given the format string, or other
  2904      *          illegal conditions.  For specification of all possible
  2905      *          formatting errors, see the <a
  2906      *          href="../util/Formatter.html#detail">Details</a> section of the
  2907      *          formatter class specification
  2908      *
  2909      * @throws  NullPointerException
  2910      *          If the <tt>format</tt> is <tt>null</tt>
  2911      *
  2912      * @return  A formatted string
  2913      *
  2914      * @see  java.util.Formatter
  2915      * @since  1.5
  2916      */
  2917     public static String format(Locale l, String format, Object ... args) {
  2918         String p = format;
  2919         for (int i = 0; i < args.length; i++) {
  2920             String v = args[i] == null ? "null" : args[i].toString();
  2921             p = p.replaceFirst("%s", v);
  2922         }
  2923         return p;
  2924         // return new Formatter(l).format(format, args).toString();
  2925     }
  2926 
  2927     /**
  2928      * Returns the string representation of the <code>Object</code> argument.
  2929      *
  2930      * @param   obj   an <code>Object</code>.
  2931      * @return  if the argument is <code>null</code>, then a string equal to
  2932      *          <code>"null"</code>; otherwise, the value of
  2933      *          <code>obj.toString()</code> is returned.
  2934      * @see     java.lang.Object#toString()
  2935      */
  2936     public static String valueOf(Object obj) {
  2937         return (obj == null) ? "null" : obj.toString();
  2938     }
  2939 
  2940     /**
  2941      * Returns the string representation of the <code>char</code> array
  2942      * argument. The contents of the character array are copied; subsequent
  2943      * modification of the character array does not affect the newly
  2944      * created string.
  2945      *
  2946      * @param   data   a <code>char</code> array.
  2947      * @return  a newly allocated string representing the same sequence of
  2948      *          characters contained in the character array argument.
  2949      */
  2950     public static String valueOf(char data[]) {
  2951         return new String(data);
  2952     }
  2953 
  2954     /**
  2955      * Returns the string representation of a specific subarray of the
  2956      * <code>char</code> array argument.
  2957      * <p>
  2958      * The <code>offset</code> argument is the index of the first
  2959      * character of the subarray. The <code>count</code> argument
  2960      * specifies the length of the subarray. The contents of the subarray
  2961      * are copied; subsequent modification of the character array does not
  2962      * affect the newly created string.
  2963      *
  2964      * @param   data     the character array.
  2965      * @param   offset   the initial offset into the value of the
  2966      *                  <code>String</code>.
  2967      * @param   count    the length of the value of the <code>String</code>.
  2968      * @return  a string representing the sequence of characters contained
  2969      *          in the subarray of the character array argument.
  2970      * @exception IndexOutOfBoundsException if <code>offset</code> is
  2971      *          negative, or <code>count</code> is negative, or
  2972      *          <code>offset+count</code> is larger than
  2973      *          <code>data.length</code>.
  2974      */
  2975     public static String valueOf(char data[], int offset, int count) {
  2976         return new String(data, offset, count);
  2977     }
  2978 
  2979     /**
  2980      * Returns a String that represents the character sequence in the
  2981      * array specified.
  2982      *
  2983      * @param   data     the character array.
  2984      * @param   offset   initial offset of the subarray.
  2985      * @param   count    length of the subarray.
  2986      * @return  a <code>String</code> that contains the characters of the
  2987      *          specified subarray of the character array.
  2988      */
  2989     public static String copyValueOf(char data[], int offset, int count) {
  2990         // All public String constructors now copy the data.
  2991         return new String(data, offset, count);
  2992     }
  2993 
  2994     /**
  2995      * Returns a String that represents the character sequence in the
  2996      * array specified.
  2997      *
  2998      * @param   data   the character array.
  2999      * @return  a <code>String</code> that contains the characters of the
  3000      *          character array.
  3001      */
  3002     public static String copyValueOf(char data[]) {
  3003         return copyValueOf(data, 0, data.length);
  3004     }
  3005 
  3006     /**
  3007      * Returns the string representation of the <code>boolean</code> argument.
  3008      *
  3009      * @param   b   a <code>boolean</code>.
  3010      * @return  if the argument is <code>true</code>, a string equal to
  3011      *          <code>"true"</code> is returned; otherwise, a string equal to
  3012      *          <code>"false"</code> is returned.
  3013      */
  3014     public static String valueOf(boolean b) {
  3015         return b ? "true" : "false";
  3016     }
  3017 
  3018     /**
  3019      * Returns the string representation of the <code>char</code>
  3020      * argument.
  3021      *
  3022      * @param   c   a <code>char</code>.
  3023      * @return  a string of length <code>1</code> containing
  3024      *          as its single character the argument <code>c</code>.
  3025      */
  3026     public static String valueOf(char c) {
  3027         char data[] = {c};
  3028         return new String(data, 0, 1);
  3029     }
  3030 
  3031     /**
  3032      * Returns the string representation of the <code>int</code> argument.
  3033      * <p>
  3034      * The representation is exactly the one returned by the
  3035      * <code>Integer.toString</code> method of one argument.
  3036      *
  3037      * @param   i   an <code>int</code>.
  3038      * @return  a string representation of the <code>int</code> argument.
  3039      * @see     java.lang.Integer#toString(int, int)
  3040      */
  3041     public static String valueOf(int i) {
  3042         return Integer.toString(i);
  3043     }
  3044 
  3045     /**
  3046      * Returns the string representation of the <code>long</code> argument.
  3047      * <p>
  3048      * The representation is exactly the one returned by the
  3049      * <code>Long.toString</code> method of one argument.
  3050      *
  3051      * @param   l   a <code>long</code>.
  3052      * @return  a string representation of the <code>long</code> argument.
  3053      * @see     java.lang.Long#toString(long)
  3054      */
  3055     public static String valueOf(long l) {
  3056         return Long.toString(l);
  3057     }
  3058 
  3059     /**
  3060      * Returns the string representation of the <code>float</code> argument.
  3061      * <p>
  3062      * The representation is exactly the one returned by the
  3063      * <code>Float.toString</code> method of one argument.
  3064      *
  3065      * @param   f   a <code>float</code>.
  3066      * @return  a string representation of the <code>float</code> argument.
  3067      * @see     java.lang.Float#toString(float)
  3068      */
  3069     public static String valueOf(float f) {
  3070         return Float.toString(f);
  3071     }
  3072 
  3073     /**
  3074      * Returns the string representation of the <code>double</code> argument.
  3075      * <p>
  3076      * The representation is exactly the one returned by the
  3077      * <code>Double.toString</code> method of one argument.
  3078      *
  3079      * @param   d   a <code>double</code>.
  3080      * @return  a  string representation of the <code>double</code> argument.
  3081      * @see     java.lang.Double#toString(double)
  3082      */
  3083     public static String valueOf(double d) {
  3084         return Double.toString(d);
  3085     }
  3086 
  3087     /**
  3088      * Returns a canonical representation for the string object.
  3089      * <p>
  3090      * A pool of strings, initially empty, is maintained privately by the
  3091      * class <code>String</code>.
  3092      * <p>
  3093      * When the intern method is invoked, if the pool already contains a
  3094      * string equal to this <code>String</code> object as determined by
  3095      * the {@link #equals(Object)} method, then the string from the pool is
  3096      * returned. Otherwise, this <code>String</code> object is added to the
  3097      * pool and a reference to this <code>String</code> object is returned.
  3098      * <p>
  3099      * It follows that for any two strings <code>s</code> and <code>t</code>,
  3100      * <code>s.intern()&nbsp;==&nbsp;t.intern()</code> is <code>true</code>
  3101      * if and only if <code>s.equals(t)</code> is <code>true</code>.
  3102      * <p>
  3103      * All literal strings and string-valued constant expressions are
  3104      * interned. String literals are defined in section 3.10.5 of the
  3105      * <cite>The Java&trade; Language Specification</cite>.
  3106      *
  3107      * @return  a string that has the same contents as this string, but is
  3108      *          guaranteed to be from a pool of unique strings.
  3109      */
  3110     @JavaScriptBody(args = {}, body = 
  3111         "var s = this.toString().toString();\n" +
  3112         "var i = String.intern || (String.intern = {})\n" + 
  3113         "if (!i[s]) {\n" +
  3114         "  i[s] = s;\n" +
  3115         "}\n" +
  3116         "return i[s];"
  3117     )
  3118     public native String intern();
  3119     
  3120     
  3121     private static <T> T checkUTF8(T data, String charsetName)
  3122         throws UnsupportedEncodingException {
  3123         if (charsetName == null) {
  3124             throw new NullPointerException("charsetName");
  3125         }
  3126         if (!charsetName.equalsIgnoreCase("UTF-8")
  3127             && !charsetName.equalsIgnoreCase("UTF8")) {
  3128             throw new UnsupportedEncodingException(charsetName);
  3129         }
  3130         return data;
  3131     }
  3132     
  3133     private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
  3134         int c = arr[index[0]++] & 0xff;
  3135         switch (c >> 4) {
  3136             case 0:
  3137             case 1:
  3138             case 2:
  3139             case 3:
  3140             case 4:
  3141             case 5:
  3142             case 6:
  3143             case 7:
  3144                 /* 0xxxxxxx*/
  3145                 return c;
  3146             case 12:
  3147             case 13: {
  3148                 /* 110x xxxx   10xx xxxx*/
  3149                 int char2 = (int) arr[index[0]++];
  3150                 if ((char2 & 0xC0) != 0x80) {
  3151                     throw new IndexOutOfBoundsException("malformed input");
  3152                 }
  3153                 return (((c & 0x1F) << 6) | (char2 & 0x3F));
  3154             }
  3155             case 14: {
  3156                 /* 1110 xxxx  10xx xxxx  10xx xxxx */
  3157                 int char2 = arr[index[0]++];
  3158                 int char3 = arr[index[0]++];
  3159                 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
  3160                     throw new IndexOutOfBoundsException("malformed input");
  3161                 }
  3162                 return (((c & 0x0F) << 12)
  3163                     | ((char2 & 0x3F) << 6)
  3164                     | ((char3 & 0x3F) << 0));
  3165             }
  3166             default:
  3167                 /* 10xx xxxx,  1111 xxxx */
  3168                 throw new IndexOutOfBoundsException("malformed input");
  3169         }
  3170         
  3171     }
  3172 }