• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 import dalvik.annotation.optimization.FastNative;
30 import java.io.ObjectStreamField;
31 import java.io.UnsupportedEncodingException;
32 import java.nio.charset.Charset;
33 import java.nio.ByteBuffer;
34 import java.util.Comparator;
35 import java.util.Formatter;
36 import java.util.Locale;
37 import java.util.Objects;
38 import java.util.Spliterator;
39 import java.util.StringJoiner;
40 import java.util.regex.Pattern;
41 import java.util.regex.PatternSyntaxException;
42 import java.util.stream.IntStream;
43 import java.util.stream.Stream;
44 import java.util.stream.StreamSupport;
45 import jdk.internal.HotSpotIntrinsicCandidate;
46 
47 import libcore.util.CharsetUtils;
48 
49 /**
50  * The {@code String} class represents character strings. All
51  * string literals in Java programs, such as {@code "abc"}, are
52  * implemented as instances of this class.
53  * <p>
54  * Strings are constant; their values cannot be changed after they
55  * are created. String buffers support mutable strings.
56  * Because String objects are immutable they can be shared. For example:
57  * <blockquote><pre>
58  *     String str = "abc";
59  * </pre></blockquote><p>
60  * is equivalent to:
61  * <blockquote><pre>
62  *     char data[] = {'a', 'b', 'c'};
63  *     String str = new String(data);
64  * </pre></blockquote><p>
65  * Here are some more examples of how strings can be used:
66  * <blockquote><pre>
67  *     System.out.println("abc");
68  *     String cde = "cde";
69  *     System.out.println("abc" + cde);
70  *     String c = "abc".substring(2,3);
71  *     String d = cde.substring(1, 2);
72  * </pre></blockquote>
73  * <p>
74  * The class {@code String} includes methods for examining
75  * individual characters of the sequence, for comparing strings, for
76  * searching strings, for extracting substrings, and for creating a
77  * copy of a string with all characters translated to uppercase or to
78  * lowercase. Case mapping is based on the Unicode Standard version
79  * specified by the {@link java.lang.Character Character} class.
80  * <p>
81  * The Java language provides special support for the string
82  * concatenation operator (&nbsp;+&nbsp;), and for conversion of
83  * other objects to strings. For additional information on string
84  * concatenation and conversion, see <i>The Java&trade; Language Specification</i>.
85  *
86  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
87  * or method in this class will cause a {@link NullPointerException} to be
88  * thrown.
89  *
90  * <p>A {@code String} represents a string in the UTF-16 format
91  * in which <em>supplementary characters</em> are represented by <em>surrogate
92  * pairs</em> (see the section <a href="Character.html#unicode">Unicode
93  * Character Representations</a> in the {@code Character} class for
94  * more information).
95  * Index values refer to {@code char} code units, so a supplementary
96  * character uses two positions in a {@code String}.
97  * <p>The {@code String} class provides methods for dealing with
98  * Unicode code points (i.e., characters), in addition to those for
99  * dealing with Unicode code units (i.e., {@code char} values).
100  *
101  * <p>Unless otherwise noted, methods for comparing Strings do not take locale
102  * into account.  The {@link java.text.Collator} class provides methods for
103  * finer-grain, locale-sensitive String comparison.
104  *
105  * @implNote The implementation of the string concatenation operator is left to
106  * the discretion of a Java compiler, as long as the compiler ultimately conforms
107  * to <i>The Java&trade; Language Specification</i>. For example, the {@code javac} compiler
108  * may implement the operator with {@code StringBuffer}, {@code StringBuilder},
109  * or {@code java.lang.invoke.StringConcatFactory} depending on the JDK version. The
110  * implementation of string conversion is typically through the method {@code toString},
111  * defined by {@code Object} and inherited by all classes in Java.
112  *
113  * @author  Lee Boynton
114  * @author  Arthur van Hoff
115  * @author  Martin Buchholz
116  * @author  Ulf Zibis
117  * @see     java.lang.Object#toString()
118  * @see     java.lang.StringBuffer
119  * @see     java.lang.StringBuilder
120  * @see     java.nio.charset.Charset
121  * @since   1.0
122  * @jls     15.18.1 String Concatenation Operator +
123  */
124 
125 public final class String
126     implements java.io.Serializable, Comparable<String>, CharSequence {
127     // BEGIN Android-changed: The character data is managed by the runtime.
128     /*
129     We only keep track of the length here and compression here. This has several consequences
130     throughout this class:
131      - References to value[i] are replaced by charAt(i).
132      - References to value.length are replaced by calls to length().
133      - Sometimes the result of length() is assigned to a local variable to avoid repeated calls.
134      - We skip several attempts at optimization where the values field was assigned to a local
135        variable to avoid the getfield opcode.
136     These changes are not all marked individually.
137 
138     If STRING_COMPRESSION_ENABLED, count stores the length shifted one bit to the left with the
139     lowest bit used to indicate whether or not the bytes are compressed (see GetFlaggedCount in
140     the native code).
141     /**
142      * The value is used for character storage.
143      *
144      * @implNote This field is trusted by the VM, and is a subject to
145      * constant folding if String instance is constant. Overwriting this
146      * field after construction will cause problems.
147      *
148      * Additionally, it is marked with {@link Stable} to trust the contents
149      * of the array. No other facility in JDK provides this functionality (yet).
150      * {@link Stable} is safe here, because value is never null.
151      *
152     @Stable
153     private final byte[] value;
154     */
155     private final int count;
156     // END Android-changed: The character data is managed by the runtime.
157 
158     // Android-changed: We make use of new StringIndexOutOfBoundsException constructor signatures.
159     // These improve some error messages. These changes are not all marked individually.
160 
161     /** Cache the hash code for the string */
162     private int hash; // Default to 0
163 
164     /** use serialVersionUID from JDK 1.0.2 for interoperability */
165     private static final long serialVersionUID = -6849794470754667710L;
166 
167     /**
168      * Class String is special cased within the Serialization Stream Protocol.
169      *
170      * A String instance is written into an ObjectOutputStream according to
171      * <a href="{@docRoot}/../specs/serialization/protocol.html#stream-elements">
172      * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
173      */
174     private static final ObjectStreamField[] serialPersistentFields =
175         new ObjectStreamField[0];
176 
177     /**
178      * Initializes a newly created {@code String} object so that it represents
179      * an empty character sequence.  Note that use of this constructor is
180      * unnecessary since Strings are immutable.
181      */
String()182     public String() {
183         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
184         /*
185         this.value = "".value;
186         this.coder = "".coder;
187          */
188         throw new UnsupportedOperationException("Use StringFactory instead.");
189         // END Android-changed: Implemented as compiler and runtime intrinsics.
190     }
191 
192     /**
193      * Initializes a newly created {@code String} object so that it represents
194      * the same sequence of characters as the argument; in other words, the
195      * newly created string is a copy of the argument string. Unless an
196      * explicit copy of {@code original} is needed, use of this constructor is
197      * unnecessary since Strings are immutable.
198      *
199      * @param  original
200      *         A {@code String}
201      */
202     @HotSpotIntrinsicCandidate
String(String original)203     public String(String original) {
204         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
205         /*
206         this.value = original.value;
207         this.coder = original.coder;
208         this.hash = original.hash;
209          */
210         throw new UnsupportedOperationException("Use StringFactory instead.");
211         // END Android-changed: Implemented as compiler and runtime intrinsics.
212     }
213 
214     /**
215      * Allocates a new {@code String} so that it represents the sequence of
216      * characters currently contained in the character array argument. The
217      * contents of the character array are copied; subsequent modification of
218      * the character array does not affect the newly created string.
219      *
220      * @param  value
221      *         The initial value of the string
222      */
String(char value[])223     public String(char value[]) {
224         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
225         /*
226         this(value, 0, value.length, null);
227          */
228         throw new UnsupportedOperationException("Use StringFactory instead.");
229         // END Android-changed: Implemented as compiler and runtime intrinsics.
230     }
231 
232     /**
233      * Allocates a new {@code String} that contains characters from a subarray
234      * of the character array argument. The {@code offset} argument is the
235      * index of the first character of the subarray and the {@code count}
236      * argument specifies the length of the subarray. The contents of the
237      * subarray are copied; subsequent modification of the character array does
238      * not affect the newly created string.
239      *
240      * @param  value
241      *         Array that is the source of characters
242      *
243      * @param  offset
244      *         The initial offset
245      *
246      * @param  count
247      *         The length
248      *
249      * @throws  IndexOutOfBoundsException
250      *          If {@code offset} is negative, {@code count} is negative, or
251      *          {@code offset} is greater than {@code value.length - count}
252      */
String(char value[], int offset, int count)253     public String(char value[], int offset, int count) {
254         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
255         /*
256         this(value, offset, count, rangeCheck(value, offset, count));
257     }
258 
259     private static Void rangeCheck(char[] value, int offset, int count) {
260         checkBoundsOffCount(offset, count, value.length);
261         return null;
262          */
263         throw new UnsupportedOperationException("Use StringFactory instead.");
264         // END Android-changed: Implemented as compiler and runtime intrinsics.
265     }
266 
267     /**
268      * Allocates a new {@code String} that contains characters from a subarray
269      * of the <a href="Character.html#unicode">Unicode code point</a> array
270      * argument.  The {@code offset} argument is the index of the first code
271      * point of the subarray and the {@code count} argument specifies the
272      * length of the subarray.  The contents of the subarray are converted to
273      * {@code char}s; subsequent modification of the {@code int} array does not
274      * affect the newly created string.
275      *
276      * @param  codePoints
277      *         Array that is the source of Unicode code points
278      *
279      * @param  offset
280      *         The initial offset
281      *
282      * @param  count
283      *         The length
284      *
285      * @throws  IllegalArgumentException
286      *          If any invalid Unicode code point is found in {@code
287      *          codePoints}
288      *
289      * @throws  IndexOutOfBoundsException
290      *          If {@code offset} is negative, {@code count} is negative, or
291      *          {@code offset} is greater than {@code codePoints.length - count}
292      *
293      * @since  1.5
294      */
String(int[] codePoints, int offset, int count)295     public String(int[] codePoints, int offset, int count) {
296         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
297         /*
298         checkBoundsOffCount(offset, count, codePoints.length);
299         if (count == 0) {
300             this.value = "".value;
301             this.coder = "".coder;
302             return;
303         }
304         if (COMPACT_STRINGS) {
305             byte[] val = StringLatin1.toBytes(codePoints, offset, count);
306             if (val != null) {
307                 this.coder = LATIN1;
308                 this.value = val;
309                 return;
310             }
311         }
312         this.coder = UTF16;
313         this.value = StringUTF16.toBytes(codePoints, offset, count);
314         */
315         throw new UnsupportedOperationException("Use StringFactory instead.");
316         // END Android-changed: Implemented as compiler and runtime intrinsics.
317     }
318 
319     /**
320      * Allocates a new {@code String} constructed from a subarray of an array
321      * of 8-bit integer values.
322      *
323      * <p> The {@code offset} argument is the index of the first byte of the
324      * subarray, and the {@code count} argument specifies the length of the
325      * subarray.
326      *
327      * <p> Each {@code byte} in the subarray is converted to a {@code char} as
328      * specified in the {@link #String(byte[],int) String(byte[],int)} constructor.
329      *
330      * @deprecated This method does not properly convert bytes into characters.
331      * As of JDK&nbsp;1.1, the preferred way to do this is via the
332      * {@code String} constructors that take a {@link
333      * java.nio.charset.Charset}, charset name, or that use the platform's
334      * default charset.
335      *
336      * @param  ascii
337      *         The bytes to be converted to characters
338      *
339      * @param  hibyte
340      *         The top 8 bits of each 16-bit Unicode code unit
341      *
342      * @param  offset
343      *         The initial offset
344      * @param  count
345      *         The length
346      *
347      * @throws  IndexOutOfBoundsException
348      *          If {@code offset} is negative, {@code count} is negative, or
349      *          {@code offset} is greater than {@code ascii.length - count}
350      *
351      * @see  #String(byte[], int)
352      * @see  #String(byte[], int, int, java.lang.String)
353      * @see  #String(byte[], int, int, java.nio.charset.Charset)
354      * @see  #String(byte[], int, int)
355      * @see  #String(byte[], java.lang.String)
356      * @see  #String(byte[], java.nio.charset.Charset)
357      * @see  #String(byte[])
358      */
359     @Deprecated(since="1.1")
String(byte ascii[], int hibyte, int offset, int count)360     public String(byte ascii[], int hibyte, int offset, int count) {
361         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
362         /*
363         checkBoundsOffCount(offset, count, ascii.length);
364         if (count == 0) {
365             this.value = "".value;
366             this.coder = "".coder;
367             return;
368         }
369         if (COMPACT_STRINGS && (byte)hibyte == 0) {
370             this.value = Arrays.copyOfRange(ascii, offset, offset + count);
371             this.coder = LATIN1;
372         } else {
373             hibyte <<= 8;
374             byte[] val = StringUTF16.newBytesFor(count);
375             for (int i = 0; i < count; i++) {
376                 StringUTF16.putChar(val, i, hibyte | (ascii[offset++] & 0xff));
377             }
378             this.value = val;
379             this.coder = UTF16;
380         }
381         */
382         throw new UnsupportedOperationException("Use StringFactory instead.");
383         // END Android-changed: Implemented as compiler and runtime intrinsics.
384     }
385 
386     /**
387      * Allocates a new {@code String} containing characters constructed from
388      * an array of 8-bit integer values. Each character <i>c</i> in the
389      * resulting string is constructed from the corresponding component
390      * <i>b</i> in the byte array such that:
391      *
392      * <blockquote><pre>
393      *     <b><i>c</i></b> == (char)(((hibyte &amp; 0xff) &lt;&lt; 8)
394      *                         | (<b><i>b</i></b> &amp; 0xff))
395      * </pre></blockquote>
396      *
397      * @deprecated  This method does not properly convert bytes into
398      * characters.  As of JDK&nbsp;1.1, the preferred way to do this is via the
399      * {@code String} constructors that take a {@link
400      * java.nio.charset.Charset}, charset name, or that use the platform's
401      * default charset.
402      *
403      * @param  ascii
404      *         The bytes to be converted to characters
405      *
406      * @param  hibyte
407      *         The top 8 bits of each 16-bit Unicode code unit
408      *
409      * @see  #String(byte[], int, int, java.lang.String)
410      * @see  #String(byte[], int, int, java.nio.charset.Charset)
411      * @see  #String(byte[], int, int)
412      * @see  #String(byte[], java.lang.String)
413      * @see  #String(byte[], java.nio.charset.Charset)
414      * @see  #String(byte[])
415      */
416     @Deprecated(since="1.1")
String(byte ascii[], int hibyte)417     public String(byte ascii[], int hibyte) {
418         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
419         /*
420         this(ascii, hibyte, 0, ascii.length);
421         */
422         throw new UnsupportedOperationException("Use StringFactory instead.");
423         // END Android-changed: Implemented as compiler and runtime intrinsics.
424     }
425 
426     // BEGIN Android-removed: checkBounds(byte[] bytes, int offset, int length) utility method.
427     /* Common private utility method used to bounds check the byte array
428      * and requested offset & length values used by the String(byte[],..)
429      * constructors.
430      *
431     private static void checkBounds(byte[] bytes, int offset, int length) {
432         if (length < 0)
433             throw new StringIndexOutOfBoundsException(length);
434         if (offset < 0)
435             throw new StringIndexOutOfBoundsException(offset);
436         if (offset > bytes.length - length)
437             throw new StringIndexOutOfBoundsException(offset + length);
438     }
439     // END Android-removed: checkBounds(byte[] bytes, int offset, int length) utility method.
440 
441     /**
442      * Constructs a new {@code String} by decoding the specified subarray of
443      * bytes using the specified charset.  The length of the new {@code String}
444      * is a function of the charset, and hence may not be equal to the length
445      * of the subarray.
446      *
447      * <p> The behavior of this constructor when the given bytes are not valid
448      * in the given charset is unspecified.  The {@link
449      * java.nio.charset.CharsetDecoder} class should be used when more control
450      * over the decoding process is required.
451      *
452      * @param  bytes
453      *         The bytes to be decoded into characters
454      *
455      * @param  offset
456      *         The index of the first byte to decode
457      *
458      * @param  length
459      *         The number of bytes to decode
460 
461      * @param  charsetName
462      *         The name of a supported {@linkplain java.nio.charset.Charset
463      *         charset}
464      *
465      * @throws  UnsupportedEncodingException
466      *          If the named charset is not supported
467      *
468      * @throws  IndexOutOfBoundsException
469      *          If {@code offset} is negative, {@code length} is negative, or
470      *          {@code offset} is greater than {@code bytes.length - length}
471      *
472      * @since  1.1
473      */
String(byte bytes[], int offset, int length, String charsetName)474     public String(byte bytes[], int offset, int length, String charsetName)
475             throws UnsupportedEncodingException {
476         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
477         /*
478         if (charsetName == null)
479             throw new NullPointerException("charsetName");
480         checkBoundsOffCount(offset, length, bytes.length);
481         StringCoding.Result ret =
482             StringCoding.decode(charsetName, bytes, offset, length);
483         this.value = ret.value;
484         this.coder = ret.coder;
485         */
486         throw new UnsupportedOperationException("Use StringFactory instead.");
487         // END Android-changed: Implemented as compiler and runtime intrinsics.
488     }
489 
490     /**
491      * Constructs a new {@code String} by decoding the specified subarray of
492      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
493      * The length of the new {@code String} is a function of the charset, and
494      * hence may not be equal to the length of the subarray.
495      *
496      * <p> This method always replaces malformed-input and unmappable-character
497      * sequences with this charset's default replacement string.  The {@link
498      * java.nio.charset.CharsetDecoder} class should be used when more control
499      * over the decoding process is required.
500      *
501      * @param  bytes
502      *         The bytes to be decoded into characters
503      *
504      * @param  offset
505      *         The index of the first byte to decode
506      *
507      * @param  length
508      *         The number of bytes to decode
509      *
510      * @param  charset
511      *         The {@linkplain java.nio.charset.Charset charset} to be used to
512      *         decode the {@code bytes}
513      *
514      * @throws  IndexOutOfBoundsException
515      *          If {@code offset} is negative, {@code length} is negative, or
516      *          {@code offset} is greater than {@code bytes.length - length}
517      *
518      * @since  1.6
519      */
String(byte bytes[], int offset, int length, Charset charset)520     public String(byte bytes[], int offset, int length, Charset charset) {
521         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
522         /*
523         if (charset == null)
524             throw new NullPointerException("charset");
525         checkBoundsOffCount(offset, length, bytes.length);
526         StringCoding.Result ret =
527             StringCoding.decode(charset, bytes, offset, length);
528         this.value = ret.value;
529         this.coder = ret.coder;
530         */
531         throw new UnsupportedOperationException("Use StringFactory instead.");
532         // END Android-changed: Implemented as compiler and runtime intrinsics.
533     }
534 
535     /**
536      * Constructs a new {@code String} by decoding the specified array of bytes
537      * using the specified {@linkplain java.nio.charset.Charset charset}.  The
538      * length of the new {@code String} is a function of the charset, and hence
539      * may not be equal to the length of the byte array.
540      *
541      * <p> The behavior of this constructor when the given bytes are not valid
542      * in the given charset is unspecified.  The {@link
543      * java.nio.charset.CharsetDecoder} class should be used when more control
544      * over the decoding process is required.
545      *
546      * @param  bytes
547      *         The bytes to be decoded into characters
548      *
549      * @param  charsetName
550      *         The name of a supported {@linkplain java.nio.charset.Charset
551      *         charset}
552      *
553      * @throws  UnsupportedEncodingException
554      *          If the named charset is not supported
555      *
556      * @since  1.1
557      */
String(byte bytes[], String charsetName)558     public String(byte bytes[], String charsetName)
559             throws UnsupportedEncodingException {
560         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
561         /*
562         this(bytes, 0, bytes.length, charsetName);
563          */
564         throw new UnsupportedOperationException("Use StringFactory instead.");
565         // END Android-changed: Implemented as compiler and runtime intrinsics.
566     }
567 
568     /**
569      * Constructs a new {@code String} by decoding the specified array of
570      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
571      * The length of the new {@code String} is a function of the charset, and
572      * hence may not be equal to the length of the byte array.
573      *
574      * <p> This method always replaces malformed-input and unmappable-character
575      * sequences with this charset's default replacement string.  The {@link
576      * java.nio.charset.CharsetDecoder} class should be used when more control
577      * over the decoding process is required.
578      *
579      * @param  bytes
580      *         The bytes to be decoded into characters
581      *
582      * @param  charset
583      *         The {@linkplain java.nio.charset.Charset charset} to be used to
584      *         decode the {@code bytes}
585      *
586      * @since  1.6
587      */
String(byte bytes[], Charset charset)588     public String(byte bytes[], Charset charset) {
589         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
590         /*
591         this(bytes, 0, bytes.length, charset);
592          */
593         throw new UnsupportedOperationException("Use StringFactory instead.");
594         // END Android-changed: Implemented as compiler and runtime intrinsics.
595     }
596 
597     /**
598      * Constructs a new {@code String} by decoding the specified subarray of
599      * bytes using the platform's default charset.  The length of the new
600      * {@code String} is a function of the charset, and hence may not be equal
601      * to the length of the subarray.
602      *
603      * <p> The behavior of this constructor when the given bytes are not valid
604      * in the default charset is unspecified.  The {@link
605      * java.nio.charset.CharsetDecoder} class should be used when more control
606      * over the decoding process is required.
607      *
608      * @param  bytes
609      *         The bytes to be decoded into characters
610      *
611      * @param  offset
612      *         The index of the first byte to decode
613      *
614      * @param  length
615      *         The number of bytes to decode
616      *
617      * @throws  IndexOutOfBoundsException
618      *          If {@code offset} is negative, {@code length} is negative, or
619      *          {@code offset} is greater than {@code bytes.length - length}
620      *
621      * @since  1.1
622      */
String(byte bytes[], int offset, int length)623     public String(byte bytes[], int offset, int length) {
624         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
625         /*
626         checkBoundsOffCount(offset, length, bytes.length);
627         StringCoding.Result ret = StringCoding.decode(bytes, offset, length);
628         this.value = ret.value;
629         this.coder = ret.coder;
630          */
631         throw new UnsupportedOperationException("Use StringFactory instead.");
632         // END Android-changed: Implemented as compiler and runtime intrinsics.
633     }
634 
635     /**
636      * Constructs a new {@code String} by decoding the specified array of bytes
637      * using the platform's default charset.  The length of the new {@code
638      * String} is a function of the charset, and hence may not be equal to the
639      * length of the byte array.
640      *
641      * <p> The behavior of this constructor when the given bytes are not valid
642      * in the default charset is unspecified.  The {@link
643      * java.nio.charset.CharsetDecoder} class should be used when more control
644      * over the decoding process is required.
645      *
646      * @param  bytes
647      *         The bytes to be decoded into characters
648      *
649      * @since  1.1
650      */
String(byte[] bytes)651     public String(byte[] bytes) {
652         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
653         /*
654         this(bytes, 0, bytes.length);
655          */
656         throw new UnsupportedOperationException("Use StringFactory instead.");
657         // END Android-changed: Implemented as compiler and runtime intrinsics.
658     }
659 
660     /**
661      * Allocates a new string that contains the sequence of characters
662      * currently contained in the string buffer argument. The contents of the
663      * string buffer are copied; subsequent modification of the string buffer
664      * does not affect the newly created string.
665      *
666      * @param  buffer
667      *         A {@code StringBuffer}
668      */
String(StringBuffer buffer)669     public String(StringBuffer buffer) {
670         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
671         /*
672         this(buffer.toString());
673          */
674         throw new UnsupportedOperationException("Use StringFactory instead.");
675         // END Android-changed: Implemented as compiler and runtime intrinsics.
676     }
677 
678     /**
679      * Allocates a new string that contains the sequence of characters
680      * currently contained in the string builder argument. The contents of the
681      * string builder are copied; subsequent modification of the string builder
682      * does not affect the newly created string.
683      *
684      * <p> This constructor is provided to ease migration to {@code
685      * StringBuilder}. Obtaining a string from a string builder via the {@code
686      * toString} method is likely to run faster and is generally preferred.
687      *
688      * @param   builder
689      *          A {@code StringBuilder}
690      *
691      * @since  1.5
692      */
String(StringBuilder builder)693     public String(StringBuilder builder) {
694         // BEGIN Android-changed: Implemented as compiler and runtime intrinsics.
695         /*
696         this(builder, null);
697          */
698         throw new UnsupportedOperationException("Use StringFactory instead.");
699         // END Android-changed: Implemented as compiler and runtime intrinsics.
700     }
701 
702     // BEGIN Android-removed: Unused package-private constructor String(char[] value, boolean share).
703     /*
704     /*
705     * Package private constructor which shares value array for speed.
706     * this constructor is always expected to be called with share==true.
707     * a separate constructor is needed because we already have a public
708     * String(char[]) constructor that makes a copy of the given char[].
709     *
710     String(char[] value, boolean share) {
711         // assert share : "unshared not supported";
712         this.value = value;
713     }
714     */
715     // END Android-removed: Unused package-private constructor String(char[] value, boolean share).
716 
717     // BEGIN Android-added: Constructor for internal use.
718     // Not implemented in java as all calls are intercepted by the runtime.
719     /**
720      * Package private constructor
721      *
722      * @deprecated Use {@link #String(char[],int,int)} instead.
723      */
724     @Deprecated
String(int offset, int count, char[] value)725     String(int offset, int count, char[] value) {
726         throw new UnsupportedOperationException("Use StringFactory instead.");
727     }
728     // END Android-added: Constructor for internal use.
729 
730     /**
731      * Returns the length of this string.
732      * The length is equal to the number of <a href="Character.html#unicode">Unicode
733      * code units</a> in the string.
734      *
735      * @return  the length of the sequence of characters represented by this
736      *          object.
737      */
length()738     public int length() {
739         // BEGIN Android-changed: Get length from count field rather than value array (see above).
740         /*
741         return value.length >> coder();
742         */
743         final boolean STRING_COMPRESSION_ENABLED = true;
744         if (STRING_COMPRESSION_ENABLED) {
745             // For the compression purposes (save the characters as 8-bit if all characters
746             // are ASCII), the least significant bit of "count" is used as the compression flag.
747             return (count >>> 1);
748         } else {
749             return count;
750         }
751         // END Android-changed: Get length from count field rather than value array (see above).
752     }
753 
754     /**
755      * Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
756      *
757      * @return {@code true} if {@link #length()} is {@code 0}, otherwise
758      * {@code false}
759      *
760      * @since 1.6
761      */
isEmpty()762     public boolean isEmpty() {
763         // BEGIN Android-changed: Get length from count field rather than value array (see above).
764         // Empty string has {@code count == 0} with or without string compression enabled.
765         /*
766         return value.length == 0;
767          */
768         return count == 0;
769         // END Android-changed: Get length from count field rather than value array (see above).
770     }
771 
772     /**
773      * Returns the {@code char} value at the
774      * specified index. An index ranges from {@code 0} to
775      * {@code length() - 1}. The first {@code char} value of the sequence
776      * is at index {@code 0}, the next at index {@code 1},
777      * and so on, as for array indexing.
778      *
779      * <p>If the {@code char} value specified by the index is a
780      * <a href="Character.html#unicode">surrogate</a>, the surrogate
781      * value is returned.
782      *
783      * @param      index   the index of the {@code char} value.
784      * @return     the {@code char} value at the specified index of this string.
785      *             The first {@code char} value is at index {@code 0}.
786      * @exception  IndexOutOfBoundsException  if the {@code index}
787      *             argument is negative or not less than the length of this
788      *             string.
789      */
790     // BEGIN Android-changed: Replace with implementation in runtime to access chars (see above).
791     /*
792     public char charAt(int index) {
793         if (isLatin1()) {
794             return StringLatin1.charAt(value, index);
795         } else {
796             return StringUTF16.charAt(value, index);
797         }
798     }
799     */
800     @FastNative
charAt(int index)801     public native char charAt(int index);
802     // END Android-changed: Replace with implementation in runtime to access chars (see above).
803 
804     /**
805      * Returns the character (Unicode code point) at the specified
806      * index. The index refers to {@code char} values
807      * (Unicode code units) and ranges from {@code 0} to
808      * {@link #length()}{@code  - 1}.
809      *
810      * <p> If the {@code char} value specified at the given index
811      * is in the high-surrogate range, the following index is less
812      * than the length of this {@code String}, and the
813      * {@code char} value at the following index is in the
814      * low-surrogate range, then the supplementary code point
815      * corresponding to this surrogate pair is returned. Otherwise,
816      * the {@code char} value at the given index is returned.
817      *
818      * @param      index the index to the {@code char} values
819      * @return     the code point value of the character at the
820      *             {@code index}
821      * @exception  IndexOutOfBoundsException  if the {@code index}
822      *             argument is negative or not less than the length of this
823      *             string.
824      * @since      1.5
825      */
codePointAt(int index)826     public int codePointAt(int index) {
827         // BEGIN Android-changed: delegate codePointAt() to Character class.
828         /*
829         if (isLatin1()) {
830             checkIndex(index, value.length);
831             return value[index] & 0xff;
832         }
833         int length = value.length >> 1;
834         checkIndex(index, length);
835         return StringUTF16.codePointAt(value, index, length);
836          */
837         checkIndex(index, length());
838         return Character.codePointAt(this, index);
839     }
840 
841     /**
842      * Returns the character (Unicode code point) before the specified
843      * index. The index refers to {@code char} values
844      * (Unicode code units) and ranges from {@code 1} to {@link
845      * CharSequence#length() length}.
846      *
847      * <p> If the {@code char} value at {@code (index - 1)}
848      * is in the low-surrogate range, {@code (index - 2)} is not
849      * negative, and the {@code char} value at {@code (index -
850      * 2)} is in the high-surrogate range, then the
851      * supplementary code point value of the surrogate pair is
852      * returned. If the {@code char} value at {@code index -
853      * 1} is an unpaired low-surrogate or a high-surrogate, the
854      * surrogate value is returned.
855      *
856      * @param     index the index following the code point that should be returned
857      * @return    the Unicode code point value before the given index.
858      * @exception IndexOutOfBoundsException if the {@code index}
859      *            argument is less than 1 or greater than the length
860      *            of this string.
861      * @since     1.5
862      */
codePointBefore(int index)863     public int codePointBefore(int index) {
864         int i = index - 1;
865         if (i < 0 || i >= length()) {
866             throw new StringIndexOutOfBoundsException(index);
867         }
868         // BEGIN Android-changed: delegate codePointBefore to Character class.
869         /*
870         if (isLatin1()) {
871             return (value[i] & 0xff);
872         }
873         return StringUTF16.codePointBefore(value, index);
874          */
875         return Character.codePointBefore(this, index);
876     }
877 
878     /**
879      * Returns the number of Unicode code points in the specified text
880      * range of this {@code String}. The text range begins at the
881      * specified {@code beginIndex} and extends to the
882      * {@code char} at index {@code endIndex - 1}. Thus the
883      * length (in {@code char}s) of the text range is
884      * {@code endIndex-beginIndex}. Unpaired surrogates within
885      * the text range count as one code point each.
886      *
887      * @param beginIndex the index to the first {@code char} of
888      * the text range.
889      * @param endIndex the index after the last {@code char} of
890      * the text range.
891      * @return the number of Unicode code points in the specified text
892      * range
893      * @exception IndexOutOfBoundsException if the
894      * {@code beginIndex} is negative, or {@code endIndex}
895      * is larger than the length of this {@code String}, or
896      * {@code beginIndex} is larger than {@code endIndex}.
897      * @since  1.5
898      */
codePointCount(int beginIndex, int endIndex)899     public int codePointCount(int beginIndex, int endIndex) {
900         if (beginIndex < 0 || beginIndex > endIndex ||
901             endIndex > length()) {
902             throw new IndexOutOfBoundsException();
903         }
904         // BEGIN Android-changed: delegate codePointCount to Character class.
905         /*
906         if (isLatin1()) {
907             return endIndex - beginIndex;
908         }
909         return StringUTF16.codePointCount(value, beginIndex, endIndex);
910          */
911         return Character.codePointCount(this, beginIndex, endIndex);
912         // END Android-changed: delegate codePointCount to Character class.
913     }
914 
915     /**
916      * Returns the index within this {@code String} that is
917      * offset from the given {@code index} by
918      * {@code codePointOffset} code points. Unpaired surrogates
919      * within the text range given by {@code index} and
920      * {@code codePointOffset} count as one code point each.
921      *
922      * @param index the index to be offset
923      * @param codePointOffset the offset in code points
924      * @return the index within this {@code String}
925      * @exception IndexOutOfBoundsException if {@code index}
926      *   is negative or larger then the length of this
927      *   {@code String}, or if {@code codePointOffset} is positive
928      *   and the substring starting with {@code index} has fewer
929      *   than {@code codePointOffset} code points,
930      *   or if {@code codePointOffset} is negative and the substring
931      *   before {@code index} has fewer than the absolute value
932      *   of {@code codePointOffset} code points.
933      * @since 1.5
934      */
offsetByCodePoints(int index, int codePointOffset)935     public int offsetByCodePoints(int index, int codePointOffset) {
936         if (index < 0 || index > length()) {
937             throw new IndexOutOfBoundsException();
938         }
939         return Character.offsetByCodePoints(this, index, codePointOffset);
940     }
941 
942     /**
943      * Copy characters from this string into dst starting at dstBegin.
944      * This method doesn't perform any range checking.
945      */
getChars(char dst[], int dstBegin)946     void getChars(char dst[], int dstBegin) {
947         // Android-changed: Replace arraycopy with native call since chars are managed by runtime.
948         // System.arraycopy(value, 0, dst, dstBegin, value.length);
949         getCharsNoCheck(0, length(), dst, dstBegin);
950     }
951 
952     /**
953      * Copies characters from this string into the destination character
954      * array.
955      * <p>
956      * The first character to be copied is at index {@code srcBegin};
957      * the last character to be copied is at index {@code srcEnd-1}
958      * (thus the total number of characters to be copied is
959      * {@code srcEnd-srcBegin}). The characters are copied into the
960      * subarray of {@code dst} starting at index {@code dstBegin}
961      * and ending at index:
962      * <blockquote><pre>
963      *     dstBegin + (srcEnd-srcBegin) - 1
964      * </pre></blockquote>
965      *
966      * @param      srcBegin   index of the first character in the string
967      *                        to copy.
968      * @param      srcEnd     index after the last character in the string
969      *                        to copy.
970      * @param      dst        the destination array.
971      * @param      dstBegin   the start offset in the destination array.
972      * @exception IndexOutOfBoundsException If any of the following
973      *            is true:
974      *            <ul><li>{@code srcBegin} is negative.
975      *            <li>{@code srcBegin} is greater than {@code srcEnd}
976      *            <li>{@code srcEnd} is greater than the length of this
977      *                string
978      *            <li>{@code dstBegin} is negative
979      *            <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
980      *                {@code dst.length}</ul>
981      */
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)982     public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
983         // BEGIN Android-added: Null pointer check.
984         if (dst == null) {
985             throw new NullPointerException("dst == null");
986         }
987         // END Android-added: Null pointer check.
988         checkBoundsBeginEnd(srcBegin, srcEnd, length());
989         // BEGIN Android-changed: Implement in terms of length() and native getCharsNoCheck method.
990         /*
991         checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
992         if (isLatin1()) {
993             StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
994         } else {
995             StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
996         }
997         */
998         if (dstBegin < 0) {
999             throw new ArrayIndexOutOfBoundsException("dstBegin < 0. dstBegin=" + dstBegin);
1000         }
1001         // dstBegin can be equal to dst.length, but only in the case where zero chars are to be
1002         // copied.
1003         if (dstBegin > dst.length) {
1004             throw new ArrayIndexOutOfBoundsException(
1005                     "dstBegin > dst.length. dstBegin=" + dstBegin + ", dst.length=" + dst.length);
1006         }
1007 
1008         int n = srcEnd - srcBegin;
1009         if (n > dst.length - dstBegin) {
1010             throw new ArrayIndexOutOfBoundsException(
1011                     "n > dst.length - dstBegin. n=" + n + ", dst.length=" + dst.length
1012                             + "dstBegin=" + dstBegin);
1013         }
1014 
1015         getCharsNoCheck(srcBegin, srcEnd, dst, dstBegin);
1016         // END Android-changed: Implement in terms of length() and native getCharsNoCheck method.
1017     }
1018 
1019     // BEGIN Android-added: Native method to access char storage managed by runtime.
1020     /**
1021      * getChars without bounds checks, for use by other classes
1022      * within the java.lang package only.  The caller is responsible for
1023      * ensuring that start >= 0 && start <= end && end <= count.
1024      */
1025     @FastNative
getCharsNoCheck(int start, int end, char[] buffer, int index)1026     native void getCharsNoCheck(int start, int end, char[] buffer, int index);
1027     // END Android-added: Native method to access char storage managed by runtime.
1028 
1029     /**
1030      * Copies characters from this string into the destination byte array. Each
1031      * byte receives the 8 low-order bits of the corresponding character. The
1032      * eight high-order bits of each character are not copied and do not
1033      * participate in the transfer in any way.
1034      *
1035      * <p> The first character to be copied is at index {@code srcBegin}; the
1036      * last character to be copied is at index {@code srcEnd-1}.  The total
1037      * number of characters to be copied is {@code srcEnd-srcBegin}. The
1038      * characters, converted to bytes, are copied into the subarray of {@code
1039      * dst} starting at index {@code dstBegin} and ending at index:
1040      *
1041      * <blockquote><pre>
1042      *     dstBegin + (srcEnd-srcBegin) - 1
1043      * </pre></blockquote>
1044      *
1045      * @deprecated  This method does not properly convert characters into
1046      * bytes.  As of JDK&nbsp;1.1, the preferred way to do this is via the
1047      * {@link #getBytes()} method, which uses the platform's default charset.
1048      *
1049      * @param  srcBegin
1050      *         Index of the first character in the string to copy
1051      *
1052      * @param  srcEnd
1053      *         Index after the last character in the string to copy
1054      *
1055      * @param  dst
1056      *         The destination array
1057      *
1058      * @param  dstBegin
1059      *         The start offset in the destination array
1060      *
1061      * @throws  IndexOutOfBoundsException
1062      *          If any of the following is true:
1063      *          <ul>
1064      *            <li> {@code srcBegin} is negative
1065      *            <li> {@code srcBegin} is greater than {@code srcEnd}
1066      *            <li> {@code srcEnd} is greater than the length of this String
1067      *            <li> {@code dstBegin} is negative
1068      *            <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
1069      *                 dst.length}
1070      *          </ul>
1071      */
1072     @Deprecated(since="1.1")
getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin)1073     public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
1074         checkBoundsBeginEnd(srcBegin, srcEnd, length());
1075         Objects.requireNonNull(dst);
1076         checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
1077         // BEGIN Android-changed: Implement in terms of charAt().
1078         /*
1079         if (isLatin1()) {
1080             StringLatin1.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
1081         } else {
1082             StringUTF16.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
1083         }
1084          */
1085         int j = dstBegin;
1086         int n = srcEnd;
1087         int i = srcBegin;
1088 
1089         while (i < n) {
1090             dst[j++] = (byte)charAt(i++);
1091         }
1092         // END Android-changed: Implement in terms of charAt().
1093     }
1094 
1095     /**
1096      * Encodes this {@code String} into a sequence of bytes using the named
1097      * charset, storing the result into a new byte array.
1098      *
1099      * <p> The behavior of this method when this string cannot be encoded in
1100      * the given charset is unspecified.  The {@link
1101      * java.nio.charset.CharsetEncoder} class should be used when more control
1102      * over the encoding process is required.
1103      *
1104      * @param  charsetName
1105      *         The name of a supported {@linkplain java.nio.charset.Charset
1106      *         charset}
1107      *
1108      * @return  The resultant byte array
1109      *
1110      * @throws  UnsupportedEncodingException
1111      *          If the named charset is not supported
1112      *
1113      * @since  1.1
1114      */
getBytes(String charsetName)1115     public byte[] getBytes(String charsetName)
1116             throws UnsupportedEncodingException {
1117         if (charsetName == null) throw new NullPointerException();
1118         // BEGIN Android-changed: Skip StringCoding optimization that needs access to java chars.
1119         /*
1120         return StringCoding.encode(charsetName, coder(), value);
1121          */
1122         return getBytes(Charset.forNameUEE(charsetName));
1123         // END Android-changed: Skip StringCoding optimization that needs access to java chars.
1124     }
1125 
1126     /**
1127      * Encodes this {@code String} into a sequence of bytes using the given
1128      * {@linkplain java.nio.charset.Charset charset}, storing the result into a
1129      * new byte array.
1130      *
1131      * <p> This method always replaces malformed-input and unmappable-character
1132      * sequences with this charset's default replacement byte array.  The
1133      * {@link java.nio.charset.CharsetEncoder} class should be used when more
1134      * control over the encoding process is required.
1135      *
1136      * @param  charset
1137      *         The {@linkplain java.nio.charset.Charset} to be used to encode
1138      *         the {@code String}
1139      *
1140      * @return  The resultant byte array
1141      *
1142      * @since  1.6
1143      */
getBytes(Charset charset)1144     public byte[] getBytes(Charset charset) {
1145         if (charset == null) throw new NullPointerException();
1146         // BEGIN Android-changed: Skip StringCoding optimization that needs access to java chars.
1147         /*
1148         return StringCoding.encode(charset, coder(), value);
1149         */
1150         final int len = length();
1151         final String name = charset.name();
1152         if ("UTF-8".equals(name)) {
1153             return CharsetUtils.toUtf8Bytes(this, 0, len);
1154         } else if ("ISO-8859-1".equals(name)) {
1155             return CharsetUtils.toIsoLatin1Bytes(this, 0, len);
1156         } else if ("US-ASCII".equals(name)) {
1157             return CharsetUtils.toAsciiBytes(this, 0, len);
1158         } else if ("UTF-16BE".equals(name)) {
1159             return CharsetUtils.toBigEndianUtf16Bytes(this, 0, len);
1160         }
1161 
1162         ByteBuffer buffer = charset.encode(this);
1163         byte[] bytes = new byte[buffer.limit()];
1164         buffer.get(bytes);
1165         return bytes;
1166         // END Android-changed: Skip StringCoding optimization that needs access to java chars.
1167     }
1168 
1169     /**
1170      * Encodes this {@code String} into a sequence of bytes using the
1171      * platform's default charset, storing the result into a new byte array.
1172      *
1173      * <p> The behavior of this method when this string cannot be encoded in
1174      * the default charset is unspecified.  The {@link
1175      * java.nio.charset.CharsetEncoder} class should be used when more control
1176      * over the encoding process is required.
1177      *
1178      * @return  The resultant byte array
1179      *
1180      * @since      1.1
1181      */
getBytes()1182     public byte[] getBytes() {
1183         // BEGIN Android-changed: Skip StringCoding optimization that needs access to java chars.
1184         /*
1185         return StringCoding.encode(coder(), value);
1186          */
1187         return getBytes(Charset.defaultCharset());
1188         // END Android-changed: Skip StringCoding optimization that needs access to java chars.
1189     }
1190 
1191     /**
1192      * Compares this string to the specified object.  The result is {@code
1193      * true} if and only if the argument is not {@code null} and is a {@code
1194      * String} object that represents the same sequence of characters as this
1195      * object.
1196      *
1197      * <p>For finer-grained String comparison, refer to
1198      * {@link java.text.Collator}.
1199      *
1200      * @param  anObject
1201      *         The object to compare this {@code String} against
1202      *
1203      * @return  {@code true} if the given object represents a {@code String}
1204      *          equivalent to this string, {@code false} otherwise
1205      *
1206      * @see  #compareTo(String)
1207      * @see  #equalsIgnoreCase(String)
1208      */
equals(Object anObject)1209     public boolean equals(Object anObject) {
1210         if (this == anObject) {
1211             return true;
1212         }
1213         if (anObject instanceof String) {
1214             // BEGIN Android-changed: Implement in terms of charAt().
1215             /*
1216             String aString = (String)anObject;
1217             if (coder() == aString.coder()) {
1218                 return isLatin1() ? StringLatin1.equals(value, aString.value)
1219                                   : StringUTF16.equals(value, aString.value);
1220             }
1221              */
1222             String anotherString = (String)anObject;
1223             int n = length();
1224             if (n == anotherString.length()) {
1225                 int i = 0;
1226                 while (n-- != 0) {
1227                     if (charAt(i) != anotherString.charAt(i))
1228                             return false;
1229                     i++;
1230                 }
1231                 return true;
1232             }
1233             // END Android-changed: Implement in terms of charAt().
1234         }
1235         return false;
1236     }
1237 
1238     /**
1239      * Compares this string to the specified {@code StringBuffer}.  The result
1240      * is {@code true} if and only if this {@code String} represents the same
1241      * sequence of characters as the specified {@code StringBuffer}. This method
1242      * synchronizes on the {@code StringBuffer}.
1243      *
1244      * <p>For finer-grained String comparison, refer to
1245      * {@link java.text.Collator}.
1246      *
1247      * @param  sb
1248      *         The {@code StringBuffer} to compare this {@code String} against
1249      *
1250      * @return  {@code true} if this {@code String} represents the same
1251      *          sequence of characters as the specified {@code StringBuffer},
1252      *          {@code false} otherwise
1253      *
1254      * @since  1.4
1255      */
contentEquals(StringBuffer sb)1256     public boolean contentEquals(StringBuffer sb) {
1257         return contentEquals((CharSequence)sb);
1258     }
1259 
nonSyncContentEquals(AbstractStringBuilder sb)1260     private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
1261         int len = length();
1262         if (len != sb.length()) {
1263             return false;
1264         }
1265         // BEGIN Android-changed: Implement in terms of charAt().
1266         /*
1267         byte v1[] = value;
1268         byte v2[] = sb.getValue();
1269         if (coder() == sb.getCoder()) {
1270             int n = v1.length;
1271             for (int i = 0; i < n; i++) {
1272                 if (v1[i] != v2[i]) {
1273                     return false;
1274                 }
1275             }
1276         } else {
1277             if (!isLatin1()) {  // utf16 str and latin1 abs can never be "equal"
1278                 return false;
1279             }
1280             return StringUTF16.contentEquals(v1, v2, len);
1281         }
1282          */
1283         char[] v2 = sb.getValue();
1284         for (int i = 0; i < len; i++) {
1285             if (charAt(i) != v2[i]) {
1286                 return false;
1287             }
1288         }
1289         // END Android-changed: Implement in terms of charAt().
1290         return true;
1291     }
1292 
1293     /**
1294      * Compares this string to the specified {@code CharSequence}.  The
1295      * result is {@code true} if and only if this {@code String} represents the
1296      * same sequence of char values as the specified sequence. Note that if the
1297      * {@code CharSequence} is a {@code StringBuffer} then the method
1298      * synchronizes on it.
1299      *
1300      * <p>For finer-grained String comparison, refer to
1301      * {@link java.text.Collator}.
1302      *
1303      * @param  cs
1304      *         The sequence to compare this {@code String} against
1305      *
1306      * @return  {@code true} if this {@code String} represents the same
1307      *          sequence of char values as the specified sequence, {@code
1308      *          false} otherwise
1309      *
1310      * @since  1.5
1311      */
contentEquals(CharSequence cs)1312     public boolean contentEquals(CharSequence cs) {
1313         // Argument is a StringBuffer, StringBuilder
1314         if (cs instanceof AbstractStringBuilder) {
1315             if (cs instanceof StringBuffer) {
1316                 synchronized(cs) {
1317                    return nonSyncContentEquals((AbstractStringBuilder)cs);
1318                 }
1319             } else {
1320                 return nonSyncContentEquals((AbstractStringBuilder)cs);
1321             }
1322         }
1323         // Argument is a String
1324         if (cs instanceof String) {
1325             return equals(cs);
1326         }
1327         // Argument is a generic CharSequence
1328         int n = cs.length();
1329         if (n != length()) {
1330             return false;
1331         }
1332         // BEGIN Android-changed: Implement in terms of charAt().
1333         /*
1334         byte[] val = this.value;
1335         if (isLatin1()) {
1336             for (int i = 0; i < n; i++) {
1337                 if ((val[i] & 0xff) != cs.charAt(i)) {
1338                     return false;
1339                 }
1340             }
1341         } else {
1342             if (!StringUTF16.contentEquals(val, cs, n)) {
1343          */
1344         for (int i = 0; i < n; i++) {
1345             if (charAt(i) != cs.charAt(i)) {
1346         // END Android-changed: Implement in terms of charAt().
1347                 return false;
1348             }
1349         }
1350         return true;
1351     }
1352 
1353     /**
1354      * Compares this {@code String} to another {@code String}, ignoring case
1355      * considerations.  Two strings are considered equal ignoring case if they
1356      * are of the same length and corresponding characters in the two strings
1357      * are equal ignoring case.
1358      *
1359      * <p> Two characters {@code c1} and {@code c2} are considered the same
1360      * ignoring case if at least one of the following is true:
1361      * <ul>
1362      *   <li> The two characters are the same (as compared by the
1363      *        {@code ==} operator)
1364      *   <li> Calling {@code Character.toLowerCase(Character.toUpperCase(char))}
1365      *        on each character produces the same result
1366      * </ul>
1367      *
1368      * <p>Note that this method does <em>not</em> take locale into account, and
1369      * will result in unsatisfactory results for certain locales.  The
1370      * {@link java.text.Collator} class provides locale-sensitive comparison.
1371      *
1372      * @param  anotherString
1373      *         The {@code String} to compare this {@code String} against
1374      *
1375      * @return  {@code true} if the argument is not {@code null} and it
1376      *          represents an equivalent {@code String} ignoring case; {@code
1377      *          false} otherwise
1378      *
1379      * @see  #equals(Object)
1380      */
equalsIgnoreCase(String anotherString)1381     public boolean equalsIgnoreCase(String anotherString) {
1382         // Android-added: Cache length() result so it's called once.
1383         final int len = length();
1384         return (this == anotherString) ? true
1385                 : (anotherString != null)
1386                 && (anotherString.length() == len)
1387                 && regionMatches(true, 0, anotherString, 0, len);
1388     }
1389 
1390     /**
1391      * Compares two strings lexicographically.
1392      * The comparison is based on the Unicode value of each character in
1393      * the strings. The character sequence represented by this
1394      * {@code String} object is compared lexicographically to the
1395      * character sequence represented by the argument string. The result is
1396      * a negative integer if this {@code String} object
1397      * lexicographically precedes the argument string. The result is a
1398      * positive integer if this {@code String} object lexicographically
1399      * follows the argument string. The result is zero if the strings
1400      * are equal; {@code compareTo} returns {@code 0} exactly when
1401      * the {@link #equals(Object)} method would return {@code true}.
1402      * <p>
1403      * This is the definition of lexicographic ordering. If two strings are
1404      * different, then either they have different characters at some index
1405      * that is a valid index for both strings, or their lengths are different,
1406      * or both. If they have different characters at one or more index
1407      * positions, let <i>k</i> be the smallest such index; then the string
1408      * whose character at position <i>k</i> has the smaller value, as
1409      * determined by using the {@code <} operator, lexicographically precedes the
1410      * other string. In this case, {@code compareTo} returns the
1411      * difference of the two character values at position {@code k} in
1412      * the two string -- that is, the value:
1413      * <blockquote><pre>
1414      * this.charAt(k)-anotherString.charAt(k)
1415      * </pre></blockquote>
1416      * If there is no index position at which they differ, then the shorter
1417      * string lexicographically precedes the longer string. In this case,
1418      * {@code compareTo} returns the difference of the lengths of the
1419      * strings -- that is, the value:
1420      * <blockquote><pre>
1421      * this.length()-anotherString.length()
1422      * </pre></blockquote>
1423      *
1424      * <p>For finer-grained String comparison, refer to
1425      * {@link java.text.Collator}.
1426      *
1427      * @param   anotherString   the {@code String} to be compared.
1428      * @return  the value {@code 0} if the argument string is equal to
1429      *          this string; a value less than {@code 0} if this string
1430      *          is lexicographically less than the string argument; and a
1431      *          value greater than {@code 0} if this string is
1432      *          lexicographically greater than the string argument.
1433      */
1434     // BEGIN Android-changed: Replace with implementation in runtime to access chars (see above).
1435     /*
1436     public int compareTo(String anotherString) {
1437         byte v1[] = value;
1438         byte v2[] = anotherString.value;
1439         if (coder() == anotherString.coder()) {
1440             return isLatin1() ? StringLatin1.compareTo(v1, v2)
1441                               : StringUTF16.compareTo(v1, v2);
1442         }
1443         return isLatin1() ? StringLatin1.compareToUTF16(v1, v2)
1444                           : StringUTF16.compareToLatin1(v1, v2);
1445      }
1446     */
1447     @FastNative
compareTo(String anotherString)1448     public native int compareTo(String anotherString);
1449     // END Android-changed: Replace with implementation in runtime to access chars (see above).
1450 
1451     /**
1452      * A Comparator that orders {@code String} objects as by
1453      * {@code compareToIgnoreCase}. This comparator is serializable.
1454      * <p>
1455      * Note that this Comparator does <em>not</em> take locale into account,
1456      * and will result in an unsatisfactory ordering for certain locales.
1457      * The {@link java.text.Collator} class provides locale-sensitive comparison.
1458      *
1459      * @see     java.text.Collator
1460      * @since   1.2
1461      */
1462     public static final Comparator<String> CASE_INSENSITIVE_ORDER
1463                                          = new CaseInsensitiveComparator();
1464     private static class CaseInsensitiveComparator
1465             implements Comparator<String>, java.io.Serializable {
1466         // use serialVersionUID from JDK 1.2.2 for interoperability
1467         private static final long serialVersionUID = 8575799808933029326L;
1468 
compare(String s1, String s2)1469         public int compare(String s1, String s2) {
1470             // BEGIN Android-changed: Implement in terms of charAt().
1471             /*
1472             byte v1[] = s1.value;
1473             byte v2[] = s2.value;
1474             if (s1.coder() == s2.coder()) {
1475                 return s1.isLatin1() ? StringLatin1.compareToCI(v1, v2)
1476                                      : StringUTF16.compareToCI(v1, v2);
1477             }
1478             return s1.isLatin1() ? StringLatin1.compareToCI_UTF16(v1, v2)
1479                                  : StringUTF16.compareToCI_Latin1(v1, v2);
1480              */
1481             int n1 = s1.length();
1482             int n2 = s2.length();
1483             int min = Math.min(n1, n2);
1484             for (int i = 0; i < min; i++) {
1485                 char c1 = s1.charAt(i);
1486                 char c2 = s2.charAt(i);
1487                 if (c1 != c2) {
1488                     c1 = Character.toUpperCase(c1);
1489                     c2 = Character.toUpperCase(c2);
1490                     if (c1 != c2) {
1491                         c1 = Character.toLowerCase(c1);
1492                         c2 = Character.toLowerCase(c2);
1493                         if (c1 != c2) {
1494                             // No overflow because of numeric promotion
1495                             return c1 - c2;
1496                         }
1497                     }
1498                 }
1499             }
1500             return n1 - n2;
1501             // END Android-changed: Implement in terms of charAt().
1502         }
1503 
1504         /** Replaces the de-serialized object. */
readResolve()1505         private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
1506     }
1507 
1508     /**
1509      * Compares two strings lexicographically, ignoring case
1510      * differences. This method returns an integer whose sign is that of
1511      * calling {@code compareTo} with normalized versions of the strings
1512      * where case differences have been eliminated by calling
1513      * {@code Character.toLowerCase(Character.toUpperCase(character))} on
1514      * each character.
1515      * <p>
1516      * Note that this method does <em>not</em> take locale into account,
1517      * and will result in an unsatisfactory ordering for certain locales.
1518      * The {@link java.text.Collator} class provides locale-sensitive comparison.
1519      *
1520      * @param   str   the {@code String} to be compared.
1521      * @return  a negative integer, zero, or a positive integer as the
1522      *          specified String is greater than, equal to, or less
1523      *          than this String, ignoring case considerations.
1524      * @see     java.text.Collator
1525      * @since   1.2
1526      */
compareToIgnoreCase(String str)1527     public int compareToIgnoreCase(String str) {
1528         return CASE_INSENSITIVE_ORDER.compare(this, str);
1529     }
1530 
1531     /**
1532      * Tests if two string regions are equal.
1533      * <p>
1534      * A substring of this {@code String} object is compared to a substring
1535      * of the argument other. The result is true if these substrings
1536      * represent identical character sequences. The substring of this
1537      * {@code String} object to be compared begins at index {@code toffset}
1538      * and has length {@code len}. The substring of other to be compared
1539      * begins at index {@code ooffset} and has length {@code len}. The
1540      * result is {@code false} if and only if at least one of the following
1541      * is true:
1542      * <ul><li>{@code toffset} is negative.
1543      * <li>{@code ooffset} is negative.
1544      * <li>{@code toffset+len} is greater than the length of this
1545      * {@code String} object.
1546      * <li>{@code ooffset+len} is greater than the length of the other
1547      * argument.
1548      * <li>There is some nonnegative integer <i>k</i> less than {@code len}
1549      * such that:
1550      * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
1551      * <i>k</i>{@code )}
1552      * </ul>
1553      *
1554      * <p>Note that this method does <em>not</em> take locale into account.  The
1555      * {@link java.text.Collator} class provides locale-sensitive comparison.
1556      *
1557      * @param   toffset   the starting offset of the subregion in this string.
1558      * @param   other     the string argument.
1559      * @param   ooffset   the starting offset of the subregion in the string
1560      *                    argument.
1561      * @param   len       the number of characters to compare.
1562      * @return  {@code true} if the specified subregion of this string
1563      *          exactly matches the specified subregion of the string argument;
1564      *          {@code false} otherwise.
1565      */
regionMatches(int toffset, String other, int ooffset, int len)1566     public boolean regionMatches(int toffset, String other, int ooffset, int len) {
1567         // BEGIN Android-removed: Implement in terms of charAt().
1568         /*
1569         byte tv[] = value;
1570         byte ov[] = other.value;
1571          */
1572         // Note: toffset, ooffset, or len might be near -1>>>1.
1573         if ((ooffset < 0) || (toffset < 0) ||
1574              (toffset > (long)length() - len) ||
1575              (ooffset > (long)other.length() - len)) {
1576             return false;
1577         }
1578         // BEGIN Android-removed: Implement in terms of charAt().
1579         /*
1580         if (coder() == other.coder()) {
1581             if (!isLatin1() && (len > 0)) {
1582                 toffset = toffset << 1;
1583                 ooffset = ooffset << 1;
1584                 len = len << 1;
1585             }
1586             while (len-- > 0) {
1587                 if (tv[toffset++] != ov[ooffset++]) {
1588                     return false;
1589                 }
1590             }
1591         } else {
1592             if (coder() == LATIN1) {
1593                 while (len-- > 0) {
1594                     if (StringLatin1.getChar(tv, toffset++) !=
1595                         StringUTF16.getChar(ov, ooffset++)) {
1596                         return false;
1597                     }
1598                 }
1599             } else {
1600                 while (len-- > 0) {
1601                     if (StringUTF16.getChar(tv, toffset++) !=
1602                         StringLatin1.getChar(ov, ooffset++)) {
1603                         return false;
1604                     }
1605                 }
1606          */
1607         while (len-- > 0) {
1608             if (charAt(toffset++) != other.charAt(ooffset++)) {
1609                 return false;
1610         // END Android-removed: Implement in terms of charAt().
1611             }
1612         }
1613         return true;
1614     }
1615 
1616     /**
1617      * Tests if two string regions are equal.
1618      * <p>
1619      * A substring of this {@code String} object is compared to a substring
1620      * of the argument {@code other}. The result is {@code true} if these
1621      * substrings represent character sequences that are the same, ignoring
1622      * case if and only if {@code ignoreCase} is true. The substring of
1623      * this {@code String} object to be compared begins at index
1624      * {@code toffset} and has length {@code len}. The substring of
1625      * {@code other} to be compared begins at index {@code ooffset} and
1626      * has length {@code len}. The result is {@code false} if and only if
1627      * at least one of the following is true:
1628      * <ul><li>{@code toffset} is negative.
1629      * <li>{@code ooffset} is negative.
1630      * <li>{@code toffset+len} is greater than the length of this
1631      * {@code String} object.
1632      * <li>{@code ooffset+len} is greater than the length of the other
1633      * argument.
1634      * <li>{@code ignoreCase} is {@code false} and there is some nonnegative
1635      * integer <i>k</i> less than {@code len} such that:
1636      * <blockquote><pre>
1637      * this.charAt(toffset+k) != other.charAt(ooffset+k)
1638      * </pre></blockquote>
1639      * <li>{@code ignoreCase} is {@code true} and there is some nonnegative
1640      * integer <i>k</i> less than {@code len} such that:
1641      * <blockquote><pre>
1642      * Character.toLowerCase(Character.toUpperCase(this.charAt(toffset+k))) !=
1643      Character.toLowerCase(Character.toUpperCase(other.charAt(ooffset+k)))
1644      * </pre></blockquote>
1645      * </ul>
1646      *
1647      * <p>Note that this method does <em>not</em> take locale into account,
1648      * and will result in unsatisfactory results for certain locales when
1649      * {@code ignoreCase} is {@code true}.  The {@link java.text.Collator} class
1650      * provides locale-sensitive comparison.
1651      *
1652      * @param   ignoreCase   if {@code true}, ignore case when comparing
1653      *                       characters.
1654      * @param   toffset      the starting offset of the subregion in this
1655      *                       string.
1656      * @param   other        the string argument.
1657      * @param   ooffset      the starting offset of the subregion in the string
1658      *                       argument.
1659      * @param   len          the number of characters to compare.
1660      * @return  {@code true} if the specified subregion of this string
1661      *          matches the specified subregion of the string argument;
1662      *          {@code false} otherwise. Whether the matching is exact
1663      *          or case insensitive depends on the {@code ignoreCase}
1664      *          argument.
1665      */
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)1666     public boolean regionMatches(boolean ignoreCase, int toffset,
1667             String other, int ooffset, int len) {
1668         if (!ignoreCase) {
1669             return regionMatches(toffset, other, ooffset, len);
1670         }
1671         // Note: toffset, ooffset, or len might be near -1>>>1.
1672         if ((ooffset < 0) || (toffset < 0)
1673                 || (toffset > (long)length() - len)
1674                 || (ooffset > (long)other.length() - len)) {
1675             return false;
1676         }
1677         // BEGIN Android-changed: Implement in terms of charAt().
1678         /*
1679         byte tv[] = value;
1680         byte ov[] = other.value;
1681         if (coder() == other.coder()) {
1682             return isLatin1()
1683               ? StringLatin1.regionMatchesCI(tv, toffset, ov, ooffset, len)
1684               : StringUTF16.regionMatchesCI(tv, toffset, ov, ooffset, len);
1685         }
1686         return isLatin1()
1687               ? StringLatin1.regionMatchesCI_UTF16(tv, toffset, ov, ooffset, len)
1688               : StringUTF16.regionMatchesCI_Latin1(tv, toffset, ov, ooffset, len);
1689          */
1690         while (len-- > 0) {
1691             char c1 = charAt(toffset++);
1692             char c2 = other.charAt(ooffset++);
1693             if (c1 == c2) {
1694                 continue;
1695             }
1696             if (ignoreCase) {
1697                 // If characters don't match but case may be ignored,
1698                 // try converting both characters to uppercase.
1699                 // If the results match, then the comparison scan should
1700                 // continue.
1701                 char u1 = Character.toUpperCase(c1);
1702                 char u2 = Character.toUpperCase(c2);
1703                 if (u1 == u2) {
1704                     continue;
1705                 }
1706                 // Unfortunately, conversion to uppercase does not work properly
1707                 // for the Georgian alphabet, which has strange rules about case
1708                 // conversion.  So we need to make one last check before
1709                 // exiting.
1710                 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
1711                     continue;
1712                 }
1713             }
1714             return false;
1715         }
1716         return true;
1717         // END Android-changed: Implement in terms of charAt().
1718     }
1719 
1720     /**
1721      * Tests if the substring of this string beginning at the
1722      * specified index starts with the specified prefix.
1723      *
1724      * @param   prefix    the prefix.
1725      * @param   toffset   where to begin looking in this string.
1726      * @return  {@code true} if the character sequence represented by the
1727      *          argument is a prefix of the substring of this object starting
1728      *          at index {@code toffset}; {@code false} otherwise.
1729      *          The result is {@code false} if {@code toffset} is
1730      *          negative or greater than the length of this
1731      *          {@code String} object; otherwise the result is the same
1732      *          as the result of the expression
1733      *          <pre>
1734      *          this.substring(toffset).startsWith(prefix)
1735      *          </pre>
1736      */
startsWith(String prefix, int toffset)1737     public boolean startsWith(String prefix, int toffset) {
1738         // Android-added: Cache length() result so it's called once.
1739         int pc = prefix.length();
1740         // Note: toffset might be near -1>>>1.
1741         if (toffset < 0 || toffset > length() - pc) {
1742             return false;
1743         }
1744         // BEGIN Android-changed: Implement in terms of charAt().
1745         /*
1746         byte ta[] = value;
1747         byte pa[] = prefix.value;
1748         int po = 0;
1749         int pc = pa.length;
1750         if (coder() == prefix.coder()) {
1751             int to = isLatin1() ? toffset : toffset << 1;
1752             while (po < pc) {
1753                 if (ta[to++] != pa[po++]) {
1754                     return false;
1755                 }
1756             }
1757         } else {
1758             if (isLatin1()) {  // && pcoder == UTF16
1759                 return false;
1760             }
1761             // coder == UTF16 && pcoder == LATIN1)
1762             while (po < pc) {
1763                 if (StringUTF16.getChar(ta, toffset++) != (pa[po++] & 0xff)) {
1764                     return false;
1765                }
1766             }
1767          */
1768         int po = 0;
1769         while (--pc >= 0) {
1770             if (charAt(toffset++) != prefix.charAt(po++)) {
1771                 return false;
1772             }
1773         // END Android-changed: Implement in terms of charAt().
1774         }
1775         return true;
1776     }
1777 
1778     /**
1779      * Tests if this string starts with the specified prefix.
1780      *
1781      * @param   prefix   the prefix.
1782      * @return  {@code true} if the character sequence represented by the
1783      *          argument is a prefix of the character sequence represented by
1784      *          this string; {@code false} otherwise.
1785      *          Note also that {@code true} will be returned if the
1786      *          argument is an empty string or is equal to this
1787      *          {@code String} object as determined by the
1788      *          {@link #equals(Object)} method.
1789      * @since   1.0
1790      */
startsWith(String prefix)1791     public boolean startsWith(String prefix) {
1792         return startsWith(prefix, 0);
1793     }
1794 
1795     /**
1796      * Tests if this string ends with the specified suffix.
1797      *
1798      * @param   suffix   the suffix.
1799      * @return  {@code true} if the character sequence represented by the
1800      *          argument is a suffix of the character sequence represented by
1801      *          this object; {@code false} otherwise. Note that the
1802      *          result will be {@code true} if the argument is the
1803      *          empty string or is equal to this {@code String} object
1804      *          as determined by the {@link #equals(Object)} method.
1805      */
endsWith(String suffix)1806     public boolean endsWith(String suffix) {
1807         return startsWith(suffix, length() - suffix.length());
1808     }
1809 
1810     /**
1811      * Returns a hash code for this string. The hash code for a
1812      * {@code String} object is computed as
1813      * <blockquote><pre>
1814      * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
1815      * </pre></blockquote>
1816      * using {@code int} arithmetic, where {@code s[i]} is the
1817      * <i>i</i>th character of the string, {@code n} is the length of
1818      * the string, and {@code ^} indicates exponentiation.
1819      * (The hash value of the empty string is zero.)
1820      *
1821      * @return  a hash code value for this object.
1822      */
hashCode()1823     public int hashCode() {
1824         int h = hash;
1825         // BEGIN Android-changed: Implement in terms of charAt().
1826         /*
1827         if (h == 0 && value.length > 0) {
1828             hash = h = isLatin1() ? StringLatin1.hashCode(value)
1829                                   : StringUTF16.hashCode(value);
1830          */
1831         final int len = length();
1832         if (h == 0 && len > 0) {
1833             for (int i = 0; i < len; i++) {
1834                 h = 31 * h + charAt(i);
1835             }
1836             hash = h;
1837         // END Android-changed: Implement in terms of charAt().
1838         }
1839         return h;
1840     }
1841 
1842     /**
1843      * Returns the index within this string of the first occurrence of
1844      * the specified character. If a character with value
1845      * {@code ch} occurs in the character sequence represented by
1846      * this {@code String} object, then the index (in Unicode
1847      * code units) of the first such occurrence is returned. For
1848      * values of {@code ch} in the range from 0 to 0xFFFF
1849      * (inclusive), this is the smallest value <i>k</i> such that:
1850      * <blockquote><pre>
1851      * this.charAt(<i>k</i>) == ch
1852      * </pre></blockquote>
1853      * is true. For other values of {@code ch}, it is the
1854      * smallest value <i>k</i> such that:
1855      * <blockquote><pre>
1856      * this.codePointAt(<i>k</i>) == ch
1857      * </pre></blockquote>
1858      * is true. In either case, if no such character occurs in this
1859      * string, then {@code -1} is returned.
1860      *
1861      * @param   ch   a character (Unicode code point).
1862      * @return  the index of the first occurrence of the character in the
1863      *          character sequence represented by this object, or
1864      *          {@code -1} if the character does not occur.
1865      */
indexOf(int ch)1866     public int indexOf(int ch) {
1867         return indexOf(ch, 0);
1868     }
1869 
1870     /**
1871      * Returns the index within this string of the first occurrence of the
1872      * specified character, starting the search at the specified index.
1873      * <p>
1874      * If a character with value {@code ch} occurs in the
1875      * character sequence represented by this {@code String}
1876      * object at an index no smaller than {@code fromIndex}, then
1877      * the index of the first such occurrence is returned. For values
1878      * of {@code ch} in the range from 0 to 0xFFFF (inclusive),
1879      * this is the smallest value <i>k</i> such that:
1880      * <blockquote><pre>
1881      * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex)
1882      * </pre></blockquote>
1883      * is true. For other values of {@code ch}, it is the
1884      * smallest value <i>k</i> such that:
1885      * <blockquote><pre>
1886      * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex)
1887      * </pre></blockquote>
1888      * is true. In either case, if no such character occurs in this
1889      * string at or after position {@code fromIndex}, then
1890      * {@code -1} is returned.
1891      *
1892      * <p>
1893      * There is no restriction on the value of {@code fromIndex}. If it
1894      * is negative, it has the same effect as if it were zero: this entire
1895      * string may be searched. If it is greater than the length of this
1896      * string, it has the same effect as if it were equal to the length of
1897      * this string: {@code -1} is returned.
1898      *
1899      * <p>All indices are specified in {@code char} values
1900      * (Unicode code units).
1901      *
1902      * @param   ch          a character (Unicode code point).
1903      * @param   fromIndex   the index to start the search from.
1904      * @return  the index of the first occurrence of the character in the
1905      *          character sequence represented by this object that is greater
1906      *          than or equal to {@code fromIndex}, or {@code -1}
1907      *          if the character does not occur.
1908      */
indexOf(int ch, int fromIndex)1909     public int indexOf(int ch, int fromIndex) {
1910     // BEGIN Android-changed: Implement in terms of charAt().
1911         /*
1912         return isLatin1() ? StringLatin1.indexOf(value, ch, fromIndex)
1913                           : StringUTF16.indexOf(value, ch, fromIndex);
1914          */
1915         final int max = length();
1916         if (fromIndex < 0) {
1917             fromIndex = 0;
1918         } else if (fromIndex >= max) {
1919             // Note: fromIndex might be near -1>>>1.
1920             return -1;
1921         }
1922 
1923         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
1924             // handle most cases here (ch is a BMP code point or a
1925             // negative value (invalid code point))
1926             for (int i = fromIndex; i < max; i++) {
1927                 if (charAt(i) == ch) {
1928                     return i;
1929                 }
1930             }
1931             return -1;
1932         } else {
1933             return indexOfSupplementary(ch, fromIndex);
1934         }
1935     }
1936 
1937     /**
1938      * Handles (rare) calls of indexOf with a supplementary character.
1939      */
indexOfSupplementary(int ch, int fromIndex)1940     private int indexOfSupplementary(int ch, int fromIndex) {
1941         if (Character.isValidCodePoint(ch)) {
1942             final char hi = Character.highSurrogate(ch);
1943             final char lo = Character.lowSurrogate(ch);
1944             final int max = length() - 1;
1945             for (int i = fromIndex; i < max; i++) {
1946                 if (charAt(i) == hi && charAt(i + 1) == lo) {
1947                     return i;
1948                 }
1949             }
1950         }
1951         return -1;
1952     // END Android-changed: Implement in terms of charAt().
1953     }
1954 
1955     /**
1956      * Returns the index within this string of the last occurrence of
1957      * the specified character. For values of {@code ch} in the
1958      * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
1959      * units) returned is the largest value <i>k</i> such that:
1960      * <blockquote><pre>
1961      * this.charAt(<i>k</i>) == ch
1962      * </pre></blockquote>
1963      * is true. For other values of {@code ch}, it is the
1964      * largest value <i>k</i> such that:
1965      * <blockquote><pre>
1966      * this.codePointAt(<i>k</i>) == ch
1967      * </pre></blockquote>
1968      * is true.  In either case, if no such character occurs in this
1969      * string, then {@code -1} is returned.  The
1970      * {@code String} is searched backwards starting at the last
1971      * character.
1972      *
1973      * @param   ch   a character (Unicode code point).
1974      * @return  the index of the last occurrence of the character in the
1975      *          character sequence represented by this object, or
1976      *          {@code -1} if the character does not occur.
1977      */
lastIndexOf(int ch)1978     public int lastIndexOf(int ch) {
1979         return lastIndexOf(ch, length() - 1);
1980     }
1981 
1982     /**
1983      * Returns the index within this string of the last occurrence of
1984      * the specified character, searching backward starting at the
1985      * specified index. For values of {@code ch} in the range
1986      * from 0 to 0xFFFF (inclusive), the index returned is the largest
1987      * value <i>k</i> such that:
1988      * <blockquote><pre>
1989      * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex)
1990      * </pre></blockquote>
1991      * is true. For other values of {@code ch}, it is the
1992      * largest value <i>k</i> such that:
1993      * <blockquote><pre>
1994      * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex)
1995      * </pre></blockquote>
1996      * is true. In either case, if no such character occurs in this
1997      * string at or before position {@code fromIndex}, then
1998      * {@code -1} is returned.
1999      *
2000      * <p>All indices are specified in {@code char} values
2001      * (Unicode code units).
2002      *
2003      * @param   ch          a character (Unicode code point).
2004      * @param   fromIndex   the index to start the search from. There is no
2005      *          restriction on the value of {@code fromIndex}. If it is
2006      *          greater than or equal to the length of this string, it has
2007      *          the same effect as if it were equal to one less than the
2008      *          length of this string: this entire string may be searched.
2009      *          If it is negative, it has the same effect as if it were -1:
2010      *          -1 is returned.
2011      * @return  the index of the last occurrence of the character in the
2012      *          character sequence represented by this object that is less
2013      *          than or equal to {@code fromIndex}, or {@code -1}
2014      *          if the character does not occur before that point.
2015      */
lastIndexOf(int ch, int fromIndex)2016     public int lastIndexOf(int ch, int fromIndex) {
2017     // BEGIN Android-changed: Implement in terms of charAt().
2018         /*
2019         return isLatin1() ? StringLatin1.lastIndexOf(value, ch, fromIndex)
2020                           : StringUTF16.lastIndexOf(value, ch, fromIndex);
2021          */
2022         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
2023             // handle most cases here (ch is a BMP code point or a
2024             // negative value (invalid code point))
2025             int i = Math.min(fromIndex, length() - 1);
2026             for (; i >= 0; i--) {
2027                 if (charAt(i) == ch) {
2028                     return i;
2029                 }
2030             }
2031             return -1;
2032         } else {
2033             return lastIndexOfSupplementary(ch, fromIndex);
2034         }
2035     }
2036 
2037     /**
2038      * Handles (rare) calls of lastIndexOf with a supplementary character.
2039      */
lastIndexOfSupplementary(int ch, int fromIndex)2040     private int lastIndexOfSupplementary(int ch, int fromIndex) {
2041         if (Character.isValidCodePoint(ch)) {
2042             char hi = Character.highSurrogate(ch);
2043             char lo = Character.lowSurrogate(ch);
2044             int i = Math.min(fromIndex, length() - 2);
2045             for (; i >= 0; i--) {
2046                 if (charAt(i) == hi && charAt(i + 1) == lo) {
2047                     return i;
2048                 }
2049             }
2050         }
2051         return -1;
2052     // END Android-changed: Implement in terms of charAt().
2053     }
2054 
2055     /**
2056      * Returns the index within this string of the first occurrence of the
2057      * specified substring.
2058      *
2059      * <p>The returned index is the smallest value {@code k} for which:
2060      * <pre>{@code
2061      * this.startsWith(str, k)
2062      * }</pre>
2063      * If no such value of {@code k} exists, then {@code -1} is returned.
2064      *
2065      * @param   str   the substring to search for.
2066      * @return  the index of the first occurrence of the specified substring,
2067      *          or {@code -1} if there is no such occurrence.
2068      */
indexOf(String str)2069     public int indexOf(String str) {
2070         // BEGIN Android-changed: Implement with indexOf() method that takes String parameters.
2071         /*
2072         if (coder() == str.coder()) {
2073             return isLatin1() ? StringLatin1.indexOf(value, str.value)
2074                               : StringUTF16.indexOf(value, str.value);
2075         }
2076         if (coder() == LATIN1) {  // str.coder == UTF16
2077             return -1;
2078         }
2079         return StringUTF16.indexOfLatin1(value, str.value);
2080          */
2081         return indexOf(str, 0);
2082         // END Android-changed: Implement with indexOf() method that takes String parameters.
2083     }
2084 
2085     /**
2086      * Returns the index within this string of the first occurrence of the
2087      * specified substring, starting at the specified index.
2088      *
2089      * <p>The returned index is the smallest value {@code k} for which:
2090      * <pre>{@code
2091      *     k >= Math.min(fromIndex, this.length()) &&
2092      *                   this.startsWith(str, k)
2093      * }</pre>
2094      * If no such value of {@code k} exists, then {@code -1} is returned.
2095      *
2096      * @param   str         the substring to search for.
2097      * @param   fromIndex   the index from which to start the search.
2098      * @return  the index of the first occurrence of the specified substring,
2099      *          starting at the specified index,
2100      *          or {@code -1} if there is no such occurrence.
2101      */
indexOf(String str, int fromIndex)2102     public int indexOf(String str, int fromIndex) {
2103         // BEGIN Android-changed: Implement with indexOf() method that takes String parameters.
2104         /*
2105         return indexOf(value, coder(), length(), str, fromIndex);
2106          */
2107         return indexOf(this, str, fromIndex);
2108         // END Android-changed: Implement with indexOf() method that takes String parameters.
2109     }
2110 
2111     // BEGIN Android-added: Private static indexOf method that takes String parameters.
2112     // The use of length(), charAt(), etc. makes it more efficient for compressed strings.
2113     /**
2114      * The source is the string being searched, and the target is the string being searched for.
2115      *
2116      * @param   source       the characters being searched.
2117      * @param   target       the characters being searched for.
2118      * @param   fromIndex    the index to begin searching from.
2119      */
indexOf(String source, String target, int fromIndex)2120     private static int indexOf(String source, String target, int fromIndex) {
2121         final int sourceLength = source.length();
2122         final int targetLength = target.length();
2123         if (fromIndex >= sourceLength) {
2124             return (targetLength == 0 ? sourceLength : -1);
2125         }
2126         if (fromIndex < 0) {
2127             fromIndex = 0;
2128         }
2129         if (targetLength == 0) {
2130             return fromIndex;
2131         }
2132 
2133         char first = target.charAt(0);
2134         int max = (sourceLength - targetLength);
2135 
2136         for (int i = fromIndex; i <= max; i++) {
2137             /* Look for first character. */
2138             if (source.charAt(i)!= first) {
2139                 while (++i <= max && source.charAt(i) != first);
2140             }
2141 
2142             /* Found first character, now look at the rest of v2 */
2143             if (i <= max) {
2144                 int j = i + 1;
2145                 int end = j + targetLength - 1;
2146                 for (int k = 1; j < end && source.charAt(j)
2147                          == target.charAt(k); j++, k++);
2148 
2149                 if (j == end) {
2150                     /* Found whole string. */
2151                     return i;
2152                 }
2153             }
2154         }
2155         return -1;
2156     }
2157     // END Android-added: Private static indexOf method that takes String parameters.
2158 
2159     /**
2160      * Code shared by String and AbstractStringBuilder to do searches. The
2161      * source is the character array being searched, and the target
2162      * is the string being searched for.
2163      *
2164      * @param   source       the characters being searched.
2165      * @param   sourceOffset offset of the source string.
2166      * @param   sourceCount  count of the source string.
2167      * @param   target       the characters being searched for.
2168      * @param   fromIndex    the index to begin searching from.
2169      */
indexOf(char[] source, int sourceOffset, int sourceCount, String target, int fromIndex)2170     static int indexOf(char[] source, int sourceOffset, int sourceCount,
2171             String target, int fromIndex) {
2172         return indexOf(source, sourceOffset, sourceCount,
2173                        target.toCharArray(), 0, target.length(),
2174                        fromIndex);
2175     }
2176 
2177     /**
2178      * Code shared by String and StringBuffer to do searches. The
2179      * source is the character array being searched, and the target
2180      * is the string being searched for.
2181      *
2182      * @param   source       the characters being searched.
2183      * @param   sourceOffset offset of the source string.
2184      * @param   sourceCount  count of the source string.
2185      * @param   target       the characters being searched for.
2186      * @param   targetOffset offset of the target string.
2187      * @param   targetCount  count of the target string.
2188      * @param   fromIndex    the index to begin searching from.
2189      */
indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex)2190     static int indexOf(char[] source, int sourceOffset, int sourceCount,
2191             char[] target, int targetOffset, int targetCount,
2192             int fromIndex) {
2193         if (fromIndex >= sourceCount) {
2194             return (targetCount == 0 ? sourceCount : -1);
2195         }
2196         if (fromIndex < 0) {
2197             fromIndex = 0;
2198         }
2199         if (targetCount == 0) {
2200             return fromIndex;
2201         }
2202 
2203         char first = target[targetOffset];
2204         int max = sourceOffset + (sourceCount - targetCount);
2205 
2206         for (int i = sourceOffset + fromIndex; i <= max; i++) {
2207             /* Look for first character. */
2208             if (source[i] != first) {
2209                 while (++i <= max && source[i] != first);
2210             }
2211 
2212             /* Found first character, now look at the rest of v2 */
2213             if (i <= max) {
2214                 int j = i + 1;
2215                 int end = j + targetCount - 1;
2216                 for (int k = targetOffset + 1; j < end && source[j]
2217                         == target[k]; j++, k++);
2218 
2219                 if (j == end) {
2220                     /* Found whole string. */
2221                     return i - sourceOffset;
2222                 }
2223             }
2224         }
2225         return -1;
2226     }
2227 
2228     /**
2229      * Returns the index within this string of the last occurrence of the
2230      * specified substring.  The last occurrence of the empty string ""
2231      * is considered to occur at the index value {@code this.length()}.
2232      *
2233      * <p>The returned index is the largest value {@code k} for which:
2234      * <pre>{@code
2235      * this.startsWith(str, k)
2236      * }</pre>
2237      * If no such value of {@code k} exists, then {@code -1} is returned.
2238      *
2239      * @param   str   the substring to search for.
2240      * @return  the index of the last occurrence of the specified substring,
2241      *          or {@code -1} if there is no such occurrence.
2242      */
lastIndexOf(String str)2243     public int lastIndexOf(String str) {
2244         return lastIndexOf(str, length());
2245     }
2246 
2247     /**
2248      * Returns the index within this string of the last occurrence of the
2249      * specified substring, searching backward starting at the specified index.
2250      *
2251      * <p>The returned index is the largest value {@code k} for which:
2252      * <pre>{@code
2253      *     k <= Math.min(fromIndex, this.length()) &&
2254      *                   this.startsWith(str, k)
2255      * }</pre>
2256      * If no such value of {@code k} exists, then {@code -1} is returned.
2257      *
2258      * @param   str         the substring to search for.
2259      * @param   fromIndex   the index to start the search from.
2260      * @return  the index of the last occurrence of the specified substring,
2261      *          searching backward from the specified index,
2262      *          or {@code -1} if there is no such occurrence.
2263      */
lastIndexOf(String str, int fromIndex)2264     public int lastIndexOf(String str, int fromIndex) {
2265         // BEGIN Android-changed: Implement with static lastIndexOf() that takes String parameters.
2266         /*
2267         return lastIndexOf(value, coder(), length(), str, fromIndex);
2268          */
2269         return lastIndexOf(this, str, fromIndex);
2270         // END Android-changed: Implement with static lastIndexOf() that takes String parameters.
2271     }
2272 
2273     // BEGIN Android-added: Private static lastIndexOf method that takes String parameters.
2274     // The use of length(), charAt(), etc. makes it more efficient for compressed strings.
2275     /**
2276      * The source is the string being searched, and the target is the string being searched for.
2277      *
2278      * @param   source       the characters being searched.
2279      * @param   target       the characters being searched for.
2280      * @param   fromIndex    the index to begin searching from.
2281      */
lastIndexOf(String source, String target, int fromIndex)2282     private static int lastIndexOf(String source, String target, int fromIndex) {
2283         /*
2284          * Check arguments; return immediately where possible. For
2285          * consistency, don't check for null str.
2286          */
2287         final int sourceLength = source.length();
2288         final int targetLength = target.length();
2289         int rightIndex = sourceLength - targetLength;
2290         if (fromIndex < 0) {
2291             return -1;
2292         }
2293         if (fromIndex > rightIndex) {
2294             fromIndex = rightIndex;
2295         }
2296         /* Empty string always matches. */
2297         if (targetLength == 0) {
2298             return fromIndex;
2299         }
2300 
2301         int strLastIndex = targetLength - 1;
2302         char strLastChar = target.charAt(strLastIndex);
2303         int min = targetLength - 1;
2304         int i = min + fromIndex;
2305 
2306         startSearchForLastChar:
2307         while (true) {
2308             while (i >= min && source.charAt(i) != strLastChar) {
2309                 i--;
2310             }
2311             if (i < min) {
2312                 return -1;
2313             }
2314             int j = i - 1;
2315             int start = j - (targetLength - 1);
2316             int k = strLastIndex - 1;
2317 
2318             while (j > start) {
2319                 if (source.charAt(j--) != target.charAt(k--)) {
2320                     i--;
2321                     continue startSearchForLastChar;
2322                 }
2323             }
2324             return start + 1;
2325         }
2326     }
2327     // END Android-added: Private static lastIndexOf method that takes String parameters.
2328 
2329     /**
2330      * Code shared by String and AbstractStringBuilder to do searches. The
2331      * source is the character array being searched, and the target
2332      * is the string being searched for.
2333      *
2334      * @param   source       the characters being searched.
2335      * @param   sourceOffset offset of the source string.
2336      * @param   sourceCount  count of the source string.
2337      * @param   target       the characters being searched for.
2338      * @param   fromIndex    the index to begin searching from.
2339      */
lastIndexOf(char[] source, int sourceOffset, int sourceCount, String target, int fromIndex)2340     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
2341             String target, int fromIndex) {
2342         return lastIndexOf(source, sourceOffset, sourceCount,
2343                        target.toCharArray(), 0, target.length(),
2344                        fromIndex);
2345     }
2346 
2347     /**
2348      * Code shared by String and StringBuffer to do searches. The
2349      * source is the character array being searched, and the target
2350      * is the string being searched for.
2351      *
2352      * @param   source       the characters being searched.
2353      * @param   sourceOffset offset of the source string.
2354      * @param   sourceCount  count of the source string.
2355      * @param   target       the characters being searched for.
2356      * @param   targetOffset offset of the target string.
2357      * @param   targetCount  count of the target string.
2358      * @param   fromIndex    the index to begin searching from.
2359      */
lastIndexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex)2360     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
2361             char[] target, int targetOffset, int targetCount,
2362             int fromIndex) {
2363         /*
2364          * Check arguments; return immediately where possible. For
2365          * consistency, don't check for null str.
2366          */
2367         int rightIndex = sourceCount - targetCount;
2368         if (fromIndex < 0) {
2369             return -1;
2370         }
2371         if (fromIndex > rightIndex) {
2372             fromIndex = rightIndex;
2373         }
2374         /* Empty string always matches. */
2375         if (targetCount == 0) {
2376             return fromIndex;
2377         }
2378 
2379         int strLastIndex = targetOffset + targetCount - 1;
2380         char strLastChar = target[strLastIndex];
2381         int min = sourceOffset + targetCount - 1;
2382         int i = min + fromIndex;
2383 
2384     startSearchForLastChar:
2385         while (true) {
2386             while (i >= min && source[i] != strLastChar) {
2387                 i--;
2388             }
2389             if (i < min) {
2390                 return -1;
2391             }
2392             int j = i - 1;
2393             int start = j - (targetCount - 1);
2394             int k = strLastIndex - 1;
2395 
2396             while (j > start) {
2397                 if (source[j--] != target[k--]) {
2398                     i--;
2399                     continue startSearchForLastChar;
2400                 }
2401             }
2402             return start - sourceOffset + 1;
2403         }
2404     }
2405 
2406     /**
2407      * Returns a string that is a substring of this string. The
2408      * substring begins with the character at the specified index and
2409      * extends to the end of this string. <p>
2410      * Examples:
2411      * <blockquote><pre>
2412      * "unhappy".substring(2) returns "happy"
2413      * "Harbison".substring(3) returns "bison"
2414      * "emptiness".substring(9) returns "" (an empty string)
2415      * </pre></blockquote>
2416      *
2417      * @param      beginIndex   the beginning index, inclusive.
2418      * @return     the specified substring.
2419      * @exception  IndexOutOfBoundsException  if
2420      *             {@code beginIndex} is negative or larger than the
2421      *             length of this {@code String} object.
2422      */
substring(int beginIndex)2423     public String substring(int beginIndex) {
2424         if (beginIndex < 0) {
2425             throw new StringIndexOutOfBoundsException(this, beginIndex);
2426         }
2427         int subLen = length() - beginIndex;
2428         if (subLen < 0) {
2429             throw new StringIndexOutOfBoundsException(this, beginIndex);
2430         }
2431         if (beginIndex == 0) {
2432             return this;
2433         }
2434         // BEGIN Android-changed: Use native fastSubstring instead of String constructor.
2435         /*
2436         return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
2437                           : StringUTF16.newString(value, beginIndex, subLen);
2438          */
2439         return fastSubstring(beginIndex, subLen);
2440         // END Android-changed: Use native fastSubstring instead of String constructor.
2441     }
2442 
2443     /**
2444      * Returns a string that is a substring of this string. The
2445      * substring begins at the specified {@code beginIndex} and
2446      * extends to the character at index {@code endIndex - 1}.
2447      * Thus the length of the substring is {@code endIndex-beginIndex}.
2448      * <p>
2449      * Examples:
2450      * <blockquote><pre>
2451      * "hamburger".substring(4, 8) returns "urge"
2452      * "smiles".substring(1, 5) returns "mile"
2453      * </pre></blockquote>
2454      *
2455      * @param      beginIndex   the beginning index, inclusive.
2456      * @param      endIndex     the ending index, exclusive.
2457      * @return     the specified substring.
2458      * @exception  IndexOutOfBoundsException  if the
2459      *             {@code beginIndex} is negative, or
2460      *             {@code endIndex} is larger than the length of
2461      *             this {@code String} object, or
2462      *             {@code beginIndex} is larger than
2463      *             {@code endIndex}.
2464      */
substring(int beginIndex, int endIndex)2465     public String substring(int beginIndex, int endIndex) {
2466         int length = length();
2467         checkBoundsBeginEnd(beginIndex, endIndex, length);
2468         int subLen = endIndex - beginIndex;
2469         if (beginIndex == 0 && endIndex == length) {
2470             return this;
2471         }
2472 
2473         // BEGIN Android-changed: Use native fastSubstring instead of String constructor.
2474         /*
2475         return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
2476                           : StringUTF16.newString(value, beginIndex, subLen);
2477          */
2478         return fastSubstring(beginIndex, subLen);
2479         // END Android-changed: Use native fastSubstring instead of String constructor.
2480     }
2481 
2482     // BEGIN Android-added: Native method to access char storage managed by runtime.
2483     @FastNative
fastSubstring(int start, int length)2484     private native String fastSubstring(int start, int length);
2485     // END Android-added: Native method to access char storage managed by runtime.
2486 
2487     /**
2488      * Returns a character sequence that is a subsequence of this sequence.
2489      *
2490      * <p> An invocation of this method of the form
2491      *
2492      * <blockquote><pre>
2493      * str.subSequence(begin,&nbsp;end)</pre></blockquote>
2494      *
2495      * behaves in exactly the same way as the invocation
2496      *
2497      * <blockquote><pre>
2498      * str.substring(begin,&nbsp;end)</pre></blockquote>
2499      *
2500      * @apiNote
2501      * This method is defined so that the {@code String} class can implement
2502      * the {@link CharSequence} interface.
2503      *
2504      * @param   beginIndex   the begin index, inclusive.
2505      * @param   endIndex     the end index, exclusive.
2506      * @return  the specified subsequence.
2507      *
2508      * @throws  IndexOutOfBoundsException
2509      *          if {@code beginIndex} or {@code endIndex} is negative,
2510      *          if {@code endIndex} is greater than {@code length()},
2511      *          or if {@code beginIndex} is greater than {@code endIndex}
2512      *
2513      * @since 1.4
2514      * @spec JSR-51
2515      */
subSequence(int beginIndex, int endIndex)2516     public CharSequence subSequence(int beginIndex, int endIndex) {
2517         return this.substring(beginIndex, endIndex);
2518     }
2519 
2520     /**
2521      * Concatenates the specified string to the end of this string.
2522      * <p>
2523      * If the length of the argument string is {@code 0}, then this
2524      * {@code String} object is returned. Otherwise, a
2525      * {@code String} object is returned that represents a character
2526      * sequence that is the concatenation of the character sequence
2527      * represented by this {@code String} object and the character
2528      * sequence represented by the argument string.<p>
2529      * Examples:
2530      * <blockquote><pre>
2531      * "cares".concat("s") returns "caress"
2532      * "to".concat("get").concat("her") returns "together"
2533      * </pre></blockquote>
2534      *
2535      * @param   str   the {@code String} that is concatenated to the end
2536      *                of this {@code String}.
2537      * @return  a string that represents the concatenation of this object's
2538      *          characters followed by the string argument's characters.
2539      */
2540     // BEGIN Android-changed: Replace with implementation in runtime to access chars (see above).
2541     /*
2542     public String concat(String str) {
2543         if (str.isEmpty()) {
2544             return this;
2545         }
2546         if (coder() == str.coder()) {
2547             byte[] val = this.value;
2548             byte[] oval = str.value;
2549             int len = val.length + oval.length;
2550             byte[] buf = Arrays.copyOf(val, len);
2551             System.arraycopy(oval, 0, buf, val.length, oval.length);
2552             return new String(buf, coder);
2553         }
2554         int len = length();
2555         int olen = str.length();
2556         byte[] buf = StringUTF16.newBytesFor(len + olen);
2557         getBytes(buf, 0, UTF16);
2558         str.getBytes(buf, len, UTF16);
2559         return new String(buf, UTF16);
2560     }
2561     */
2562     @FastNative
concat(String str)2563     public native String concat(String str);
2564     // END Android-changed: Replace with implementation in runtime to access chars (see above).
2565 
2566     /**
2567      * Returns a string resulting from replacing all occurrences of
2568      * {@code oldChar} in this string with {@code newChar}.
2569      * <p>
2570      * If the character {@code oldChar} does not occur in the
2571      * character sequence represented by this {@code String} object,
2572      * then a reference to this {@code String} object is returned.
2573      * Otherwise, a {@code String} object is returned that
2574      * represents a character sequence identical to the character sequence
2575      * represented by this {@code String} object, except that every
2576      * occurrence of {@code oldChar} is replaced by an occurrence
2577      * of {@code newChar}.
2578      * <p>
2579      * Examples:
2580      * <blockquote><pre>
2581      * "mesquite in your cellar".replace('e', 'o')
2582      *         returns "mosquito in your collar"
2583      * "the war of baronets".replace('r', 'y')
2584      *         returns "the way of bayonets"
2585      * "sparring with a purple porpoise".replace('p', 't')
2586      *         returns "starring with a turtle tortoise"
2587      * "JonL".replace('q', 'x') returns "JonL" (no change)
2588      * </pre></blockquote>
2589      *
2590      * @param   oldChar   the old character.
2591      * @param   newChar   the new character.
2592      * @return  a string derived from this string by replacing every
2593      *          occurrence of {@code oldChar} with {@code newChar}.
2594      */
replace(char oldChar, char newChar)2595     public String replace(char oldChar, char newChar) {
2596         // BEGIN Android-changed: Replace with implementation using native doReplace method.
2597         if (oldChar != newChar) {
2598             /*
2599             String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar)
2600                                     : StringUTF16.replace(value, oldChar, newChar);
2601             if (ret != null) {
2602                 return ret;
2603             }
2604             */
2605             final int len = length();
2606             for (int i = 0; i < len; ++i) {
2607                 if (charAt(i) == oldChar) {
2608                     return doReplace(oldChar, newChar);
2609                 }
2610             }
2611         }
2612         // END Android-changed: Replace with implementation using native doReplace method.
2613         return this;
2614     }
2615 
2616     // BEGIN Android-added: Native method to access char storage managed by runtime.
2617     // Implementation of replace(char oldChar, char newChar) called when we found a match.
2618     @FastNative
doReplace(char oldChar, char newChar)2619     private native String doReplace(char oldChar, char newChar);
2620     // END Android-added: Native method to access char storage managed by runtime.
2621 
2622     /**
2623      * Tells whether or not this string matches the given <a
2624      * href="../util/regex/Pattern.html#sum">regular expression</a>.
2625      *
2626      * <p> An invocation of this method of the form
2627      * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
2628      * same result as the expression
2629      *
2630      * <blockquote>
2631      * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence)
2632      * matches(<i>regex</i>, <i>str</i>)}
2633      * </blockquote>
2634      *
2635      * @param   regex
2636      *          the regular expression to which this string is to be matched
2637      *
2638      * @return  {@code true} if, and only if, this string matches the
2639      *          given regular expression
2640      *
2641      * @throws  PatternSyntaxException
2642      *          if the regular expression's syntax is invalid
2643      *
2644      * @see java.util.regex.Pattern
2645      *
2646      * @since 1.4
2647      * @spec JSR-51
2648      */
matches(String regex)2649     public boolean matches(String regex) {
2650         return Pattern.matches(regex, this);
2651     }
2652 
2653     /**
2654      * Returns true if and only if this string contains the specified
2655      * sequence of char values.
2656      *
2657      * @param s the sequence to search for
2658      * @return true if this string contains {@code s}, false otherwise
2659      * @since 1.5
2660      */
contains(CharSequence s)2661     public boolean contains(CharSequence s) {
2662         return indexOf(s.toString()) >= 0;
2663     }
2664 
2665     /**
2666      * Replaces the first substring of this string that matches the given <a
2667      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2668      * given replacement.
2669      *
2670      * <p> An invocation of this method of the form
2671      * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
2672      * yields exactly the same result as the expression
2673      *
2674      * <blockquote>
2675      * <code>
2676      * {@link java.util.regex.Pattern}.{@link
2677      * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
2678      * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
2679      * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)
2680      * </code>
2681      * </blockquote>
2682      *
2683      *<p>
2684      * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
2685      * replacement string may cause the results to be different than if it were
2686      * being treated as a literal replacement string; see
2687      * {@link java.util.regex.Matcher#replaceFirst}.
2688      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2689      * meaning of these characters, if desired.
2690      *
2691      * @param   regex
2692      *          the regular expression to which this string is to be matched
2693      * @param   replacement
2694      *          the string to be substituted for the first match
2695      *
2696      * @return  The resulting {@code String}
2697      *
2698      * @throws  PatternSyntaxException
2699      *          if the regular expression's syntax is invalid
2700      *
2701      * @see java.util.regex.Pattern
2702      *
2703      * @since 1.4
2704      * @spec JSR-51
2705      */
replaceFirst(String regex, String replacement)2706     public String replaceFirst(String regex, String replacement) {
2707         return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
2708     }
2709 
2710     /**
2711      * Replaces each substring of this string that matches the given <a
2712      * href="../util/regex/Pattern.html#sum">regular expression</a> with the
2713      * given replacement.
2714      *
2715      * <p> An invocation of this method of the form
2716      * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
2717      * yields exactly the same result as the expression
2718      *
2719      * <blockquote>
2720      * <code>
2721      * {@link java.util.regex.Pattern}.{@link
2722      * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
2723      * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
2724      * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>)
2725      * </code>
2726      * </blockquote>
2727      *
2728      *<p>
2729      * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
2730      * replacement string may cause the results to be different than if it were
2731      * being treated as a literal replacement string; see
2732      * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
2733      * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
2734      * meaning of these characters, if desired.
2735      *
2736      * @param   regex
2737      *          the regular expression to which this string is to be matched
2738      * @param   replacement
2739      *          the string to be substituted for each match
2740      *
2741      * @return  The resulting {@code String}
2742      *
2743      * @throws  PatternSyntaxException
2744      *          if the regular expression's syntax is invalid
2745      *
2746      * @see java.util.regex.Pattern
2747      *
2748      * @since 1.4
2749      * @spec JSR-51
2750      */
replaceAll(String regex, String replacement)2751     public String replaceAll(String regex, String replacement) {
2752         return Pattern.compile(regex).matcher(this).replaceAll(replacement);
2753     }
2754 
2755     /**
2756      * Replaces each substring of this string that matches the literal target
2757      * sequence with the specified literal replacement sequence. The
2758      * replacement proceeds from the beginning of the string to the end, for
2759      * example, replacing "aa" with "b" in the string "aaa" will result in
2760      * "ba" rather than "ab".
2761      *
2762      * @param  target The sequence of char values to be replaced
2763      * @param  replacement The replacement sequence of char values
2764      * @return  The resulting string
2765      * @since 1.5
2766      */
replace(CharSequence target, CharSequence replacement)2767     public String replace(CharSequence target, CharSequence replacement) {
2768         // BEGIN Android-added: Additional null check for parameters.
2769         Objects.requireNonNull(target);
2770         Objects.requireNonNull(replacement);
2771         // END Android-added: Additional null check for parameters.
2772 
2773         String tgtStr = target.toString();
2774         String replStr = replacement.toString();
2775         int j = indexOf(tgtStr);
2776         if (j < 0) {
2777             return this;
2778         }
2779         int tgtLen = tgtStr.length();
2780         int tgtLen1 = Math.max(tgtLen, 1);
2781         int thisLen = length();
2782 
2783         int newLenHint = thisLen - tgtLen + replStr.length();
2784         if (newLenHint < 0) {
2785             throw new OutOfMemoryError();
2786         }
2787         StringBuilder sb = new StringBuilder(newLenHint);
2788         int i = 0;
2789         do {
2790             sb.append(this, i, j).append(replStr);
2791             i = j + tgtLen;
2792         } while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
2793         return sb.append(this, i, thisLen).toString();
2794     }
2795 
2796     /**
2797      * Splits this string around matches of the given
2798      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
2799      *
2800      * <p> The array returned by this method contains each substring of this
2801      * string that is terminated by another substring that matches the given
2802      * expression or is terminated by the end of the string.  The substrings in
2803      * the array are in the order in which they occur in this string.  If the
2804      * expression does not match any part of the input then the resulting array
2805      * has just one element, namely this string.
2806      *
2807      * <p> When there is a positive-width match at the beginning of this
2808      * string then an empty leading substring is included at the beginning
2809      * of the resulting array. A zero-width match at the beginning however
2810      * never produces such empty leading substring.
2811      *
2812      * <p> The {@code limit} parameter controls the number of times the
2813      * pattern is applied and therefore affects the length of the resulting
2814      * array.
2815      * <ul>
2816      *    <li><p>
2817      *    If the <i>limit</i> is positive then the pattern will be applied
2818      *    at most <i>limit</i>&nbsp;-&nbsp;1 times, the array's length will be
2819      *    no greater than <i>limit</i>, and the array's last entry will contain
2820      *    all input beyond the last matched delimiter.</p></li>
2821      *
2822      *    <li><p>
2823      *    If the <i>limit</i> is zero then the pattern will be applied as
2824      *    many times as possible, the array can have any length, and trailing
2825      *    empty strings will be discarded.</p></li>
2826      *
2827      *    <li><p>
2828      *    If the <i>limit</i> is negative then the pattern will be applied
2829      *    as many times as possible and the array can have any length.</p></li>
2830      * </ul>
2831      *
2832      * <p> The string {@code "boo:and:foo"}, for example, yields the
2833      * following results with these parameters:
2834      *
2835      * <blockquote><table class="plain">
2836      * <caption style="display:none">Split example showing regex, limit, and result</caption>
2837      * <thead>
2838      * <tr>
2839      *     <th scope="col">Regex</th>
2840      *     <th scope="col">Limit</th>
2841      *     <th scope="col">Result</th>
2842      * </tr>
2843      * </thead>
2844      * <tbody>
2845      * <tr><th scope="row" rowspan="3" style="font-weight:normal">:</th>
2846      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">2</th>
2847      *     <td>{@code { "boo", "and:foo" }}</td></tr>
2848      * <tr><!-- : -->
2849      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
2850      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
2851      * <tr><!-- : -->
2852      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
2853      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
2854      * <tr><th scope="row" rowspan="3" style="font-weight:normal">o</th>
2855      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
2856      *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
2857      * <tr><!-- o -->
2858      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
2859      *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
2860      * <tr><!-- o -->
2861      *     <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">0</th>
2862      *     <td>{@code { "b", "", ":and:f" }}</td></tr>
2863      * </tbody>
2864      * </table></blockquote>
2865      *
2866      * <p> An invocation of this method of the form
2867      * <i>str.</i>{@code split(}<i>regex</i>{@code ,}&nbsp;<i>n</i>{@code )}
2868      * yields the same result as the expression
2869      *
2870      * <blockquote>
2871      * <code>
2872      * {@link java.util.regex.Pattern}.{@link
2873      * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
2874      * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>,&nbsp;<i>n</i>)
2875      * </code>
2876      * </blockquote>
2877      *
2878      *
2879      * @param  regex
2880      *         the delimiting regular expression
2881      *
2882      * @param  limit
2883      *         the result threshold, as described above
2884      *
2885      * @return  the array of strings computed by splitting this string
2886      *          around matches of the given regular expression
2887      *
2888      * @throws  PatternSyntaxException
2889      *          if the regular expression's syntax is invalid
2890      *
2891      * @see java.util.regex.Pattern
2892      *
2893      * @since 1.4
2894      * @spec JSR-51
2895      */
split(String regex, int limit)2896     public String[] split(String regex, int limit) {
2897         // BEGIN Android-changed: Replace custom fast-path with use of new Pattern.fastSplit method.
2898         // Try fast splitting without allocating Pattern object
2899         /*
2900         /* fastpath if the regex is a
2901          (1)one-char String and this character is not one of the
2902             RegEx's meta characters ".$|()[{^?*+\\", or
2903          (2)two-char String and the first char is the backslash and
2904             the second is not the ascii digit or ascii letter.
2905          *
2906         char ch = 0;
2907         if (((regex.length() == 1 &&
2908              ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
2909              (regex.length() == 2 &&
2910               regex.charAt(0) == '\\' &&
2911               (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
2912               ((ch-'a')|('z'-ch)) < 0 &&
2913               ((ch-'A')|('Z'-ch)) < 0)) &&
2914             (ch < Character.MIN_HIGH_SURROGATE ||
2915              ch > Character.MAX_LOW_SURROGATE))
2916         {
2917             int off = 0;
2918             int next = 0;
2919             boolean limited = limit > 0;
2920             ArrayList<String> list = new ArrayList<>();
2921             while ((next = indexOf(ch, off)) != -1) {
2922                 if (!limited || list.size() < limit - 1) {
2923                     list.add(substring(off, next));
2924                     off = next + 1;
2925                 } else {    // last one
2926                     //assert (list.size() == limit - 1);
2927                     int last = length();
2928                     list.add(substring(off, last));
2929                     off = last;
2930                     break;
2931                 }
2932             }
2933             // If no match was found, return this
2934             if (off == 0)
2935                 return new String[]{this};
2936 
2937             // Add remaining segment
2938             if (!limited || list.size() < limit)
2939                 list.add(substring(off, length()));
2940 
2941             // Construct result
2942             int resultSize = list.size();
2943             if (limit == 0) {
2944                 while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {
2945                     resultSize--;
2946                 }
2947             }
2948             String[] result = new String[resultSize];
2949             return list.subList(0, resultSize).toArray(result);
2950         }
2951         */
2952         String[] fast = Pattern.fastSplit(regex, this, limit);
2953         if (fast != null) {
2954             return fast;
2955         }
2956         // END Android-changed: Replace custom fast-path with use of new Pattern.fastSplit method.
2957         return Pattern.compile(regex).split(this, limit);
2958     }
2959 
2960     /**
2961      * Splits this string around matches of the given <a
2962      * href="../util/regex/Pattern.html#sum">regular expression</a>.
2963      *
2964      * <p> This method works as if by invoking the two-argument {@link
2965      * #split(String, int) split} method with the given expression and a limit
2966      * argument of zero.  Trailing empty strings are therefore not included in
2967      * the resulting array.
2968      *
2969      * <p> The string {@code "boo:and:foo"}, for example, yields the following
2970      * results with these expressions:
2971      *
2972      * <blockquote><table class="plain">
2973      * <caption style="display:none">Split examples showing regex and result</caption>
2974      * <thead>
2975      * <tr>
2976      *  <th scope="col">Regex</th>
2977      *  <th scope="col">Result</th>
2978      * </tr>
2979      * </thead>
2980      * <tbody>
2981      * <tr><th scope="row" style="text-weight:normal">:</th>
2982      *     <td>{@code { "boo", "and", "foo" }}</td></tr>
2983      * <tr><th scope="row" style="text-weight:normal">o</th>
2984      *     <td>{@code { "b", "", ":and:f" }}</td></tr>
2985      * </tbody>
2986      * </table></blockquote>
2987      *
2988      *
2989      * @param  regex
2990      *         the delimiting regular expression
2991      *
2992      * @return  the array of strings computed by splitting this string
2993      *          around matches of the given regular expression
2994      *
2995      * @throws  PatternSyntaxException
2996      *          if the regular expression's syntax is invalid
2997      *
2998      * @see java.util.regex.Pattern
2999      *
3000      * @since 1.4
3001      * @spec JSR-51
3002      */
split(String regex)3003     public String[] split(String regex) {
3004         return split(regex, 0);
3005     }
3006 
3007     /**
3008      * Returns a new String composed of copies of the
3009      * {@code CharSequence elements} joined together with a copy of
3010      * the specified {@code delimiter}.
3011      *
3012      * <blockquote>For example,
3013      * <pre>{@code
3014      *     String message = String.join("-", "Java", "is", "cool");
3015      *     // message returned is: "Java-is-cool"
3016      * }</pre></blockquote>
3017      *
3018      * Note that if an element is null, then {@code "null"} is added.
3019      *
3020      * @param  delimiter the delimiter that separates each element
3021      * @param  elements the elements to join together.
3022      *
3023      * @return a new {@code String} that is composed of the {@code elements}
3024      *         separated by the {@code delimiter}
3025      *
3026      * @throws NullPointerException If {@code delimiter} or {@code elements}
3027      *         is {@code null}
3028      *
3029      * @see java.util.StringJoiner
3030      * @since 1.8
3031      */
join(CharSequence delimiter, CharSequence... elements)3032     public static String join(CharSequence delimiter, CharSequence... elements) {
3033         Objects.requireNonNull(delimiter);
3034         Objects.requireNonNull(elements);
3035         // Number of elements not likely worth Arrays.stream overhead.
3036         StringJoiner joiner = new StringJoiner(delimiter);
3037         for (CharSequence cs: elements) {
3038             joiner.add(cs);
3039         }
3040         return joiner.toString();
3041     }
3042 
3043     /**
3044      * Returns a new {@code String} composed of copies of the
3045      * {@code CharSequence elements} joined together with a copy of the
3046      * specified {@code delimiter}.
3047      *
3048      * <blockquote>For example,
3049      * <pre>{@code
3050      *     List<String> strings = List.of("Java", "is", "cool");
3051      *     String message = String.join(" ", strings);
3052      *     //message returned is: "Java is cool"
3053      *
3054      *     Set<String> strings =
3055      *         new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
3056      *     String message = String.join("-", strings);
3057      *     //message returned is: "Java-is-very-cool"
3058      * }</pre></blockquote>
3059      *
3060      * Note that if an individual element is {@code null}, then {@code "null"} is added.
3061      *
3062      * @param  delimiter a sequence of characters that is used to separate each
3063      *         of the {@code elements} in the resulting {@code String}
3064      * @param  elements an {@code Iterable} that will have its {@code elements}
3065      *         joined together.
3066      *
3067      * @return a new {@code String} that is composed from the {@code elements}
3068      *         argument
3069      *
3070      * @throws NullPointerException If {@code delimiter} or {@code elements}
3071      *         is {@code null}
3072      *
3073      * @see    #join(CharSequence,CharSequence...)
3074      * @see    java.util.StringJoiner
3075      * @since 1.8
3076      */
join(CharSequence delimiter, Iterable<? extends CharSequence> elements)3077     public static String join(CharSequence delimiter,
3078             Iterable<? extends CharSequence> elements) {
3079         Objects.requireNonNull(delimiter);
3080         Objects.requireNonNull(elements);
3081         StringJoiner joiner = new StringJoiner(delimiter);
3082         for (CharSequence cs: elements) {
3083             joiner.add(cs);
3084         }
3085         return joiner.toString();
3086     }
3087 
3088     /**
3089      * Converts all of the characters in this {@code String} to lower
3090      * case using the rules of the given {@code Locale}.  Case mapping is based
3091      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
3092      * class. Since case mappings are not always 1:1 char mappings, the resulting
3093      * {@code String} may be a different length than the original {@code String}.
3094      * <p>
3095      * Examples of lowercase  mappings are in the following table:
3096      * <table class="plain">
3097      * <caption style="display:none">Lowercase mapping examples showing language code of locale, upper case, lower case, and description</caption>
3098      * <thead>
3099      * <tr>
3100      *   <th scope="col">Language Code of Locale</th>
3101      *   <th scope="col">Upper Case</th>
3102      *   <th scope="col">Lower Case</th>
3103      *   <th scope="col">Description</th>
3104      * </tr>
3105      * </thead>
3106      * <tbody>
3107      * <tr>
3108      *   <td>tr (Turkish)</td>
3109      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0130</th>
3110      *   <td>&#92;u0069</td>
3111      *   <td>capital letter I with dot above -&gt; small letter i</td>
3112      * </tr>
3113      * <tr>
3114      *   <td>tr (Turkish)</td>
3115      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0049</th>
3116      *   <td>&#92;u0131</td>
3117      *   <td>capital letter I -&gt; small letter dotless i </td>
3118      * </tr>
3119      * <tr>
3120      *   <td>(all)</td>
3121      *   <th scope="row" style="font-weight:normal; text-align:left">French Fries</th>
3122      *   <td>french fries</td>
3123      *   <td>lowercased all chars in String</td>
3124      * </tr>
3125      * <tr>
3126      *   <td>(all)</td>
3127      *   <th scope="row" style="font-weight:normal; text-align:left">
3128      *       &Iota;&Chi;&Theta;&Upsilon;&Sigma;</th>
3129      *   <td>&iota;&chi;&theta;&upsilon;&sigma;</td>
3130      *   <td>lowercased all chars in String</td>
3131      * </tr>
3132      * </tbody>
3133      * </table>
3134      *
3135      * @param locale use the case transformation rules for this locale
3136      * @return the {@code String}, converted to lowercase.
3137      * @see     java.lang.String#toLowerCase()
3138      * @see     java.lang.String#toUpperCase()
3139      * @see     java.lang.String#toUpperCase(Locale)
3140      * @since   1.1
3141      */
toLowerCase(Locale locale)3142     public String toLowerCase(Locale locale) {
3143         // BEGIN Android-changed: Replace custom code with call to new CaseMapper class.
3144         /*
3145         return isLatin1() ? StringLatin1.toLowerCase(this, value, locale)
3146                           : StringUTF16.toLowerCase(this, value, locale);
3147         */
3148         return CaseMapper.toLowerCase(locale, this);
3149         // END Android-changed: Replace custom code with call to new CaseMapper class.
3150     }
3151 
3152     /**
3153      * Converts all of the characters in this {@code String} to lower
3154      * case using the rules of the default locale. This is equivalent to calling
3155      * {@code toLowerCase(Locale.getDefault())}.
3156      * <p>
3157      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
3158      * results if used for strings that are intended to be interpreted locale
3159      * independently.
3160      * Examples are programming language identifiers, protocol keys, and HTML
3161      * tags.
3162      * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
3163      * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
3164      * LATIN SMALL LETTER DOTLESS I character.
3165      * To obtain correct results for locale insensitive strings, use
3166      * {@code toLowerCase(Locale.ROOT)}.
3167      *
3168      * @return  the {@code String}, converted to lowercase.
3169      * @see     java.lang.String#toLowerCase(Locale)
3170      */
toLowerCase()3171     public String toLowerCase() {
3172         return toLowerCase(Locale.getDefault());
3173     }
3174 
3175     /**
3176      * Converts all of the characters in this {@code String} to upper
3177      * case using the rules of the given {@code Locale}. Case mapping is based
3178      * on the Unicode Standard version specified by the {@link java.lang.Character Character}
3179      * class. Since case mappings are not always 1:1 char mappings, the resulting
3180      * {@code String} may be a different length than the original {@code String}.
3181      * <p>
3182      * Examples of locale-sensitive and 1:M case mappings are in the following table.
3183      *
3184      * <table class="plain">
3185      * <caption style="display:none">Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.</caption>
3186      * <thead>
3187      * <tr>
3188      *   <th scope="col">Language Code of Locale</th>
3189      *   <th scope="col">Lower Case</th>
3190      *   <th scope="col">Upper Case</th>
3191      *   <th scope="col">Description</th>
3192      * </tr>
3193      * </thead>
3194      * <tbody>
3195      * <tr>
3196      *   <td>tr (Turkish)</td>
3197      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0069</th>
3198      *   <td>&#92;u0130</td>
3199      *   <td>small letter i -&gt; capital letter I with dot above</td>
3200      * </tr>
3201      * <tr>
3202      *   <td>tr (Turkish)</td>
3203      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u0131</th>
3204      *   <td>&#92;u0049</td>
3205      *   <td>small letter dotless i -&gt; capital letter I</td>
3206      * </tr>
3207      * <tr>
3208      *   <td>(all)</td>
3209      *   <th scope="row" style="font-weight:normal; text-align:left">&#92;u00df</th>
3210      *   <td>&#92;u0053 &#92;u0053</td>
3211      *   <td>small letter sharp s -&gt; two letters: SS</td>
3212      * </tr>
3213      * <tr>
3214      *   <td>(all)</td>
3215      *   <th scope="row" style="font-weight:normal; text-align:left">Fahrvergn&uuml;gen</th>
3216      *   <td>FAHRVERGN&Uuml;GEN</td>
3217      *   <td></td>
3218      * </tr>
3219      * </tbody>
3220      * </table>
3221      * @param locale use the case transformation rules for this locale
3222      * @return the {@code String}, converted to uppercase.
3223      * @see     java.lang.String#toUpperCase()
3224      * @see     java.lang.String#toLowerCase()
3225      * @see     java.lang.String#toLowerCase(Locale)
3226      * @since   1.1
3227      */
toUpperCase(Locale locale)3228     public String toUpperCase(Locale locale) {
3229         // BEGIN Android-changed: Replace custom code with call to new CaseMapper class.
3230         /*
3231         return isLatin1() ? StringLatin1.toUpperCase(this, value, locale)
3232                           : StringUTF16.toUpperCase(this, value, locale);
3233         */
3234         return CaseMapper.toUpperCase(locale, this, length());
3235         // END Android-changed: Replace custom code with call to new CaseMapper class.
3236     }
3237 
3238     /**
3239      * Converts all of the characters in this {@code String} to upper
3240      * case using the rules of the default locale. This method is equivalent to
3241      * {@code toUpperCase(Locale.getDefault())}.
3242      * <p>
3243      * <b>Note:</b> This method is locale sensitive, and may produce unexpected
3244      * results if used for strings that are intended to be interpreted locale
3245      * independently.
3246      * Examples are programming language identifiers, protocol keys, and HTML
3247      * tags.
3248      * For instance, {@code "title".toUpperCase()} in a Turkish locale
3249      * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
3250      * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
3251      * To obtain correct results for locale insensitive strings, use
3252      * {@code toUpperCase(Locale.ROOT)}.
3253      *
3254      * @return  the {@code String}, converted to uppercase.
3255      * @see     java.lang.String#toUpperCase(Locale)
3256      */
toUpperCase()3257     public String toUpperCase() {
3258         return toUpperCase(Locale.getDefault());
3259     }
3260 
3261     /**
3262      * Returns a string whose value is this string, with all leading
3263      * and trailing space removed, where space is defined
3264      * as any character whose codepoint is less than or equal to
3265      * {@code 'U+0020'} (the space character).
3266      * <p>
3267      * If this {@code String} object represents an empty character
3268      * sequence, or the first and last characters of character sequence
3269      * represented by this {@code String} object both have codes
3270      * that are not space (as defined above), then a
3271      * reference to this {@code String} object is returned.
3272      * <p>
3273      * Otherwise, if all characters in this string are space (as
3274      * defined above), then a  {@code String} object representing an
3275      * empty string is returned.
3276      * <p>
3277      * Otherwise, let <i>k</i> be the index of the first character in the
3278      * string whose code is not a space (as defined above) and let
3279      * <i>m</i> be the index of the last character in the string whose code
3280      * is not a space (as defined above). A {@code String}
3281      * object is returned, representing the substring of this string that
3282      * begins with the character at index <i>k</i> and ends with the
3283      * character at index <i>m</i>-that is, the result of
3284      * {@code this.substring(k, m + 1)}.
3285      * <p>
3286      * This method may be used to trim space (as defined above) from
3287      * the beginning and end of a string.
3288      *
3289      * @return  a string whose value is this string, with all leading
3290      *          and trailing space removed, or this string if it
3291      *          has no leading or trailing space.
3292      */
trim()3293     public String trim() {
3294         // BEGIN Android-changed: Implement in terms of charAt().
3295         /*
3296         String ret = isLatin1() ? StringLatin1.trim(value)
3297                                 : StringUTF16.trim(value);
3298         return ret == null ? this : ret;
3299          */
3300         int len = length();
3301         int st = 0;
3302 
3303         while ((st < len) && (charAt(st) <= ' ')) {
3304             st++;
3305         }
3306         while ((st < len) && (charAt(len - 1) <= ' ')) {
3307             len--;
3308         }
3309         return ((st > 0) || (len < length())) ? substring(st, len) : this;
3310         // END Android-changed: Implement in terms of charAt().
3311     }
3312 
3313     /**
3314      * Returns a string whose value is this string, with all leading
3315      * and trailing {@link Character#isWhitespace(int) white space}
3316      * removed.
3317      * <p>
3318      * If this {@code String} object represents an empty string,
3319      * or if all code points in this string are
3320      * {@link Character#isWhitespace(int) white space}, then an empty string
3321      * is returned.
3322      * <p>
3323      * Otherwise, returns a substring of this string beginning with the first
3324      * code point that is not a {@link Character#isWhitespace(int) white space}
3325      * up to and including the last code point that is not a
3326      * {@link Character#isWhitespace(int) white space}.
3327      * <p>
3328      * This method may be used to strip
3329      * {@link Character#isWhitespace(int) white space} from
3330      * the beginning and end of a string.
3331      *
3332      * @return  a string whose value is this string, with all leading
3333      *          and trailing white space removed
3334      *
3335      * @see Character#isWhitespace(int)
3336      *
3337      * @since 11
3338      */
strip()3339     public String strip() {
3340         // BEGIN Android-changed: Delegate to StringUTF16.
3341         /*
3342         String ret = isLatin1() ? StringLatin1.strip(value)
3343                                 : StringUTF16.strip(value);
3344          */
3345         String ret = StringUTF16.strip(this);
3346         // END Android-changed: Delegate to StringUTF16.
3347         return ret == null ? this : ret;
3348     }
3349 
3350     /**
3351      * Returns a string whose value is this string, with all leading
3352      * {@link Character#isWhitespace(int) white space} removed.
3353      * <p>
3354      * If this {@code String} object represents an empty string,
3355      * or if all code points in this string are
3356      * {@link Character#isWhitespace(int) white space}, then an empty string
3357      * is returned.
3358      * <p>
3359      * Otherwise, returns a substring of this string beginning with the first
3360      * code point that is not a {@link Character#isWhitespace(int) white space}
3361      * up to to and including the last code point of this string.
3362      * <p>
3363      * This method may be used to trim
3364      * {@link Character#isWhitespace(int) white space} from
3365      * the beginning of a string.
3366      *
3367      * @return  a string whose value is this string, with all leading white
3368      *          space removed
3369      *
3370      * @see Character#isWhitespace(int)
3371      *
3372      * @since 11
3373      */
stripLeading()3374     public String stripLeading() {
3375         // BEGIN Android-changed: Delegate to StringUTF16.
3376         /*
3377         String ret = isLatin1() ? StringLatin1.stripLeading(value)
3378                                 : StringUTF16.stripLeading(value);
3379          */
3380         String ret = StringUTF16.stripLeading(this);
3381         // END Android-changed: Delegate to StringUTF16.
3382         return ret == null ? this : ret;
3383     }
3384 
3385     /**
3386      * Returns a string whose value is this string, with all trailing
3387      * {@link Character#isWhitespace(int) white space} removed.
3388      * <p>
3389      * If this {@code String} object represents an empty string,
3390      * or if all characters in this string are
3391      * {@link Character#isWhitespace(int) white space}, then an empty string
3392      * is returned.
3393      * <p>
3394      * Otherwise, returns a substring of this string beginning with the first
3395      * code point of this string up to and including the last code point
3396      * that is not a {@link Character#isWhitespace(int) white space}.
3397      * <p>
3398      * This method may be used to trim
3399      * {@link Character#isWhitespace(int) white space} from
3400      * the end of a string.
3401      *
3402      * @return  a string whose value is this string, with all trailing white
3403      *          space removed
3404      *
3405      * @see Character#isWhitespace(int)
3406      *
3407      * @since 11
3408      */
stripTrailing()3409     public String stripTrailing() {
3410         // BEGIN Android-changed: Delegate to StringUTF16.
3411         /*
3412         String ret = isLatin1() ? StringLatin1.stripTrailing(value)
3413                                 : StringUTF16.stripTrailing(value);
3414          */
3415         String ret = StringUTF16.stripTrailing(this);
3416         // END Android-changed: Delegate to StringUTF16.
3417         return ret == null ? this : ret;
3418     }
3419 
3420     /**
3421      * Returns {@code true} if the string is empty or contains only
3422      * {@link Character#isWhitespace(int) white space} codepoints,
3423      * otherwise {@code false}.
3424      *
3425      * @return {@code true} if the string is empty or contains only
3426      *         {@link Character#isWhitespace(int) white space} codepoints,
3427      *         otherwise {@code false}
3428      *
3429      * @see Character#isWhitespace(int)
3430      *
3431      * @since 11
3432      */
isBlank()3433     public boolean isBlank() {
3434         return indexOfNonWhitespace() == length();
3435     }
3436 
indexOfNonWhitespace()3437     private int indexOfNonWhitespace() {
3438         // BEGIN Android-removed: Delegate to StringUTF16.
3439         /*
3440         if (isLatin1()) {
3441             return StringLatin1.indexOfNonWhitespace(value);
3442         } else {
3443             return StringUTF16.indexOfNonWhitespace(value);
3444         }
3445          */
3446         return StringUTF16.indexOfNonWhitespace(this);
3447         // END Android-removed: Delegate to StringUTF16.
3448     }
3449 
3450     /**
3451      * Returns a stream of lines extracted from this string,
3452      * separated by line terminators.
3453      * <p>
3454      * A <i>line terminator</i> is one of the following:
3455      * a line feed character {@code "\n"} (U+000A),
3456      * a carriage return character {@code "\r"} (U+000D),
3457      * or a carriage return followed immediately by a line feed
3458      * {@code "\r\n"} (U+000D U+000A).
3459      * <p>
3460      * A <i>line</i> is either a sequence of zero or more characters
3461      * followed by a line terminator, or it is a sequence of one or
3462      * more characters followed by the end of the string. A
3463      * line does not include the line terminator.
3464      * <p>
3465      * The stream returned by this method contains the lines from
3466      * this string in the order in which they occur.
3467      *
3468      * @apiNote This definition of <i>line</i> implies that an empty
3469      *          string has zero lines and that there is no empty line
3470      *          following a line terminator at the end of a string.
3471      *
3472      * @implNote This method provides better performance than
3473      *           split("\R") by supplying elements lazily and
3474      *           by faster search of new line terminators.
3475      *
3476      * @return  the stream of lines extracted from this string
3477      *
3478      * @since 11
3479      */
lines()3480     public Stream<String> lines() {
3481         // BEGIN Android-removed: Delegate to StringUTF16.
3482         /*
3483         return isLatin1() ? StringLatin1.lines(value)
3484                           : StringUTF16.lines(value);
3485          */
3486         return StringUTF16.lines(this);
3487         // END Android-removed: Delegate to StringUTF16.
3488     }
3489 
3490     /**
3491      * This object (which is already a string!) is itself returned.
3492      *
3493      * @return  the string itself.
3494      */
toString()3495     public String toString() {
3496         return this;
3497     }
3498 
3499     /**
3500      * Returns a stream of {@code int} zero-extending the {@code char} values
3501      * from this sequence.  Any char which maps to a <a
3502      * href="{@docRoot}/java.base/java/lang/Character.html#unicode">surrogate code
3503      * point</a> is passed through uninterpreted.
3504      *
3505      * @return an IntStream of char values from this sequence
3506      * @since 9
3507      */
3508     @Override
chars()3509     public IntStream chars() {
3510         return StreamSupport.intStream(
3511             // BEGIN Android-removed: Delegate to StringUTF16.
3512             /*
3513             isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
3514                        : new StringUTF16.CharsSpliterator(value, Spliterator.IMMUTABLE),
3515              */
3516             new StringUTF16.CharsSpliterator(this, Spliterator.IMMUTABLE),
3517             // END Android-removed: Delegate to StringUTF16.
3518             false);
3519     }
3520 
3521 
3522     /**
3523      * Returns a stream of code point values from this sequence.  Any surrogate
3524      * pairs encountered in the sequence are combined as if by {@linkplain
3525      * Character#toCodePoint Character.toCodePoint} and the result is passed
3526      * to the stream. Any other code units, including ordinary BMP characters,
3527      * unpaired surrogates, and undefined code units, are zero-extended to
3528      * {@code int} values which are then passed to the stream.
3529      *
3530      * @return an IntStream of Unicode code points from this sequence
3531      * @since 9
3532      */
3533     @Override
codePoints()3534     public IntStream codePoints() {
3535         return StreamSupport.intStream(
3536             // BEGIN Android-removed: Delegate to StringUTF16.
3537             /*
3538             isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
3539                        : new StringUTF16.CodePointsSpliterator(value, Spliterator.IMMUTABLE),
3540              */
3541             new StringUTF16.CodePointsSpliterator(this, Spliterator.IMMUTABLE),
3542             // END Android-removed: Delegate to StringUTF16.
3543             false);
3544     }
3545 
3546     /**
3547      * Converts this string to a new character array.
3548      *
3549      * @return  a newly allocated character array whose length is the length
3550      *          of this string and whose contents are initialized to contain
3551      *          the character sequence represented by this string.
3552      */
3553     // BEGIN Android-changed: Replace with implementation in runtime to access chars (see above).
3554     /*
3555     public char[] toCharArray() {
3556         return isLatin1() ? StringLatin1.toChars(value)
3557                           : StringUTF16.toChars(value);
3558     }
3559     */
3560     @FastNative
toCharArray()3561     public native char[] toCharArray();
3562     // END Android-changed: Replace with implementation in runtime to access chars (see above).
3563 
3564 
3565     /**
3566      * Returns a formatted string using the specified format string and
3567      * arguments.
3568      *
3569      * <p> The locale always used is the one returned by {@link
3570      * java.util.Locale#getDefault(java.util.Locale.Category)
3571      * Locale.getDefault(Locale.Category)} with
3572      * {@link java.util.Locale.Category#FORMAT FORMAT} category specified.
3573      *
3574      * @param  format
3575      *         A <a href="../util/Formatter.html#syntax">format string</a>
3576      *
3577      * @param  args
3578      *         Arguments referenced by the format specifiers in the format
3579      *         string.  If there are more arguments than format specifiers, the
3580      *         extra arguments are ignored.  The number of arguments is
3581      *         variable and may be zero.  The maximum number of arguments is
3582      *         limited by the maximum dimension of a Java array as defined by
3583      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
3584      *         The behaviour on a
3585      *         {@code null} argument depends on the <a
3586      *         href="../util/Formatter.html#syntax">conversion</a>.
3587      *
3588      * @throws  java.util.IllegalFormatException
3589      *          If a format string contains an illegal syntax, a format
3590      *          specifier that is incompatible with the given arguments,
3591      *          insufficient arguments given the format string, or other
3592      *          illegal conditions.  For specification of all possible
3593      *          formatting errors, see the <a
3594      *          href="../util/Formatter.html#detail">Details</a> section of the
3595      *          formatter class specification.
3596      *
3597      * @return  A formatted string
3598      *
3599      * @see  java.util.Formatter
3600      * @since  1.5
3601      */
format(String format, Object... args)3602     public static String format(String format, Object... args) {
3603         return new Formatter().format(format, args).toString();
3604     }
3605 
3606     /**
3607      * Returns a formatted string using the specified locale, format string,
3608      * and arguments.
3609      *
3610      * @param  l
3611      *         The {@linkplain java.util.Locale locale} to apply during
3612      *         formatting.  If {@code l} is {@code null} then no localization
3613      *         is applied.
3614      *
3615      * @param  format
3616      *         A <a href="../util/Formatter.html#syntax">format string</a>
3617      *
3618      * @param  args
3619      *         Arguments referenced by the format specifiers in the format
3620      *         string.  If there are more arguments than format specifiers, the
3621      *         extra arguments are ignored.  The number of arguments is
3622      *         variable and may be zero.  The maximum number of arguments is
3623      *         limited by the maximum dimension of a Java array as defined by
3624      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
3625      *         The behaviour on a
3626      *         {@code null} argument depends on the
3627      *         <a href="../util/Formatter.html#syntax">conversion</a>.
3628      *
3629      * @throws  java.util.IllegalFormatException
3630      *          If a format string contains an illegal syntax, a format
3631      *          specifier that is incompatible with the given arguments,
3632      *          insufficient arguments given the format string, or other
3633      *          illegal conditions.  For specification of all possible
3634      *          formatting errors, see the <a
3635      *          href="../util/Formatter.html#detail">Details</a> section of the
3636      *          formatter class specification
3637      *
3638      * @return  A formatted string
3639      *
3640      * @see  java.util.Formatter
3641      * @since  1.5
3642      */
format(Locale l, String format, Object... args)3643     public static String format(Locale l, String format, Object... args) {
3644         return new Formatter(l).format(format, args).toString();
3645     }
3646 
3647     /**
3648      * Returns the string representation of the {@code Object} argument.
3649      *
3650      * @param   obj   an {@code Object}.
3651      * @return  if the argument is {@code null}, then a string equal to
3652      *          {@code "null"}; otherwise, the value of
3653      *          {@code obj.toString()} is returned.
3654      * @see     java.lang.Object#toString()
3655      */
valueOf(Object obj)3656     public static String valueOf(Object obj) {
3657         return (obj == null) ? "null" : obj.toString();
3658     }
3659 
3660     /**
3661      * Returns the string representation of the {@code char} array
3662      * argument. The contents of the character array are copied; subsequent
3663      * modification of the character array does not affect the returned
3664      * string.
3665      *
3666      * @param   data     the character array.
3667      * @return  a {@code String} that contains the characters of the
3668      *          character array.
3669      */
valueOf(char data[])3670     public static String valueOf(char data[]) {
3671         return new String(data);
3672     }
3673 
3674     /**
3675      * Returns the string representation of a specific subarray of the
3676      * {@code char} array argument.
3677      * <p>
3678      * The {@code offset} argument is the index of the first
3679      * character of the subarray. The {@code count} argument
3680      * specifies the length of the subarray. The contents of the subarray
3681      * are copied; subsequent modification of the character array does not
3682      * affect the returned string.
3683      *
3684      * @param   data     the character array.
3685      * @param   offset   initial offset of the subarray.
3686      * @param   count    length of the subarray.
3687      * @return  a {@code String} that contains the characters of the
3688      *          specified subarray of the character array.
3689      * @exception IndexOutOfBoundsException if {@code offset} is
3690      *          negative, or {@code count} is negative, or
3691      *          {@code offset+count} is larger than
3692      *          {@code data.length}.
3693      */
valueOf(char data[], int offset, int count)3694     public static String valueOf(char data[], int offset, int count) {
3695         return new String(data, offset, count);
3696     }
3697 
3698     /**
3699      * Equivalent to {@link #valueOf(char[], int, int)}.
3700      *
3701      * @param   data     the character array.
3702      * @param   offset   initial offset of the subarray.
3703      * @param   count    length of the subarray.
3704      * @return  a {@code String} that contains the characters of the
3705      *          specified subarray of the character array.
3706      * @exception IndexOutOfBoundsException if {@code offset} is
3707      *          negative, or {@code count} is negative, or
3708      *          {@code offset+count} is larger than
3709      *          {@code data.length}.
3710      */
copyValueOf(char data[], int offset, int count)3711     public static String copyValueOf(char data[], int offset, int count) {
3712         return new String(data, offset, count);
3713     }
3714 
3715     /**
3716      * Equivalent to {@link #valueOf(char[])}.
3717      *
3718      * @param   data   the character array.
3719      * @return  a {@code String} that contains the characters of the
3720      *          character array.
3721      */
copyValueOf(char data[])3722     public static String copyValueOf(char data[]) {
3723         return new String(data);
3724     }
3725 
3726     /**
3727      * Returns the string representation of the {@code boolean} argument.
3728      *
3729      * @param   b   a {@code boolean}.
3730      * @return  if the argument is {@code true}, a string equal to
3731      *          {@code "true"} is returned; otherwise, a string equal to
3732      *          {@code "false"} is returned.
3733      */
valueOf(boolean b)3734     public static String valueOf(boolean b) {
3735         return b ? "true" : "false";
3736     }
3737 
3738     /**
3739      * Returns the string representation of the {@code char}
3740      * argument.
3741      *
3742      * @param   c   a {@code char}.
3743      * @return  a string of length {@code 1} containing
3744      *          as its single character the argument {@code c}.
3745      */
valueOf(char c)3746     public static String valueOf(char c) {
3747         // BEGIN Android-changed: Replace constructor call with call to StringFactory class.
3748         // There is currently no String(char[], boolean) on Android to call. http://b/79902155
3749         /*
3750         if (COMPACT_STRINGS && StringLatin1.canEncode(c)) {
3751             return new String(StringLatin1.toBytes(c), LATIN1);
3752         }
3753         return new String(StringUTF16.toBytes(c), UTF16);
3754          */
3755         return StringFactory.newStringFromChars(0, 1, new char[] { c });
3756         // END Android-changed: Replace constructor call with call to StringFactory class.
3757     }
3758 
3759     /**
3760      * Returns the string representation of the {@code int} argument.
3761      * <p>
3762      * The representation is exactly the one returned by the
3763      * {@code Integer.toString} method of one argument.
3764      *
3765      * @param   i   an {@code int}.
3766      * @return  a string representation of the {@code int} argument.
3767      * @see     java.lang.Integer#toString(int, int)
3768      */
valueOf(int i)3769     public static String valueOf(int i) {
3770         return Integer.toString(i);
3771     }
3772 
3773     /**
3774      * Returns the string representation of the {@code long} argument.
3775      * <p>
3776      * The representation is exactly the one returned by the
3777      * {@code Long.toString} method of one argument.
3778      *
3779      * @param   l   a {@code long}.
3780      * @return  a string representation of the {@code long} argument.
3781      * @see     java.lang.Long#toString(long)
3782      */
valueOf(long l)3783     public static String valueOf(long l) {
3784         return Long.toString(l);
3785     }
3786 
3787     /**
3788      * Returns the string representation of the {@code float} argument.
3789      * <p>
3790      * The representation is exactly the one returned by the
3791      * {@code Float.toString} method of one argument.
3792      *
3793      * @param   f   a {@code float}.
3794      * @return  a string representation of the {@code float} argument.
3795      * @see     java.lang.Float#toString(float)
3796      */
valueOf(float f)3797     public static String valueOf(float f) {
3798         return Float.toString(f);
3799     }
3800 
3801     /**
3802      * Returns the string representation of the {@code double} argument.
3803      * <p>
3804      * The representation is exactly the one returned by the
3805      * {@code Double.toString} method of one argument.
3806      *
3807      * @param   d   a {@code double}.
3808      * @return  a  string representation of the {@code double} argument.
3809      * @see     java.lang.Double#toString(double)
3810      */
valueOf(double d)3811     public static String valueOf(double d) {
3812         return Double.toString(d);
3813     }
3814 
3815     /**
3816      * Returns a canonical representation for the string object.
3817      * <p>
3818      * A pool of strings, initially empty, is maintained privately by the
3819      * class {@code String}.
3820      * <p>
3821      * When the intern method is invoked, if the pool already contains a
3822      * string equal to this {@code String} object as determined by
3823      * the {@link #equals(Object)} method, then the string from the pool is
3824      * returned. Otherwise, this {@code String} object is added to the
3825      * pool and a reference to this {@code String} object is returned.
3826      * <p>
3827      * It follows that for any two strings {@code s} and {@code t},
3828      * {@code s.intern() == t.intern()} is {@code true}
3829      * if and only if {@code s.equals(t)} is {@code true}.
3830      * <p>
3831      * All literal strings and string-valued constant expressions are
3832      * interned. String literals are defined in section 3.10.5 of the
3833      * <cite>The Java&trade; Language Specification</cite>.
3834      *
3835      * @return  a string that has the same contents as this string, but is
3836      *          guaranteed to be from a pool of unique strings.
3837      * @jls 3.10.5 String Literals
3838      */
3839     // Android-added: Annotate native method as @FastNative.
3840     @FastNative
intern()3841     public native String intern();
3842 
3843     /**
3844      * Returns a string whose value is the concatenation of this
3845      * string repeated {@code count} times.
3846      * <p>
3847      * If this string is empty or count is zero then the empty
3848      * string is returned.
3849      *
3850      * @param   count number of times to repeat
3851      *
3852      * @return  A string composed of this string repeated
3853      *          {@code count} times or the empty string if this
3854      *          string is empty or count is zero
3855      *
3856      * @throws  IllegalArgumentException if the {@code count} is
3857      *          negative.
3858      *
3859      * @since 11
3860      */
repeat(int count)3861     public String repeat(int count) {
3862         if (count < 0) {
3863             throw new IllegalArgumentException("count is negative: " + count);
3864         }
3865         if (count == 1) {
3866             return this;
3867         }
3868         // Android-changed: Replace with implementation in runtime.
3869         // final int len = value.length;
3870         final int len = length();
3871         if (len == 0 || count == 0) {
3872             return "";
3873         }
3874         // BEGIN Android-changed: Replace with implementation in runtime.
3875         /*
3876         if (len == 1) {
3877             final byte[] single = new byte[count];
3878             Arrays.fill(single, value[0]);
3879             return new String(single, coder);
3880         }
3881         */
3882         // END Android-changed: Replace with implementation in runtime.
3883         if (Integer.MAX_VALUE / count < len) {
3884             throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
3885                     " times will produce a String exceeding maximum size.");
3886         }
3887         // BEGIN Android-changed: Replace with implementation in runtime.
3888         /*
3889         final int limit = len * count;
3890         final byte[] multiple = new byte[limit];
3891         System.arraycopy(value, 0, multiple, 0, len);
3892         int copied = len;
3893         for (; copied < limit - copied; copied <<= 1) {
3894             System.arraycopy(multiple, 0, multiple, copied, copied);
3895         }
3896         System.arraycopy(multiple, 0, multiple, copied, limit - copied);
3897         return new String(multiple, coder);
3898          */
3899         // END Android-changed: Replace with implementation in runtime.
3900         return doRepeat(count);
3901     }
3902 
3903     @FastNative
doRepeat(int count)3904     private native String doRepeat(int count);
3905 
3906     /*
3907      * StringIndexOutOfBoundsException  if {@code index} is
3908      * negative or greater than or equal to {@code length}.
3909      */
checkIndex(int index, int length)3910     static void checkIndex(int index, int length) {
3911         if (index < 0 || index >= length) {
3912             throw new StringIndexOutOfBoundsException("index " + index +
3913                                                       ",length " + length);
3914         }
3915     }
3916 
3917     /*
3918      * Check {@code offset}, {@code count} against {@code 0} and {@code length}
3919      * bounds.
3920      *
3921      * @throws  StringIndexOutOfBoundsException
3922      *          If {@code offset} is negative, {@code count} is negative,
3923      *          or {@code offset} is greater than {@code length - count}
3924      */
checkBoundsOffCount(int offset, int count, int length)3925     static void checkBoundsOffCount(int offset, int count, int length) {
3926         if (offset < 0 || count < 0 || offset > length - count) {
3927             throw new StringIndexOutOfBoundsException(
3928                 "offset " + offset + ", count " + count + ", length " + length);
3929         }
3930     }
3931 
3932     /*
3933      * Check {@code begin}, {@code end} against {@code 0} and {@code length}
3934      * bounds.
3935      *
3936      * @throws  StringIndexOutOfBoundsException
3937      *          If {@code begin} is negative, {@code begin} is greater than
3938      *          {@code end}, or {@code end} is greater than {@code length}.
3939      */
checkBoundsBeginEnd(int begin, int end, int length)3940     static void checkBoundsBeginEnd(int begin, int end, int length) {
3941         if (begin < 0 || begin > end || end > length) {
3942             throw new StringIndexOutOfBoundsException(
3943                 "begin " + begin + ", end " + end + ", length " + length);
3944         }
3945     }
3946 }
3947