rt/emul/mini/src/main/java/java/lang/String.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 31 Oct 2013 15:01:35 +0100
changeset 1402 e896bc687984
parent 1382 7f4d603c46dd
child 1513 ba912ef24b27
permissions -rw-r--r--
Implementing String's intern()
     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         char v1[] = toCharArray();
  1189         char v2[] = anotherString.toCharArray();
  1190         int i = offset();
  1191         int j = anotherString.offset();
  1192 
  1193         if (i == j) {
  1194             int k = i;
  1195             int lim = n + i;
  1196             while (k < lim) {
  1197                 char c1 = v1[k];
  1198                 char c2 = v2[k];
  1199                 if (c1 != c2) {
  1200                     return c1 - c2;
  1201                 }
  1202                 k++;
  1203             }
  1204         } else {
  1205             while (n-- != 0) {
  1206                 char c1 = v1[i++];
  1207                 char c2 = v2[j++];
  1208                 if (c1 != c2) {
  1209                     return c1 - c2;
  1210                 }
  1211             }
  1212         }
  1213         return len1 - len2;
  1214     }
  1215 
  1216     /**
  1217      * A Comparator that orders <code>String</code> objects as by
  1218      * <code>compareToIgnoreCase</code>. This comparator is serializable.
  1219      * <p>
  1220      * Note that this Comparator does <em>not</em> take locale into account,
  1221      * and will result in an unsatisfactory ordering for certain locales.
  1222      * The java.text package provides <em>Collators</em> to allow
  1223      * locale-sensitive ordering.
  1224      *
  1225      * @see     java.text.Collator#compare(String, String)
  1226      * @since   1.2
  1227      */
  1228     public static final Comparator<String> CASE_INSENSITIVE_ORDER
  1229                                          = new CaseInsensitiveComparator();
  1230 
  1231     private static int offset() {
  1232         return 0;
  1233     }
  1234 
  1235     private static class CaseInsensitiveComparator
  1236                          implements Comparator<String>, java.io.Serializable {
  1237         // use serialVersionUID from JDK 1.2.2 for interoperability
  1238         private static final long serialVersionUID = 8575799808933029326L;
  1239 
  1240         public int compare(String s1, String s2) {
  1241             int n1 = s1.length();
  1242             int n2 = s2.length();
  1243             int min = Math.min(n1, n2);
  1244             for (int i = 0; i < min; i++) {
  1245                 char c1 = s1.charAt(i);
  1246                 char c2 = s2.charAt(i);
  1247                 if (c1 != c2) {
  1248                     c1 = Character.toUpperCase(c1);
  1249                     c2 = Character.toUpperCase(c2);
  1250                     if (c1 != c2) {
  1251                         c1 = Character.toLowerCase(c1);
  1252                         c2 = Character.toLowerCase(c2);
  1253                         if (c1 != c2) {
  1254                             // No overflow because of numeric promotion
  1255                             return c1 - c2;
  1256                         }
  1257                     }
  1258                 }
  1259             }
  1260             return n1 - n2;
  1261         }
  1262     }
  1263 
  1264     /**
  1265      * Compares two strings lexicographically, ignoring case
  1266      * differences. This method returns an integer whose sign is that of
  1267      * calling <code>compareTo</code> with normalized versions of the strings
  1268      * where case differences have been eliminated by calling
  1269      * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
  1270      * each character.
  1271      * <p>
  1272      * Note that this method does <em>not</em> take locale into account,
  1273      * and will result in an unsatisfactory ordering for certain locales.
  1274      * The java.text package provides <em>collators</em> to allow
  1275      * locale-sensitive ordering.
  1276      *
  1277      * @param   str   the <code>String</code> to be compared.
  1278      * @return  a negative integer, zero, or a positive integer as the
  1279      *          specified String is greater than, equal to, or less
  1280      *          than this String, ignoring case considerations.
  1281      * @see     java.text.Collator#compare(String, String)
  1282      * @since   1.2
  1283      */
  1284     public int compareToIgnoreCase(String str) {
  1285         return CASE_INSENSITIVE_ORDER.compare(this, str);
  1286     }
  1287 
  1288     /**
  1289      * Tests if two string regions are equal.
  1290      * <p>
  1291      * A substring of this <tt>String</tt> object is compared to a substring
  1292      * of the argument other. The result is true if these substrings
  1293      * represent identical character sequences. The substring of this
  1294      * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
  1295      * and has length <tt>len</tt>. The substring of other to be compared
  1296      * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
  1297      * result is <tt>false</tt> if and only if at least one of the following
  1298      * is true:
  1299      * <ul><li><tt>toffset</tt> is negative.
  1300      * <li><tt>ooffset</tt> is negative.
  1301      * <li><tt>toffset+len</tt> is greater than the length of this
  1302      * <tt>String</tt> object.
  1303      * <li><tt>ooffset+len</tt> is greater than the length of the other
  1304      * argument.
  1305      * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
  1306      * such that:
  1307      * <tt>this.charAt(toffset+<i>k</i>)&nbsp;!=&nbsp;other.charAt(ooffset+<i>k</i>)</tt>
  1308      * </ul>
  1309      *
  1310      * @param   toffset   the starting offset of the subregion in this string.
  1311      * @param   other     the string argument.
  1312      * @param   ooffset   the starting offset of the subregion in the string
  1313      *                    argument.
  1314      * @param   len       the number of characters to compare.
  1315      * @return  <code>true</code> if the specified subregion of this string
  1316      *          exactly matches the specified subregion of the string argument;
  1317      *          <code>false</code> otherwise.
  1318      */
  1319     public boolean regionMatches(int toffset, String other, int ooffset,
  1320                                  int len) {
  1321         char ta[] = toCharArray();
  1322         int to = offset() + toffset;
  1323         char pa[] = other.toCharArray();
  1324         int po = other.offset() + ooffset;
  1325         // Note: toffset, ooffset, or len might be near -1>>>1.
  1326         if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len)
  1327             || (ooffset > (long)other.length() - len)) {
  1328             return false;
  1329         }
  1330         while (len-- > 0) {
  1331             if (ta[to++] != pa[po++]) {
  1332                 return false;
  1333             }
  1334         }
  1335         return true;
  1336     }
  1337 
  1338     /**
  1339      * Tests if two string regions are equal.
  1340      * <p>
  1341      * A substring of this <tt>String</tt> object is compared to a substring
  1342      * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
  1343      * substrings represent character sequences that are the same, ignoring
  1344      * case if and only if <tt>ignoreCase</tt> is true. The substring of
  1345      * this <tt>String</tt> object to be compared begins at index
  1346      * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
  1347      * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
  1348      * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
  1349      * at least one of the following is true:
  1350      * <ul><li><tt>toffset</tt> is negative.
  1351      * <li><tt>ooffset</tt> is negative.
  1352      * <li><tt>toffset+len</tt> is greater than the length of this
  1353      * <tt>String</tt> object.
  1354      * <li><tt>ooffset+len</tt> is greater than the length of the other
  1355      * argument.
  1356      * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
  1357      * integer <i>k</i> less than <tt>len</tt> such that:
  1358      * <blockquote><pre>
  1359      * this.charAt(toffset+k) != other.charAt(ooffset+k)
  1360      * </pre></blockquote>
  1361      * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
  1362      * integer <i>k</i> less than <tt>len</tt> such that:
  1363      * <blockquote><pre>
  1364      * Character.toLowerCase(this.charAt(toffset+k)) !=
  1365                Character.toLowerCase(other.charAt(ooffset+k))
  1366      * </pre></blockquote>
  1367      * and:
  1368      * <blockquote><pre>
  1369      * Character.toUpperCase(this.charAt(toffset+k)) !=
  1370      *         Character.toUpperCase(other.charAt(ooffset+k))
  1371      * </pre></blockquote>
  1372      * </ul>
  1373      *
  1374      * @param   ignoreCase   if <code>true</code>, ignore case when comparing
  1375      *                       characters.
  1376      * @param   toffset      the starting offset of the subregion in this
  1377      *                       string.
  1378      * @param   other        the string argument.
  1379      * @param   ooffset      the starting offset of the subregion in the string
  1380      *                       argument.
  1381      * @param   len          the number of characters to compare.
  1382      * @return  <code>true</code> if the specified subregion of this string
  1383      *          matches the specified subregion of the string argument;
  1384      *          <code>false</code> otherwise. Whether the matching is exact
  1385      *          or case insensitive depends on the <code>ignoreCase</code>
  1386      *          argument.
  1387      */
  1388     public boolean regionMatches(boolean ignoreCase, int toffset,
  1389                            String other, int ooffset, int len) {
  1390         char ta[] = toCharArray();
  1391         int to = offset() + toffset;
  1392         char pa[] = other.toCharArray();
  1393         int po = other.offset() + ooffset;
  1394         // Note: toffset, ooffset, or len might be near -1>>>1.
  1395         if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) ||
  1396                 (ooffset > (long)other.length() - len)) {
  1397             return false;
  1398         }
  1399         while (len-- > 0) {
  1400             char c1 = ta[to++];
  1401             char c2 = pa[po++];
  1402             if (c1 == c2) {
  1403                 continue;
  1404             }
  1405             if (ignoreCase) {
  1406                 // If characters don't match but case may be ignored,
  1407                 // try converting both characters to uppercase.
  1408                 // If the results match, then the comparison scan should
  1409                 // continue.
  1410                 char u1 = Character.toUpperCase(c1);
  1411                 char u2 = Character.toUpperCase(c2);
  1412                 if (u1 == u2) {
  1413                     continue;
  1414                 }
  1415                 // Unfortunately, conversion to uppercase does not work properly
  1416                 // for the Georgian alphabet, which has strange rules about case
  1417                 // conversion.  So we need to make one last check before
  1418                 // exiting.
  1419                 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
  1420                     continue;
  1421                 }
  1422             }
  1423             return false;
  1424         }
  1425         return true;
  1426     }
  1427 
  1428     /**
  1429      * Tests if the substring of this string beginning at the
  1430      * specified index starts with the specified prefix.
  1431      *
  1432      * @param   prefix    the prefix.
  1433      * @param   toffset   where to begin looking in this string.
  1434      * @return  <code>true</code> if the character sequence represented by the
  1435      *          argument is a prefix of the substring of this object starting
  1436      *          at index <code>toffset</code>; <code>false</code> otherwise.
  1437      *          The result is <code>false</code> if <code>toffset</code> is
  1438      *          negative or greater than the length of this
  1439      *          <code>String</code> object; otherwise the result is the same
  1440      *          as the result of the expression
  1441      *          <pre>
  1442      *          this.substring(toffset).startsWith(prefix)
  1443      *          </pre>
  1444      */
  1445     @JavaScriptBody(args = { "find", "from" }, body=
  1446         "find = find.toString();\n" +
  1447         "return this.toString().substring(from, from + find.length) === find;\n"
  1448     )
  1449     public boolean startsWith(String prefix, int toffset) {
  1450         char ta[] = toCharArray();
  1451         int to = offset() + toffset;
  1452         char pa[] = prefix.toCharArray();
  1453         int po = prefix.offset();
  1454         int pc = prefix.length();
  1455         // Note: toffset might be near -1>>>1.
  1456         if ((toffset < 0) || (toffset > length() - pc)) {
  1457             return false;
  1458         }
  1459         while (--pc >= 0) {
  1460             if (ta[to++] != pa[po++]) {
  1461                 return false;
  1462             }
  1463         }
  1464         return true;
  1465     }
  1466 
  1467     /**
  1468      * Tests if this string starts with the specified prefix.
  1469      *
  1470      * @param   prefix   the prefix.
  1471      * @return  <code>true</code> if the character sequence represented by the
  1472      *          argument is a prefix of the character sequence represented by
  1473      *          this string; <code>false</code> otherwise.
  1474      *          Note also that <code>true</code> will be returned if the
  1475      *          argument is an empty string or is equal to this
  1476      *          <code>String</code> object as determined by the
  1477      *          {@link #equals(Object)} method.
  1478      * @since   1. 0
  1479      */
  1480     public boolean startsWith(String prefix) {
  1481         return startsWith(prefix, 0);
  1482     }
  1483 
  1484     /**
  1485      * Tests if this string ends with the specified suffix.
  1486      *
  1487      * @param   suffix   the suffix.
  1488      * @return  <code>true</code> if the character sequence represented by the
  1489      *          argument is a suffix of the character sequence represented by
  1490      *          this object; <code>false</code> otherwise. Note that the
  1491      *          result will be <code>true</code> if the argument is the
  1492      *          empty string or is equal to this <code>String</code> object
  1493      *          as determined by the {@link #equals(Object)} method.
  1494      */
  1495     public boolean endsWith(String suffix) {
  1496         return startsWith(suffix, length() - suffix.length());
  1497     }
  1498 
  1499     /**
  1500      * Returns a hash code for this string. The hash code for a
  1501      * <code>String</code> object is computed as
  1502      * <blockquote><pre>
  1503      * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
  1504      * </pre></blockquote>
  1505      * using <code>int</code> arithmetic, where <code>s[i]</code> is the
  1506      * <i>i</i>th character of the string, <code>n</code> is the length of
  1507      * the string, and <code>^</code> indicates exponentiation.
  1508      * (The hash value of the empty string is zero.)
  1509      *
  1510      * @return  a hash code value for this object.
  1511      */
  1512     public int hashCode() {
  1513         return super.hashCode();
  1514     }
  1515     int computeHashCode() {
  1516         int h = 0;
  1517         if (h == 0 && length() > 0) {
  1518             int off = offset();
  1519             int len = length();
  1520 
  1521             for (int i = 0; i < len; i++) {
  1522                 h = 31*h + charAt(off++);
  1523             }
  1524         }
  1525         return h;
  1526     }
  1527 
  1528     /**
  1529      * Returns the index within this string of the first occurrence of
  1530      * the specified character. If a character with value
  1531      * <code>ch</code> occurs in the character sequence represented by
  1532      * this <code>String</code> object, then the index (in Unicode
  1533      * code units) of the first such occurrence is returned. For
  1534      * values of <code>ch</code> in the range from 0 to 0xFFFF
  1535      * (inclusive), this is the smallest value <i>k</i> such that:
  1536      * <blockquote><pre>
  1537      * this.charAt(<i>k</i>) == ch
  1538      * </pre></blockquote>
  1539      * is true. For other values of <code>ch</code>, it is the
  1540      * smallest value <i>k</i> such that:
  1541      * <blockquote><pre>
  1542      * this.codePointAt(<i>k</i>) == ch
  1543      * </pre></blockquote>
  1544      * is true. In either case, if no such character occurs in this
  1545      * string, then <code>-1</code> is returned.
  1546      *
  1547      * @param   ch   a character (Unicode code point).
  1548      * @return  the index of the first occurrence of the character in the
  1549      *          character sequence represented by this object, or
  1550      *          <code>-1</code> if the character does not occur.
  1551      */
  1552     public int indexOf(int ch) {
  1553         return indexOf(ch, 0);
  1554     }
  1555 
  1556     /**
  1557      * Returns the index within this string of the first occurrence of the
  1558      * specified character, starting the search at the specified index.
  1559      * <p>
  1560      * If a character with value <code>ch</code> occurs in the
  1561      * character sequence represented by this <code>String</code>
  1562      * object at an index no smaller than <code>fromIndex</code>, then
  1563      * the index of the first such occurrence is returned. For values
  1564      * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
  1565      * this is the smallest value <i>k</i> such that:
  1566      * <blockquote><pre>
  1567      * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex)
  1568      * </pre></blockquote>
  1569      * is true. For other values of <code>ch</code>, it is the
  1570      * smallest value <i>k</i> such that:
  1571      * <blockquote><pre>
  1572      * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex)
  1573      * </pre></blockquote>
  1574      * is true. In either case, if no such character occurs in this
  1575      * string at or after position <code>fromIndex</code>, then
  1576      * <code>-1</code> is returned.
  1577      *
  1578      * <p>
  1579      * There is no restriction on the value of <code>fromIndex</code>. If it
  1580      * is negative, it has the same effect as if it were zero: this entire
  1581      * string may be searched. If it is greater than the length of this
  1582      * string, it has the same effect as if it were equal to the length of
  1583      * this string: <code>-1</code> is returned.
  1584      *
  1585      * <p>All indices are specified in <code>char</code> values
  1586      * (Unicode code units).
  1587      *
  1588      * @param   ch          a character (Unicode code point).
  1589      * @param   fromIndex   the index to start the search from.
  1590      * @return  the index of the first occurrence of the character in the
  1591      *          character sequence represented by this object that is greater
  1592      *          than or equal to <code>fromIndex</code>, or <code>-1</code>
  1593      *          if the character does not occur.
  1594      */
  1595     @JavaScriptBody(args = { "ch", "from" }, body = 
  1596         "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
  1597         "return this.toString().indexOf(ch, from);\n"
  1598     )
  1599     public int indexOf(int ch, int fromIndex) {
  1600         if (fromIndex < 0) {
  1601             fromIndex = 0;
  1602         } else if (fromIndex >= length()) {
  1603             // Note: fromIndex might be near -1>>>1.
  1604             return -1;
  1605         }
  1606 
  1607         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
  1608             // handle most cases here (ch is a BMP code point or a
  1609             // negative value (invalid code point))
  1610             final char[] value = this.toCharArray();
  1611             final int offset = this.offset();
  1612             final int max = offset + length();
  1613             for (int i = offset + fromIndex; i < max ; i++) {
  1614                 if (value[i] == ch) {
  1615                     return i - offset;
  1616                 }
  1617             }
  1618             return -1;
  1619         } else {
  1620             return indexOfSupplementary(ch, fromIndex);
  1621         }
  1622     }
  1623 
  1624     /**
  1625      * Handles (rare) calls of indexOf with a supplementary character.
  1626      */
  1627     private int indexOfSupplementary(int ch, int fromIndex) {
  1628         if (Character.isValidCodePoint(ch)) {
  1629             final char[] value = this.toCharArray();
  1630             final int offset = this.offset();
  1631             final char hi = Character.highSurrogate(ch);
  1632             final char lo = Character.lowSurrogate(ch);
  1633             final int max = offset + length() - 1;
  1634             for (int i = offset + fromIndex; i < max; i++) {
  1635                 if (value[i] == hi && value[i+1] == lo) {
  1636                     return i - offset;
  1637                 }
  1638             }
  1639         }
  1640         return -1;
  1641     }
  1642 
  1643     /**
  1644      * Returns the index within this string of the last occurrence of
  1645      * the specified character. For values of <code>ch</code> in the
  1646      * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
  1647      * units) returned is the largest value <i>k</i> such that:
  1648      * <blockquote><pre>
  1649      * this.charAt(<i>k</i>) == ch
  1650      * </pre></blockquote>
  1651      * is true. For other values of <code>ch</code>, it is the
  1652      * largest value <i>k</i> such that:
  1653      * <blockquote><pre>
  1654      * this.codePointAt(<i>k</i>) == ch
  1655      * </pre></blockquote>
  1656      * is true.  In either case, if no such character occurs in this
  1657      * string, then <code>-1</code> is returned.  The
  1658      * <code>String</code> is searched backwards starting at the last
  1659      * character.
  1660      *
  1661      * @param   ch   a character (Unicode code point).
  1662      * @return  the index of the last occurrence of the character in the
  1663      *          character sequence represented by this object, or
  1664      *          <code>-1</code> if the character does not occur.
  1665      */
  1666     public int lastIndexOf(int ch) {
  1667         return lastIndexOf(ch, length() - 1);
  1668     }
  1669 
  1670     /**
  1671      * Returns the index within this string of the last occurrence of
  1672      * the specified character, searching backward starting at the
  1673      * specified index. For values of <code>ch</code> in the range
  1674      * from 0 to 0xFFFF (inclusive), the index returned is the largest
  1675      * value <i>k</i> such that:
  1676      * <blockquote><pre>
  1677      * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex)
  1678      * </pre></blockquote>
  1679      * is true. For other values of <code>ch</code>, it is the
  1680      * largest value <i>k</i> such that:
  1681      * <blockquote><pre>
  1682      * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex)
  1683      * </pre></blockquote>
  1684      * is true. In either case, if no such character occurs in this
  1685      * string at or before position <code>fromIndex</code>, then
  1686      * <code>-1</code> is returned.
  1687      *
  1688      * <p>All indices are specified in <code>char</code> values
  1689      * (Unicode code units).
  1690      *
  1691      * @param   ch          a character (Unicode code point).
  1692      * @param   fromIndex   the index to start the search from. There is no
  1693      *          restriction on the value of <code>fromIndex</code>. If it is
  1694      *          greater than or equal to the length of this string, it has
  1695      *          the same effect as if it were equal to one less than the
  1696      *          length of this string: this entire string may be searched.
  1697      *          If it is negative, it has the same effect as if it were -1:
  1698      *          -1 is returned.
  1699      * @return  the index of the last occurrence of the character in the
  1700      *          character sequence represented by this object that is less
  1701      *          than or equal to <code>fromIndex</code>, or <code>-1</code>
  1702      *          if the character does not occur before that point.
  1703      */
  1704     @JavaScriptBody(args = { "ch", "from" }, body = 
  1705         "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" +
  1706         "return this.toString().lastIndexOf(ch, from);"
  1707     )
  1708     public int lastIndexOf(int ch, int fromIndex) {
  1709         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
  1710             // handle most cases here (ch is a BMP code point or a
  1711             // negative value (invalid code point))
  1712             final char[] value = this.toCharArray();
  1713             final int offset = this.offset();
  1714             int i = offset + Math.min(fromIndex, length() - 1);
  1715             for (; i >= offset ; i--) {
  1716                 if (value[i] == ch) {
  1717                     return i - offset;
  1718                 }
  1719             }
  1720             return -1;
  1721         } else {
  1722             return lastIndexOfSupplementary(ch, fromIndex);
  1723         }
  1724     }
  1725 
  1726     /**
  1727      * Handles (rare) calls of lastIndexOf with a supplementary character.
  1728      */
  1729     private int lastIndexOfSupplementary(int ch, int fromIndex) {
  1730         if (Character.isValidCodePoint(ch)) {
  1731             final char[] value = this.toCharArray();
  1732             final int offset = this.offset();
  1733             char hi = Character.highSurrogate(ch);
  1734             char lo = Character.lowSurrogate(ch);
  1735             int i = offset + Math.min(fromIndex, length() - 2);
  1736             for (; i >= offset; i--) {
  1737                 if (value[i] == hi && value[i+1] == lo) {
  1738                     return i - offset;
  1739                 }
  1740             }
  1741         }
  1742         return -1;
  1743     }
  1744 
  1745     /**
  1746      * Returns the index within this string of the first occurrence of the
  1747      * specified substring.
  1748      *
  1749      * <p>The returned index is the smallest value <i>k</i> for which:
  1750      * <blockquote><pre>
  1751      * this.startsWith(str, <i>k</i>)
  1752      * </pre></blockquote>
  1753      * If no such value of <i>k</i> exists, then {@code -1} is returned.
  1754      *
  1755      * @param   str   the substring to search for.
  1756      * @return  the index of the first occurrence of the specified substring,
  1757      *          or {@code -1} if there is no such occurrence.
  1758      */
  1759     public int indexOf(String str) {
  1760         return indexOf(str, 0);
  1761     }
  1762 
  1763     /**
  1764      * Returns the index within this string of the first occurrence of the
  1765      * specified substring, starting at the specified index.
  1766      *
  1767      * <p>The returned index is the smallest value <i>k</i> for which:
  1768      * <blockquote><pre>
  1769      * <i>k</i> &gt;= fromIndex && this.startsWith(str, <i>k</i>)
  1770      * </pre></blockquote>
  1771      * If no such value of <i>k</i> exists, then {@code -1} is returned.
  1772      *
  1773      * @param   str         the substring to search for.
  1774      * @param   fromIndex   the index from which to start the search.
  1775      * @return  the index of the first occurrence of the specified substring,
  1776      *          starting at the specified index,
  1777      *          or {@code -1} if there is no such occurrence.
  1778      */
  1779     @JavaScriptBody(args = { "str", "fromIndex" }, body =
  1780         "return this.toString().indexOf(str.toString(), fromIndex);"
  1781     )
  1782     public native int indexOf(String str, int fromIndex);
  1783 
  1784     /**
  1785      * Returns the index within this string of the last occurrence of the
  1786      * specified substring.  The last occurrence of the empty string ""
  1787      * is considered to occur at the index value {@code this.length()}.
  1788      *
  1789      * <p>The returned index is the largest value <i>k</i> for which:
  1790      * <blockquote><pre>
  1791      * this.startsWith(str, <i>k</i>)
  1792      * </pre></blockquote>
  1793      * If no such value of <i>k</i> exists, then {@code -1} is returned.
  1794      *
  1795      * @param   str   the substring to search for.
  1796      * @return  the index of the last occurrence of the specified substring,
  1797      *          or {@code -1} if there is no such occurrence.
  1798      */
  1799     public int lastIndexOf(String str) {
  1800         return lastIndexOf(str, length());
  1801     }
  1802 
  1803     /**
  1804      * Returns the index within this string of the last occurrence of the
  1805      * specified substring, searching backward starting at the specified index.
  1806      *
  1807      * <p>The returned index is the largest value <i>k</i> for which:
  1808      * <blockquote><pre>
  1809      * <i>k</i> &lt;= fromIndex && this.startsWith(str, <i>k</i>)
  1810      * </pre></blockquote>
  1811      * If no such value of <i>k</i> exists, then {@code -1} is returned.
  1812      *
  1813      * @param   str         the substring to search for.
  1814      * @param   fromIndex   the index to start the search from.
  1815      * @return  the index of the last occurrence of the specified substring,
  1816      *          searching backward from the specified index,
  1817      *          or {@code -1} if there is no such occurrence.
  1818      */
  1819     @JavaScriptBody(args = { "s", "from" }, body = 
  1820         "return this.toString().lastIndexOf(s.toString(), from);"
  1821     )
  1822     public int lastIndexOf(String str, int fromIndex) {
  1823         return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex);
  1824     }
  1825 
  1826     /**
  1827      * Code shared by String and StringBuffer to do searches. The
  1828      * source is the character array being searched, and the target
  1829      * is the string being searched for.
  1830      *
  1831      * @param   source       the characters being searched.
  1832      * @param   sourceOffset offset of the source string.
  1833      * @param   sourceCount  count of the source string.
  1834      * @param   target       the characters being searched for.
  1835      * @param   targetOffset offset of the target string.
  1836      * @param   targetCount  count of the target string.
  1837      * @param   fromIndex    the index to begin searching from.
  1838      */
  1839     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
  1840                            char[] target, int targetOffset, int targetCount,
  1841                            int fromIndex) {
  1842         /*
  1843          * Check arguments; return immediately where possible. For
  1844          * consistency, don't check for null str.
  1845          */
  1846         int rightIndex = sourceCount - targetCount;
  1847         if (fromIndex < 0) {
  1848             return -1;
  1849         }
  1850         if (fromIndex > rightIndex) {
  1851             fromIndex = rightIndex;
  1852         }
  1853         /* Empty string always matches. */
  1854         if (targetCount == 0) {
  1855             return fromIndex;
  1856         }
  1857 
  1858         int strLastIndex = targetOffset + targetCount - 1;
  1859         char strLastChar = target[strLastIndex];
  1860         int min = sourceOffset + targetCount - 1;
  1861         int i = min + fromIndex;
  1862 
  1863     startSearchForLastChar:
  1864         while (true) {
  1865             while (i >= min && source[i] != strLastChar) {
  1866                 i--;
  1867             }
  1868             if (i < min) {
  1869                 return -1;
  1870             }
  1871             int j = i - 1;
  1872             int start = j - (targetCount - 1);
  1873             int k = strLastIndex - 1;
  1874 
  1875             while (j > start) {
  1876                 if (source[j--] != target[k--]) {
  1877                     i--;
  1878                     continue startSearchForLastChar;
  1879                 }
  1880             }
  1881             return start - sourceOffset + 1;
  1882         }
  1883     }
  1884 
  1885     /**
  1886      * Returns a new string that is a substring of this string. The
  1887      * substring begins with the character at the specified index and
  1888      * extends to the end of this string. <p>
  1889      * Examples:
  1890      * <blockquote><pre>
  1891      * "unhappy".substring(2) returns "happy"
  1892      * "Harbison".substring(3) returns "bison"
  1893      * "emptiness".substring(9) returns "" (an empty string)
  1894      * </pre></blockquote>
  1895      *
  1896      * @param      beginIndex   the beginning index, inclusive.
  1897      * @return     the specified substring.
  1898      * @exception  IndexOutOfBoundsException  if
  1899      *             <code>beginIndex</code> is negative or larger than the
  1900      *             length of this <code>String</code> object.
  1901      */
  1902     public String substring(int beginIndex) {
  1903         return substring(beginIndex, length());
  1904     }
  1905 
  1906     /**
  1907      * Returns a new string that is a substring of this string. The
  1908      * substring begins at the specified <code>beginIndex</code> and
  1909      * extends to the character at index <code>endIndex - 1</code>.
  1910      * Thus the length of the substring is <code>endIndex-beginIndex</code>.
  1911      * <p>
  1912      * Examples:
  1913      * <blockquote><pre>
  1914      * "hamburger".substring(4, 8) returns "urge"
  1915      * "smiles".substring(1, 5) returns "mile"
  1916      * </pre></blockquote>
  1917      *
  1918      * @param      beginIndex   the beginning index, inclusive.
  1919      * @param      endIndex     the ending index, exclusive.
  1920      * @return     the specified substring.
  1921      * @exception  IndexOutOfBoundsException  if the
  1922      *             <code>beginIndex</code> is negative, or
  1923      *             <code>endIndex</code> is larger than the length of
  1924      *             this <code>String</code> object, or
  1925      *             <code>beginIndex</code> is larger than
  1926      *             <code>endIndex</code>.
  1927      */
  1928     @JavaScriptBody(args = { "beginIndex", "endIndex" }, body = 
  1929         "return this.toString().substring(beginIndex, endIndex);"
  1930     )
  1931     public String substring(int beginIndex, int endIndex) {
  1932         if (beginIndex < 0) {
  1933             throw new StringIndexOutOfBoundsException(beginIndex);
  1934         }
  1935         if (endIndex > length()) {
  1936             throw new StringIndexOutOfBoundsException(endIndex);
  1937         }
  1938         if (beginIndex > endIndex) {
  1939             throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
  1940         }
  1941         return ((beginIndex == 0) && (endIndex == length())) ? this :
  1942             new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex);
  1943     }
  1944 
  1945     /**
  1946      * Returns a new character sequence that is a subsequence of this sequence.
  1947      *
  1948      * <p> An invocation of this method of the form
  1949      *
  1950      * <blockquote><pre>
  1951      * str.subSequence(begin,&nbsp;end)</pre></blockquote>
  1952      *
  1953      * behaves in exactly the same way as the invocation
  1954      *
  1955      * <blockquote><pre>
  1956      * str.substring(begin,&nbsp;end)</pre></blockquote>
  1957      *
  1958      * This method is defined so that the <tt>String</tt> class can implement
  1959      * the {@link CharSequence} interface. </p>
  1960      *
  1961      * @param      beginIndex   the begin index, inclusive.
  1962      * @param      endIndex     the end index, exclusive.
  1963      * @return     the specified subsequence.
  1964      *
  1965      * @throws  IndexOutOfBoundsException
  1966      *          if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
  1967      *          if <tt>endIndex</tt> is greater than <tt>length()</tt>,
  1968      *          or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
  1969      *
  1970      * @since 1.4
  1971      * @spec JSR-51
  1972      */
  1973     public CharSequence subSequence(int beginIndex, int endIndex) {
  1974         return this.substring(beginIndex, endIndex);
  1975     }
  1976 
  1977     /**
  1978      * Concatenates the specified string to the end of this string.
  1979      * <p>
  1980      * If the length of the argument string is <code>0</code>, then this
  1981      * <code>String</code> object is returned. Otherwise, a new
  1982      * <code>String</code> object is created, representing a character
  1983      * sequence that is the concatenation of the character sequence
  1984      * represented by this <code>String</code> object and the character
  1985      * sequence represented by the argument string.<p>
  1986      * Examples:
  1987      * <blockquote><pre>
  1988      * "cares".concat("s") returns "caress"
  1989      * "to".concat("get").concat("her") returns "together"
  1990      * </pre></blockquote>
  1991      *
  1992      * @param   str   the <code>String</code> that is concatenated to the end
  1993      *                of this <code>String</code>.
  1994      * @return  a string that represents the concatenation of this object's
  1995      *          characters followed by the string argument's characters.
  1996      */
  1997     public String concat(String str) {
  1998         int otherLen = str.length();
  1999         if (otherLen == 0) {
  2000             return this;
  2001         }
  2002         char buf[] = new char[length() + otherLen];
  2003         getChars(0, length(), buf, 0);
  2004         str.getChars(0, otherLen, buf, length());
  2005         return new String(buf, 0, length() + otherLen);
  2006     }
  2007 
  2008     /**
  2009      * Returns a new string resulting from replacing all occurrences of
  2010      * <code>oldChar</code> in this string with <code>newChar</code>.
  2011      * <p>
  2012      * If the character <code>oldChar</code> does not occur in the
  2013      * character sequence represented by this <code>String</code> object,
  2014      * then a reference to this <code>String</code> object is returned.
  2015      * Otherwise, a new <code>String</code> object is created that
  2016      * represents a character sequence identical to the character sequence
  2017      * represented by this <code>String</code> object, except that every
  2018      * occurrence of <code>oldChar</code> is replaced by an occurrence
  2019      * of <code>newChar</code>.
  2020      * <p>
  2021      * Examples:
  2022      * <blockquote><pre>
  2023      * "mesquite in your cellar".replace('e', 'o')
  2024      *         returns "mosquito in your collar"
  2025      * "the war of baronets".replace('r', 'y')
  2026      *         returns "the way of bayonets"
  2027      * "sparring with a purple porpoise".replace('p', 't')
  2028      *         returns "starring with a turtle tortoise"
  2029      * "JonL".replace('q', 'x') returns "JonL" (no change)
  2030      * </pre></blockquote>
  2031      *
  2032      * @param   oldChar   the old character.
  2033      * @param   newChar   the new character.
  2034      * @return  a string derived from this string by replacing every
  2035      *          occurrence of <code>oldChar</code> with <code>newChar</code>.
  2036      */
  2037     @JavaScriptBody(args = { "arg1", "arg2" }, body =
  2038         "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" +
  2039         "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" +
  2040         "var s = this.toString();\n" +
  2041         "for (;;) {\n" +
  2042         "  var ret = s.replace(arg1, arg2);\n" +
  2043         "  if (ret === s) {\n" +
  2044         "    return ret;\n" +
  2045         "  }\n" +
  2046         "  s = ret;\n" +
  2047         "}"
  2048     )
  2049     public String replace(char oldChar, char newChar) {
  2050         if (oldChar != newChar) {
  2051             int len = length();
  2052             int i = -1;
  2053             char[] val = toCharArray(); /* avoid getfield opcode */
  2054             int off = offset();   /* avoid getfield opcode */
  2055 
  2056             while (++i < len) {
  2057                 if (val[off + i] == oldChar) {
  2058                     break;
  2059                 }
  2060             }
  2061             if (i < len) {
  2062                 char buf[] = new char[len];
  2063                 for (int j = 0 ; j < i ; j++) {
  2064                     buf[j] = val[off+j];
  2065                 }
  2066                 while (i < len) {
  2067                     char c = val[off + i];
  2068                     buf[i] = (c == oldChar) ? newChar : c;
  2069                     i++;
  2070                 }
  2071                 return new String(buf, 0, len);
  2072             }
  2073         }
  2074         return this;
  2075     }
  2076 
  2077     /**
  2078      * Tells whether or not this string matches the given <a
  2079      * href="../util/regex/Pattern.html#sum">regular expression</a>.
  2080      *
  2081      * <p> An invocation of this method of the form
  2082      * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
  2083      * same result as the expression
  2084      *
  2085      * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
  2086      * java.util.regex.Pattern#matches(String,CharSequence)
  2087      * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
  2088      *
  2089      * @param   regex
  2090      *          the regular expression to which this string is to be matched
  2091      *
  2092      * @return  <tt>true</tt> if, and only if, this string matches the
  2093      *          given regular expression
  2094      *
  2095      * @throws  PatternSyntaxException
  2096      *          if the regular expression's syntax is invalid
  2097      *
  2098      * @see java.util.regex.Pattern
  2099      *
  2100      * @since 1.4
  2101      * @spec JSR-51
  2102      */
  2103     public boolean matches(String regex) {
  2104         try {
  2105             return matchesViaJS(regex);
  2106         } catch (Throwable t) {
  2107             // fallback to classical behavior
  2108             try {
  2109                 Method m = Class.forName("java.util.regex.Pattern").getMethod("matches", String.class, CharSequence.class);
  2110                 return (Boolean)m.invoke(null, regex, this);
  2111             } catch (InvocationTargetException ex) {
  2112                 if (ex.getTargetException() instanceof RuntimeException) {
  2113                     throw (RuntimeException)ex.getTargetException();
  2114                 }
  2115             } catch (Throwable another) {
  2116                 // will report the old one
  2117             }
  2118             throw new RuntimeException(t);
  2119         }
  2120     }
  2121     @JavaScriptBody(args = { "regex" }, body = 
  2122           "var self = this.toString();\n"
  2123         + "var re = new RegExp(regex.toString());\n"
  2124         + "var r = re.exec(self);\n"
  2125         + "return r != null && r.length > 0 && self.length == r[0].length;"
  2126     )
  2127     private boolean matchesViaJS(String regex) {
  2128         throw new UnsupportedOperationException();
  2129     }
  2130 
  2131     /**
  2132      * Returns true if and only if this string contains the specified
  2133      * sequence of char values.
  2134      *
  2135      * @param s the sequence to search for
  2136      * @return true if this string contains <code>s</code>, false otherwise
  2137      * @throws NullPointerException if <code>s</code> is <code>null</code>
  2138      * @since 1.5
  2139      */
  2140     public boolean contains(CharSequence s) {
  2141         return indexOf(s.toString()) > -1;
  2142     }
  2143 
  2144     /**
  2145      * Replaces the first substring of this string that matches the given <a
  2146      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
  2147      * given replacement.
  2148      *
  2149      * <p> An invocation of this method of the form
  2150      * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
  2151      * yields exactly the same result as the expression
  2152      *
  2153      * <blockquote><tt>
  2154      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
  2155      * compile}(</tt><i>regex</i><tt>).{@link
  2156      * java.util.regex.Pattern#matcher(java.lang.CharSequence)
  2157      * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
  2158      * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
  2159      *
  2160      *<p>
  2161      * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
  2162      * replacement string may cause the results to be different than if it were
  2163      * being treated as a literal replacement string; see
  2164      * {@link java.util.regex.Matcher#replaceFirst}.
  2165      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
  2166      * meaning of these characters, if desired.
  2167      *
  2168      * @param   regex
  2169      *          the regular expression to which this string is to be matched
  2170      * @param   replacement
  2171      *          the string to be substituted for the first match
  2172      *
  2173      * @return  The resulting <tt>String</tt>
  2174      *
  2175      * @throws  PatternSyntaxException
  2176      *          if the regular expression's syntax is invalid
  2177      *
  2178      * @see java.util.regex.Pattern
  2179      *
  2180      * @since 1.4
  2181      * @spec JSR-51
  2182      */
  2183     @JavaScriptBody(args = { "regex", "newText" }, body = 
  2184           "var self = this.toString();\n"
  2185         + "var re = new RegExp(regex.toString());\n"
  2186         + "var r = re.exec(self);\n"
  2187         + "if (r === null || r.length === 0) return this;\n"
  2188         + "var from = self.indexOf(r[0]);\n"
  2189         + "return this.substring(0, from) + newText + this.substring(from + r[0].length);\n"
  2190     )
  2191     public String replaceFirst(String regex, String replacement) {
  2192         throw new UnsupportedOperationException();
  2193     }
  2194 
  2195     /**
  2196      * Replaces each substring of this string that matches the given <a
  2197      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
  2198      * given replacement.
  2199      *
  2200      * <p> An invocation of this method of the form
  2201      * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
  2202      * yields exactly the same result as the expression
  2203      *
  2204      * <blockquote><tt>
  2205      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
  2206      * compile}(</tt><i>regex</i><tt>).{@link
  2207      * java.util.regex.Pattern#matcher(java.lang.CharSequence)
  2208      * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
  2209      * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
  2210      *
  2211      *<p>
  2212      * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
  2213      * replacement string may cause the results to be different than if it were
  2214      * being treated as a literal replacement string; see
  2215      * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
  2216      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
  2217      * meaning of these characters, if desired.
  2218      *
  2219      * @param   regex
  2220      *          the regular expression to which this string is to be matched
  2221      * @param   replacement
  2222      *          the string to be substituted for each match
  2223      *
  2224      * @return  The resulting <tt>String</tt>
  2225      *
  2226      * @throws  PatternSyntaxException
  2227      *          if the regular expression's syntax is invalid
  2228      *
  2229      * @see java.util.regex.Pattern
  2230      *
  2231      * @since 1.4
  2232      * @spec JSR-51
  2233      */
  2234     public String replaceAll(String regex, String replacement) {
  2235         String p = this;
  2236         for (;;) {
  2237             String n = p.replaceFirst(regex, replacement);
  2238             if (n == p) {
  2239                 return n;
  2240             }
  2241             p = n;
  2242         }
  2243     }
  2244 
  2245     /**
  2246      * Replaces each substring of this string that matches the literal target
  2247      * sequence with the specified literal replacement sequence. The
  2248      * replacement proceeds from the beginning of the string to the end, for
  2249      * example, replacing "aa" with "b" in the string "aaa" will result in
  2250      * "ba" rather than "ab".
  2251      *
  2252      * @param  target The sequence of char values to be replaced
  2253      * @param  replacement The replacement sequence of char values
  2254      * @return  The resulting string
  2255      * @throws NullPointerException if <code>target</code> or
  2256      *         <code>replacement</code> is <code>null</code>.
  2257      * @since 1.5
  2258      */
  2259     @JavaScriptBody(args = { "target", "replacement" }, body = 
  2260           "var s = this.toString();\n"
  2261         + "target = target.toString();\n"
  2262         + "replacement = replacement.toString();\n"
  2263         + "var pos = 0;\n"
  2264         + "for (;;) {\n"
  2265         + "  var indx = s.indexOf(target, pos);\n"
  2266         + "  if (indx === -1) {\n"
  2267         + "    return s;\n"
  2268         + "  }\n"
  2269         + "  pos = indx + replacement.length;\n"
  2270         + "  s = s.substring(0, indx) + replacement + s.substring(indx + target.length);\n"
  2271         + "}"
  2272     )
  2273     public native String replace(CharSequence target, CharSequence replacement);
  2274 
  2275     /**
  2276      * Splits this string around matches of the given
  2277      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
  2278      *
  2279      * <p> The array returned by this method contains each substring of this
  2280      * string that is terminated by another substring that matches the given
  2281      * expression or is terminated by the end of the string.  The substrings in
  2282      * the array are in the order in which they occur in this string.  If the
  2283      * expression does not match any part of the input then the resulting array
  2284      * has just one element, namely this string.
  2285      *
  2286      * <p> The <tt>limit</tt> parameter controls the number of times the
  2287      * pattern is applied and therefore affects the length of the resulting
  2288      * array.  If the limit <i>n</i> is greater than zero then the pattern
  2289      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
  2290      * length will be no greater than <i>n</i>, and the array's last entry
  2291      * will contain all input beyond the last matched delimiter.  If <i>n</i>
  2292      * is non-positive then the pattern will be applied as many times as
  2293      * possible and the array can have any length.  If <i>n</i> is zero then
  2294      * the pattern will be applied as many times as possible, the array can
  2295      * have any length, and trailing empty strings will be discarded.
  2296      *
  2297      * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
  2298      * following results with these parameters:
  2299      *
  2300      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
  2301      * <tr>
  2302      *     <th>Regex</th>
  2303      *     <th>Limit</th>
  2304      *     <th>Result</th>
  2305      * </tr>
  2306      * <tr><td align=center>:</td>
  2307      *     <td align=center>2</td>
  2308      *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
  2309      * <tr><td align=center>:</td>
  2310      *     <td align=center>5</td>
  2311      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  2312      * <tr><td align=center>:</td>
  2313      *     <td align=center>-2</td>
  2314      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  2315      * <tr><td align=center>o</td>
  2316      *     <td align=center>5</td>
  2317      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  2318      * <tr><td align=center>o</td>
  2319      *     <td align=center>-2</td>
  2320      *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  2321      * <tr><td align=center>o</td>
  2322      *     <td align=center>0</td>
  2323      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  2324      * </table></blockquote>
  2325      *
  2326      * <p> An invocation of this method of the form
  2327      * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
  2328      * yields the same result as the expression
  2329      *
  2330      * <blockquote>
  2331      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
  2332      * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
  2333      * java.util.regex.Pattern#split(java.lang.CharSequence,int)
  2334      * split}<tt>(</tt><i>str</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
  2335      * </blockquote>
  2336      *
  2337      *
  2338      * @param  regex
  2339      *         the delimiting regular expression
  2340      *
  2341      * @param  limit
  2342      *         the result threshold, as described above
  2343      *
  2344      * @return  the array of strings computed by splitting this string
  2345      *          around matches of the given regular expression
  2346      *
  2347      * @throws  PatternSyntaxException
  2348      *          if the regular expression's syntax is invalid
  2349      *
  2350      * @see java.util.regex.Pattern
  2351      *
  2352      * @since 1.4
  2353      * @spec JSR-51
  2354      */
  2355     public String[] split(String regex, int limit) {
  2356         if (limit <= 0) {
  2357             Object[] arr = splitImpl(this, regex, Integer.MAX_VALUE);
  2358             int to = arr.length;
  2359             if (limit == 0 && to > 0) {
  2360                 while (to > 0 && ((String)arr[--to]).isEmpty()) {
  2361                 }
  2362                 to++;
  2363             }
  2364             String[] ret = new String[to];
  2365             System.arraycopy(arr, 0, ret, 0, to);
  2366             return ret;
  2367         } else {
  2368             Object[] arr = splitImpl(this, regex, limit);
  2369             String[] ret = new String[arr.length];
  2370             int pos = 0;
  2371             for (int i = 0; i < arr.length; i++) {
  2372                 final String s = (String)arr[i];
  2373                 ret[i] = s;
  2374                 pos = indexOf(s, pos) + s.length();
  2375             }
  2376             ret[arr.length - 1] += substring(pos);
  2377             return ret;
  2378         }
  2379     }
  2380     
  2381     @JavaScriptBody(args = { "str", "regex", "limit"}, body = 
  2382         "return str.split(new RegExp(regex), limit);"
  2383     )
  2384     private static native Object[] splitImpl(String str, String regex, int limit);
  2385 
  2386     /**
  2387      * Splits this string around matches of the given <a
  2388      * href="../util/regex/Pattern.html#sum">regular expression</a>.
  2389      *
  2390      * <p> This method works as if by invoking the two-argument {@link
  2391      * #split(String, int) split} method with the given expression and a limit
  2392      * argument of zero.  Trailing empty strings are therefore not included in
  2393      * the resulting array.
  2394      *
  2395      * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
  2396      * results with these expressions:
  2397      *
  2398      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
  2399      * <tr>
  2400      *  <th>Regex</th>
  2401      *  <th>Result</th>
  2402      * </tr>
  2403      * <tr><td align=center>:</td>
  2404      *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  2405      * <tr><td align=center>o</td>
  2406      *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  2407      * </table></blockquote>
  2408      *
  2409      *
  2410      * @param  regex
  2411      *         the delimiting regular expression
  2412      *
  2413      * @return  the array of strings computed by splitting this string
  2414      *          around matches of the given regular expression
  2415      *
  2416      * @throws  PatternSyntaxException
  2417      *          if the regular expression's syntax is invalid
  2418      *
  2419      * @see java.util.regex.Pattern
  2420      *
  2421      * @since 1.4
  2422      * @spec JSR-51
  2423      */
  2424     public String[] split(String regex) {
  2425         return split(regex, 0);
  2426     }
  2427 
  2428     /**
  2429      * Converts all of the characters in this <code>String</code> to lower
  2430      * case using the rules of the given <code>Locale</code>.  Case mapping is based
  2431      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
  2432      * class. Since case mappings are not always 1:1 char mappings, the resulting
  2433      * <code>String</code> may be a different length than the original <code>String</code>.
  2434      * <p>
  2435      * Examples of lowercase  mappings are in the following table:
  2436      * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
  2437      * <tr>
  2438      *   <th>Language Code of Locale</th>
  2439      *   <th>Upper Case</th>
  2440      *   <th>Lower Case</th>
  2441      *   <th>Description</th>
  2442      * </tr>
  2443      * <tr>
  2444      *   <td>tr (Turkish)</td>
  2445      *   <td>&#92;u0130</td>
  2446      *   <td>&#92;u0069</td>
  2447      *   <td>capital letter I with dot above -&gt; small letter i</td>
  2448      * </tr>
  2449      * <tr>
  2450      *   <td>tr (Turkish)</td>
  2451      *   <td>&#92;u0049</td>
  2452      *   <td>&#92;u0131</td>
  2453      *   <td>capital letter I -&gt; small letter dotless i </td>
  2454      * </tr>
  2455      * <tr>
  2456      *   <td>(all)</td>
  2457      *   <td>French Fries</td>
  2458      *   <td>french fries</td>
  2459      *   <td>lowercased all chars in String</td>
  2460      * </tr>
  2461      * <tr>
  2462      *   <td>(all)</td>
  2463      *   <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
  2464      *       <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
  2465      *       <img src="doc-files/capsigma.gif" alt="capsigma"></td>
  2466      *   <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
  2467      *       <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
  2468      *       <img src="doc-files/sigma1.gif" alt="sigma"></td>
  2469      *   <td>lowercased all chars in String</td>
  2470      * </tr>
  2471      * </table>
  2472      *
  2473      * @param locale use the case transformation rules for this locale
  2474      * @return the <code>String</code>, converted to lowercase.
  2475      * @see     java.lang.String#toLowerCase()
  2476      * @see     java.lang.String#toUpperCase()
  2477      * @see     java.lang.String#toUpperCase(Locale)
  2478      * @since   1.1
  2479      */
  2480     public String toLowerCase(java.util.Locale locale) {
  2481         return toLowerCase();
  2482     }
  2483 //        if (locale == null) {
  2484 //            throw new NullPointerException();
  2485 //        }
  2486 //
  2487 //        int     firstUpper;
  2488 //
  2489 //        /* Now check if there are any characters that need to be changed. */
  2490 //        scan: {
  2491 //            for (firstUpper = 0 ; firstUpper < count; ) {
  2492 //                char c = value[offset+firstUpper];
  2493 //                if ((c >= Character.MIN_HIGH_SURROGATE) &&
  2494 //                    (c <= Character.MAX_HIGH_SURROGATE)) {
  2495 //                    int supplChar = codePointAt(firstUpper);
  2496 //                    if (supplChar != Character.toLowerCase(supplChar)) {
  2497 //                        break scan;
  2498 //                    }
  2499 //                    firstUpper += Character.charCount(supplChar);
  2500 //                } else {
  2501 //                    if (c != Character.toLowerCase(c)) {
  2502 //                        break scan;
  2503 //                    }
  2504 //                    firstUpper++;
  2505 //                }
  2506 //            }
  2507 //            return this;
  2508 //        }
  2509 //
  2510 //        char[]  result = new char[count];
  2511 //        int     resultOffset = 0;  /* result may grow, so i+resultOffset
  2512 //                                    * is the write location in result */
  2513 //
  2514 //        /* Just copy the first few lowerCase characters. */
  2515 //        System.arraycopy(value, offset, result, 0, firstUpper);
  2516 //
  2517 //        String lang = locale.getLanguage();
  2518 //        boolean localeDependent =
  2519 //            (lang == "tr" || lang == "az" || lang == "lt");
  2520 //        char[] lowerCharArray;
  2521 //        int lowerChar;
  2522 //        int srcChar;
  2523 //        int srcCount;
  2524 //        for (int i = firstUpper; i < count; i += srcCount) {
  2525 //            srcChar = (int)value[offset+i];
  2526 //            if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
  2527 //                (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
  2528 //                srcChar = codePointAt(i);
  2529 //                srcCount = Character.charCount(srcChar);
  2530 //            } else {
  2531 //                srcCount = 1;
  2532 //            }
  2533 //            if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
  2534 //                lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
  2535 //            } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
  2536 //                lowerChar = Character.ERROR;
  2537 //            } else {
  2538 //                lowerChar = Character.toLowerCase(srcChar);
  2539 //            }
  2540 //            if ((lowerChar == Character.ERROR) ||
  2541 //                (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
  2542 //                if (lowerChar == Character.ERROR) {
  2543 //                     if (!localeDependent && srcChar == '\u0130') {
  2544 //                         lowerCharArray =
  2545 //                             ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
  2546 //                     } else {
  2547 //                        lowerCharArray =
  2548 //                            ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
  2549 //                     }
  2550 //                } else if (srcCount == 2) {
  2551 //                    resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
  2552 //                    continue;
  2553 //                } else {
  2554 //                    lowerCharArray = Character.toChars(lowerChar);
  2555 //                }
  2556 //
  2557 //                /* Grow result if needed */
  2558 //                int mapLen = lowerCharArray.length;
  2559 //                if (mapLen > srcCount) {
  2560 //                    char[] result2 = new char[result.length + mapLen - srcCount];
  2561 //                    System.arraycopy(result, 0, result2, 0,
  2562 //                        i + resultOffset);
  2563 //                    result = result2;
  2564 //                }
  2565 //                for (int x=0; x<mapLen; ++x) {
  2566 //                    result[i+resultOffset+x] = lowerCharArray[x];
  2567 //                }
  2568 //                resultOffset += (mapLen - srcCount);
  2569 //            } else {
  2570 //                result[i+resultOffset] = (char)lowerChar;
  2571 //            }
  2572 //        }
  2573 //        return new String(0, count+resultOffset, result);
  2574 //    }
  2575 
  2576     /**
  2577      * Converts all of the characters in this <code>String</code> to lower
  2578      * case using the rules of the default locale. This is equivalent to calling
  2579      * <code>toLowerCase(Locale.getDefault())</code>.
  2580      * <p>
  2581      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
  2582      * results if used for strings that are intended to be interpreted locale
  2583      * independently.
  2584      * Examples are programming language identifiers, protocol keys, and HTML
  2585      * tags.
  2586      * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
  2587      * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
  2588      * LATIN SMALL LETTER DOTLESS I character.
  2589      * To obtain correct results for locale insensitive strings, use
  2590      * <code>toLowerCase(Locale.ENGLISH)</code>.
  2591      * <p>
  2592      * @return  the <code>String</code>, converted to lowercase.
  2593      * @see     java.lang.String#toLowerCase(Locale)
  2594      */
  2595     @JavaScriptBody(args = {}, body = "return this.toLowerCase();")
  2596     public String toLowerCase() {
  2597         return null;
  2598     }
  2599 
  2600     /**
  2601      * Converts all of the characters in this <code>String</code> to upper
  2602      * case using the rules of the given <code>Locale</code>. Case mapping is based
  2603      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
  2604      * class. Since case mappings are not always 1:1 char mappings, the resulting
  2605      * <code>String</code> may be a different length than the original <code>String</code>.
  2606      * <p>
  2607      * Examples of locale-sensitive and 1:M case mappings are in the following table.
  2608      * <p>
  2609      * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
  2610      * <tr>
  2611      *   <th>Language Code of Locale</th>
  2612      *   <th>Lower Case</th>
  2613      *   <th>Upper Case</th>
  2614      *   <th>Description</th>
  2615      * </tr>
  2616      * <tr>
  2617      *   <td>tr (Turkish)</td>
  2618      *   <td>&#92;u0069</td>
  2619      *   <td>&#92;u0130</td>
  2620      *   <td>small letter i -&gt; capital letter I with dot above</td>
  2621      * </tr>
  2622      * <tr>
  2623      *   <td>tr (Turkish)</td>
  2624      *   <td>&#92;u0131</td>
  2625      *   <td>&#92;u0049</td>
  2626      *   <td>small letter dotless i -&gt; capital letter I</td>
  2627      * </tr>
  2628      * <tr>
  2629      *   <td>(all)</td>
  2630      *   <td>&#92;u00df</td>
  2631      *   <td>&#92;u0053 &#92;u0053</td>
  2632      *   <td>small letter sharp s -&gt; two letters: SS</td>
  2633      * </tr>
  2634      * <tr>
  2635      *   <td>(all)</td>
  2636      *   <td>Fahrvergn&uuml;gen</td>
  2637      *   <td>FAHRVERGN&Uuml;GEN</td>
  2638      *   <td></td>
  2639      * </tr>
  2640      * </table>
  2641      * @param locale use the case transformation rules for this locale
  2642      * @return the <code>String</code>, converted to uppercase.
  2643      * @see     java.lang.String#toUpperCase()
  2644      * @see     java.lang.String#toLowerCase()
  2645      * @see     java.lang.String#toLowerCase(Locale)
  2646      * @since   1.1
  2647      */
  2648     public String toUpperCase(Locale locale) {
  2649         return toUpperCase();
  2650     }
  2651     /* not for javascript 
  2652         if (locale == null) {
  2653             throw new NullPointerException();
  2654         }
  2655 
  2656         int     firstLower;
  2657 
  2658         // Now check if there are any characters that need to be changed. 
  2659         scan: {
  2660             for (firstLower = 0 ; firstLower < count; ) {
  2661                 int c = (int)value[offset+firstLower];
  2662                 int srcCount;
  2663                 if ((c >= Character.MIN_HIGH_SURROGATE) &&
  2664                     (c <= Character.MAX_HIGH_SURROGATE)) {
  2665                     c = codePointAt(firstLower);
  2666                     srcCount = Character.charCount(c);
  2667                 } else {
  2668                     srcCount = 1;
  2669                 }
  2670                 int upperCaseChar = Character.toUpperCaseEx(c);
  2671                 if ((upperCaseChar == Character.ERROR) ||
  2672                     (c != upperCaseChar)) {
  2673                     break scan;
  2674                 }
  2675                 firstLower += srcCount;
  2676             }
  2677             return this;
  2678         }
  2679 
  2680         char[]  result       = new char[count]; /* may grow *
  2681         int     resultOffset = 0;  /* result may grow, so i+resultOffset
  2682                                     * is the write location in result *
  2683 
  2684         /* Just copy the first few upperCase characters. *
  2685         System.arraycopy(value, offset, result, 0, firstLower);
  2686 
  2687         String lang = locale.getLanguage();
  2688         boolean localeDependent =
  2689             (lang == "tr" || lang == "az" || lang == "lt");
  2690         char[] upperCharArray;
  2691         int upperChar;
  2692         int srcChar;
  2693         int srcCount;
  2694         for (int i = firstLower; i < count; i += srcCount) {
  2695             srcChar = (int)value[offset+i];
  2696             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
  2697                 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
  2698                 srcChar = codePointAt(i);
  2699                 srcCount = Character.charCount(srcChar);
  2700             } else {
  2701                 srcCount = 1;
  2702             }
  2703             if (localeDependent) {
  2704                 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
  2705             } else {
  2706                 upperChar = Character.toUpperCaseEx(srcChar);
  2707             }
  2708             if ((upperChar == Character.ERROR) ||
  2709                 (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
  2710                 if (upperChar == Character.ERROR) {
  2711                     if (localeDependent) {
  2712                         upperCharArray =
  2713                             ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
  2714                     } else {
  2715                         upperCharArray = Character.toUpperCaseCharArray(srcChar);
  2716                     }
  2717                 } else if (srcCount == 2) {
  2718                     resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
  2719                     continue;
  2720                 } else {
  2721                     upperCharArray = Character.toChars(upperChar);
  2722                 }
  2723 
  2724                 /* Grow result if needed *
  2725                 int mapLen = upperCharArray.length;
  2726                 if (mapLen > srcCount) {
  2727                     char[] result2 = new char[result.length + mapLen - srcCount];
  2728                     System.arraycopy(result, 0, result2, 0,
  2729                         i + resultOffset);
  2730                     result = result2;
  2731                 }
  2732                 for (int x=0; x<mapLen; ++x) {
  2733                     result[i+resultOffset+x] = upperCharArray[x];
  2734                 }
  2735                 resultOffset += (mapLen - srcCount);
  2736             } else {
  2737                 result[i+resultOffset] = (char)upperChar;
  2738             }
  2739         }
  2740         return new String(0, count+resultOffset, result);
  2741     }
  2742     */
  2743 
  2744     /**
  2745      * Converts all of the characters in this <code>String</code> to upper
  2746      * case using the rules of the default locale. This method is equivalent to
  2747      * <code>toUpperCase(Locale.getDefault())</code>.
  2748      * <p>
  2749      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
  2750      * results if used for strings that are intended to be interpreted locale
  2751      * independently.
  2752      * Examples are programming language identifiers, protocol keys, and HTML
  2753      * tags.
  2754      * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
  2755      * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
  2756      * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
  2757      * To obtain correct results for locale insensitive strings, use
  2758      * <code>toUpperCase(Locale.ENGLISH)</code>.
  2759      * <p>
  2760      * @return  the <code>String</code>, converted to uppercase.
  2761      * @see     java.lang.String#toUpperCase(Locale)
  2762      */
  2763     @JavaScriptBody(args = {}, body = "return this.toUpperCase();")
  2764     public String toUpperCase() {
  2765         return null;
  2766     }
  2767 
  2768     /**
  2769      * Returns a copy of the string, with leading and trailing whitespace
  2770      * omitted.
  2771      * <p>
  2772      * If this <code>String</code> object represents an empty character
  2773      * sequence, or the first and last characters of character sequence
  2774      * represented by this <code>String</code> object both have codes
  2775      * greater than <code>'&#92;u0020'</code> (the space character), then a
  2776      * reference to this <code>String</code> object is returned.
  2777      * <p>
  2778      * Otherwise, if there is no character with a code greater than
  2779      * <code>'&#92;u0020'</code> in the string, then a new
  2780      * <code>String</code> object representing an empty string is created
  2781      * and returned.
  2782      * <p>
  2783      * Otherwise, let <i>k</i> be the index of the first character in the
  2784      * string whose code is greater than <code>'&#92;u0020'</code>, and let
  2785      * <i>m</i> be the index of the last character in the string whose code
  2786      * is greater than <code>'&#92;u0020'</code>. A new <code>String</code>
  2787      * object is created, representing the substring of this string that
  2788      * begins with the character at index <i>k</i> and ends with the
  2789      * character at index <i>m</i>-that is, the result of
  2790      * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
  2791      * <p>
  2792      * This method may be used to trim whitespace (as defined above) from
  2793      * the beginning and end of a string.
  2794      *
  2795      * @return  A copy of this string with leading and trailing white
  2796      *          space removed, or this string if it has no leading or
  2797      *          trailing white space.
  2798      */
  2799     public String trim() {
  2800         int len = length();
  2801         int st = 0;
  2802         int off = offset();      /* avoid getfield opcode */
  2803         char[] val = toCharArray();    /* avoid getfield opcode */
  2804 
  2805         while ((st < len) && (val[off + st] <= ' ')) {
  2806             st++;
  2807         }
  2808         while ((st < len) && (val[off + len - 1] <= ' ')) {
  2809             len--;
  2810         }
  2811         return ((st > 0) || (len < length())) ? substring(st, len) : this;
  2812     }
  2813 
  2814     /**
  2815      * This object (which is already a string!) is itself returned.
  2816      *
  2817      * @return  the string itself.
  2818      */
  2819     @JavaScriptBody(args = {}, body = "return this.toString();")
  2820     public String toString() {
  2821         return this;
  2822     }
  2823 
  2824     /**
  2825      * Converts this string to a new character array.
  2826      *
  2827      * @return  a newly allocated character array whose length is the length
  2828      *          of this string and whose contents are initialized to contain
  2829      *          the character sequence represented by this string.
  2830      */
  2831     public char[] toCharArray() {
  2832         char result[] = new char[length()];
  2833         getChars(0, length(), result, 0);
  2834         return result;
  2835     }
  2836 
  2837     /**
  2838      * Returns a formatted string using the specified format string and
  2839      * arguments.
  2840      *
  2841      * <p> The locale always used is the one returned by {@link
  2842      * java.util.Locale#getDefault() Locale.getDefault()}.
  2843      *
  2844      * @param  format
  2845      *         A <a href="../util/Formatter.html#syntax">format string</a>
  2846      *
  2847      * @param  args
  2848      *         Arguments referenced by the format specifiers in the format
  2849      *         string.  If there are more arguments than format specifiers, the
  2850      *         extra arguments are ignored.  The number of arguments is
  2851      *         variable and may be zero.  The maximum number of arguments is
  2852      *         limited by the maximum dimension of a Java array as defined by
  2853      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
  2854      *         The behaviour on a
  2855      *         <tt>null</tt> argument depends on the <a
  2856      *         href="../util/Formatter.html#syntax">conversion</a>.
  2857      *
  2858      * @throws  IllegalFormatException
  2859      *          If a format string contains an illegal syntax, a format
  2860      *          specifier that is incompatible with the given arguments,
  2861      *          insufficient arguments given the format string, or other
  2862      *          illegal conditions.  For specification of all possible
  2863      *          formatting errors, see the <a
  2864      *          href="../util/Formatter.html#detail">Details</a> section of the
  2865      *          formatter class specification.
  2866      *
  2867      * @throws  NullPointerException
  2868      *          If the <tt>format</tt> is <tt>null</tt>
  2869      *
  2870      * @return  A formatted string
  2871      *
  2872      * @see  java.util.Formatter
  2873      * @since  1.5
  2874      */
  2875     public static String format(String format, Object ... args) {
  2876         return format((Locale)null, format, args);
  2877     }
  2878 
  2879     /**
  2880      * Returns a formatted string using the specified locale, format string,
  2881      * and arguments.
  2882      *
  2883      * @param  l
  2884      *         The {@linkplain java.util.Locale locale} to apply during
  2885      *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
  2886      *         is applied.
  2887      *
  2888      * @param  format
  2889      *         A <a href="../util/Formatter.html#syntax">format string</a>
  2890      *
  2891      * @param  args
  2892      *         Arguments referenced by the format specifiers in the format
  2893      *         string.  If there are more arguments than format specifiers, the
  2894      *         extra arguments are ignored.  The number of arguments is
  2895      *         variable and may be zero.  The maximum number of arguments is
  2896      *         limited by the maximum dimension of a Java array as defined by
  2897      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
  2898      *         The behaviour on a
  2899      *         <tt>null</tt> argument depends on the <a
  2900      *         href="../util/Formatter.html#syntax">conversion</a>.
  2901      *
  2902      * @throws  IllegalFormatException
  2903      *          If a format string contains an illegal syntax, a format
  2904      *          specifier that is incompatible with the given arguments,
  2905      *          insufficient arguments given the format string, or other
  2906      *          illegal conditions.  For specification of all possible
  2907      *          formatting errors, see the <a
  2908      *          href="../util/Formatter.html#detail">Details</a> section of the
  2909      *          formatter class specification
  2910      *
  2911      * @throws  NullPointerException
  2912      *          If the <tt>format</tt> is <tt>null</tt>
  2913      *
  2914      * @return  A formatted string
  2915      *
  2916      * @see  java.util.Formatter
  2917      * @since  1.5
  2918      */
  2919     public static String format(Locale l, String format, Object ... args) {
  2920         String p = format;
  2921         for (int i = 0; i < args.length; i++) {
  2922             String v = args[i] == null ? "null" : args[i].toString();
  2923             p = p.replaceFirst("%s", v);
  2924         }
  2925         return p;
  2926         // return new Formatter(l).format(format, args).toString();
  2927     }
  2928 
  2929     /**
  2930      * Returns the string representation of the <code>Object</code> argument.
  2931      *
  2932      * @param   obj   an <code>Object</code>.
  2933      * @return  if the argument is <code>null</code>, then a string equal to
  2934      *          <code>"null"</code>; otherwise, the value of
  2935      *          <code>obj.toString()</code> is returned.
  2936      * @see     java.lang.Object#toString()
  2937      */
  2938     public static String valueOf(Object obj) {
  2939         return (obj == null) ? "null" : obj.toString();
  2940     }
  2941 
  2942     /**
  2943      * Returns the string representation of the <code>char</code> array
  2944      * argument. The contents of the character array are copied; subsequent
  2945      * modification of the character array does not affect the newly
  2946      * created string.
  2947      *
  2948      * @param   data   a <code>char</code> array.
  2949      * @return  a newly allocated string representing the same sequence of
  2950      *          characters contained in the character array argument.
  2951      */
  2952     public static String valueOf(char data[]) {
  2953         return new String(data);
  2954     }
  2955 
  2956     /**
  2957      * Returns the string representation of a specific subarray of the
  2958      * <code>char</code> array argument.
  2959      * <p>
  2960      * The <code>offset</code> argument is the index of the first
  2961      * character of the subarray. The <code>count</code> argument
  2962      * specifies the length of the subarray. The contents of the subarray
  2963      * are copied; subsequent modification of the character array does not
  2964      * affect the newly created string.
  2965      *
  2966      * @param   data     the character array.
  2967      * @param   offset   the initial offset into the value of the
  2968      *                  <code>String</code>.
  2969      * @param   count    the length of the value of the <code>String</code>.
  2970      * @return  a string representing the sequence of characters contained
  2971      *          in the subarray of the character array argument.
  2972      * @exception IndexOutOfBoundsException if <code>offset</code> is
  2973      *          negative, or <code>count</code> is negative, or
  2974      *          <code>offset+count</code> is larger than
  2975      *          <code>data.length</code>.
  2976      */
  2977     public static String valueOf(char data[], int offset, int count) {
  2978         return new String(data, offset, count);
  2979     }
  2980 
  2981     /**
  2982      * Returns a String that represents the character sequence in the
  2983      * array specified.
  2984      *
  2985      * @param   data     the character array.
  2986      * @param   offset   initial offset of the subarray.
  2987      * @param   count    length of the subarray.
  2988      * @return  a <code>String</code> that contains the characters of the
  2989      *          specified subarray of the character array.
  2990      */
  2991     public static String copyValueOf(char data[], int offset, int count) {
  2992         // All public String constructors now copy the data.
  2993         return new String(data, offset, count);
  2994     }
  2995 
  2996     /**
  2997      * Returns a String that represents the character sequence in the
  2998      * array specified.
  2999      *
  3000      * @param   data   the character array.
  3001      * @return  a <code>String</code> that contains the characters of the
  3002      *          character array.
  3003      */
  3004     public static String copyValueOf(char data[]) {
  3005         return copyValueOf(data, 0, data.length);
  3006     }
  3007 
  3008     /**
  3009      * Returns the string representation of the <code>boolean</code> argument.
  3010      *
  3011      * @param   b   a <code>boolean</code>.
  3012      * @return  if the argument is <code>true</code>, a string equal to
  3013      *          <code>"true"</code> is returned; otherwise, a string equal to
  3014      *          <code>"false"</code> is returned.
  3015      */
  3016     public static String valueOf(boolean b) {
  3017         return b ? "true" : "false";
  3018     }
  3019 
  3020     /**
  3021      * Returns the string representation of the <code>char</code>
  3022      * argument.
  3023      *
  3024      * @param   c   a <code>char</code>.
  3025      * @return  a string of length <code>1</code> containing
  3026      *          as its single character the argument <code>c</code>.
  3027      */
  3028     public static String valueOf(char c) {
  3029         char data[] = {c};
  3030         return new String(data, 0, 1);
  3031     }
  3032 
  3033     /**
  3034      * Returns the string representation of the <code>int</code> argument.
  3035      * <p>
  3036      * The representation is exactly the one returned by the
  3037      * <code>Integer.toString</code> method of one argument.
  3038      *
  3039      * @param   i   an <code>int</code>.
  3040      * @return  a string representation of the <code>int</code> argument.
  3041      * @see     java.lang.Integer#toString(int, int)
  3042      */
  3043     public static String valueOf(int i) {
  3044         return Integer.toString(i);
  3045     }
  3046 
  3047     /**
  3048      * Returns the string representation of the <code>long</code> argument.
  3049      * <p>
  3050      * The representation is exactly the one returned by the
  3051      * <code>Long.toString</code> method of one argument.
  3052      *
  3053      * @param   l   a <code>long</code>.
  3054      * @return  a string representation of the <code>long</code> argument.
  3055      * @see     java.lang.Long#toString(long)
  3056      */
  3057     public static String valueOf(long l) {
  3058         return Long.toString(l);
  3059     }
  3060 
  3061     /**
  3062      * Returns the string representation of the <code>float</code> argument.
  3063      * <p>
  3064      * The representation is exactly the one returned by the
  3065      * <code>Float.toString</code> method of one argument.
  3066      *
  3067      * @param   f   a <code>float</code>.
  3068      * @return  a string representation of the <code>float</code> argument.
  3069      * @see     java.lang.Float#toString(float)
  3070      */
  3071     public static String valueOf(float f) {
  3072         return Float.toString(f);
  3073     }
  3074 
  3075     /**
  3076      * Returns the string representation of the <code>double</code> argument.
  3077      * <p>
  3078      * The representation is exactly the one returned by the
  3079      * <code>Double.toString</code> method of one argument.
  3080      *
  3081      * @param   d   a <code>double</code>.
  3082      * @return  a  string representation of the <code>double</code> argument.
  3083      * @see     java.lang.Double#toString(double)
  3084      */
  3085     public static String valueOf(double d) {
  3086         return Double.toString(d);
  3087     }
  3088 
  3089     /**
  3090      * Returns a canonical representation for the string object.
  3091      * <p>
  3092      * A pool of strings, initially empty, is maintained privately by the
  3093      * class <code>String</code>.
  3094      * <p>
  3095      * When the intern method is invoked, if the pool already contains a
  3096      * string equal to this <code>String</code> object as determined by
  3097      * the {@link #equals(Object)} method, then the string from the pool is
  3098      * returned. Otherwise, this <code>String</code> object is added to the
  3099      * pool and a reference to this <code>String</code> object is returned.
  3100      * <p>
  3101      * It follows that for any two strings <code>s</code> and <code>t</code>,
  3102      * <code>s.intern()&nbsp;==&nbsp;t.intern()</code> is <code>true</code>
  3103      * if and only if <code>s.equals(t)</code> is <code>true</code>.
  3104      * <p>
  3105      * All literal strings and string-valued constant expressions are
  3106      * interned. String literals are defined in section 3.10.5 of the
  3107      * <cite>The Java&trade; Language Specification</cite>.
  3108      *
  3109      * @return  a string that has the same contents as this string, but is
  3110      *          guaranteed to be from a pool of unique strings.
  3111      */
  3112     @JavaScriptBody(args = {}, body = 
  3113         "var s = this.toString().toString();\n" +
  3114         "var i = String.intern || (String.intern = {})\n" + 
  3115         "if (!i[s]) {\n" +
  3116         "  i[s] = s;\n" +
  3117         "}\n" +
  3118         "return i[s];"
  3119     )
  3120     public native String intern();
  3121     
  3122     
  3123     private static <T> T checkUTF8(T data, String charsetName)
  3124         throws UnsupportedEncodingException {
  3125         if (charsetName == null) {
  3126             throw new NullPointerException("charsetName");
  3127         }
  3128         if (!charsetName.equalsIgnoreCase("UTF-8")
  3129             && !charsetName.equalsIgnoreCase("UTF8")) {
  3130             throw new UnsupportedEncodingException(charsetName);
  3131         }
  3132         return data;
  3133     }
  3134     
  3135     private static int nextChar(byte[] arr, int[] index) throws IndexOutOfBoundsException {
  3136         int c = arr[index[0]++] & 0xff;
  3137         switch (c >> 4) {
  3138             case 0:
  3139             case 1:
  3140             case 2:
  3141             case 3:
  3142             case 4:
  3143             case 5:
  3144             case 6:
  3145             case 7:
  3146                 /* 0xxxxxxx*/
  3147                 return c;
  3148             case 12:
  3149             case 13: {
  3150                 /* 110x xxxx   10xx xxxx*/
  3151                 int char2 = (int) arr[index[0]++];
  3152                 if ((char2 & 0xC0) != 0x80) {
  3153                     throw new IndexOutOfBoundsException("malformed input");
  3154                 }
  3155                 return (((c & 0x1F) << 6) | (char2 & 0x3F));
  3156             }
  3157             case 14: {
  3158                 /* 1110 xxxx  10xx xxxx  10xx xxxx */
  3159                 int char2 = arr[index[0]++];
  3160                 int char3 = arr[index[0]++];
  3161                 if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
  3162                     throw new IndexOutOfBoundsException("malformed input");
  3163                 }
  3164                 return (((c & 0x0F) << 12)
  3165                     | ((char2 & 0x3F) << 6)
  3166                     | ((char3 & 0x3F) << 0));
  3167             }
  3168             default:
  3169                 /* 10xx xxxx,  1111 xxxx */
  3170                 throw new IndexOutOfBoundsException("malformed input");
  3171         }
  3172         
  3173     }
  3174 }