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