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