OSDN Git Service

* java/lang/String.java (startsWith): Fixed javadoc.
[pf3gnuchains/gcc-fork.git] / libjava / java / lang / String.java
1 /* String.java -- immutable character sequences; the object of string literals
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
3    Free Software Foundation, Inc.
4
5 This file is part of GNU Classpath.
6
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING.  If not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA.
21
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library.  Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
26
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module.  An independent module is a module which is not derived from
34 or based on this library.  If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so.  If you do not wish to do so, delete this
37 exception statement from your version. */
38
39
40 package java.lang;
41
42 import java.io.Serializable;
43 import java.io.UnsupportedEncodingException;
44 import java.lang.Comparable;
45 import java.util.Comparator;
46 import java.util.Locale;
47 import java.util.regex.Pattern;
48 import java.util.regex.PatternSyntaxException;
49
50 /**
51  * Strings represent an immutable set of characters.  All String literals
52  * are instances of this class, and two string literals with the same contents
53  * refer to the same String object.
54  *
55  * <p>This class also includes a number of methods for manipulating the
56  * contents of strings (of course, creating a new object if there are any
57  * changes, as String is immutable). Case mapping relies on Unicode 3.0.0
58  * standards, where some character sequences have a different number of
59  * characters in the uppercase version than the lower case.
60  *
61  * <p>Strings are special, in that they are the only object with an overloaded
62  * operator. When you use '+' with at least one String argument, both
63  * arguments have String conversion performed on them, and another String (not
64  * guaranteed to be unique) results.
65  *
66  * <p>String is special-cased when doing data serialization - rather than
67  * listing the fields of this class, a String object is converted to a string
68  * literal in the object stream.
69  *
70  * @author Paul N. Fisher
71  * @author Eric Blake (ebb9@email.byu.edu)
72  * @author Per Bothner (bothner@cygnus.com)
73  * @since 1.0
74  * @status updated to 1.4
75  */
76 public final class String implements Serializable, Comparable, CharSequence
77 {
78   // WARNING: String is a CORE class in the bootstrap cycle. See the comments
79   // in vm/reference/java/lang/Runtime for implications of this fact.
80
81   /**
82    * This is probably not necessary because this class is special cased already
83    * but it will avoid showing up as a discrepancy when comparing SUIDs.
84    */
85   private static final long serialVersionUID = -6849794470754667710L;
86
87   /**
88    * This is the object that holds the characters that make up the
89    * String.  It might be a char[], or it could be String.  It could
90    * even be `this'.  The actual characters can't be located using
91    * pure Java code.
92    * @see #boffset
93    */
94   private Object data;
95
96   /**
97    * This is a <emph>byte</emph> offset of the actual characters from
98    * the start of the character-holding object.  Don't use this field
99    * in Java code.
100    */
101   private int boffset;
102
103   /**
104    * Holds the number of characters in value.  Package visible for use
105    * by trusted code.
106    */
107   int count;
108
109   /**
110    * Caches the result of hashCode().  If this value is zero, the hashcode
111    * is considered uncached (even if 0 is the correct hash value).
112    */
113   private int cachedHashCode;
114
115   /**
116    * An implementation for {@link CASE_INSENSITIVE_ORDER}.
117    * This must be {@link Serializable}. The class name is dictated by
118    * compatibility with Sun's JDK.
119    */
120   private static final class CaseInsensitiveComparator
121     implements Comparator, Serializable
122   {
123     /**
124      * Compatible with JDK 1.2.
125      */
126     private static final long serialVersionUID = 8575799808933029326L;
127
128     /**
129      * The default private constructor generates unnecessary overhead.
130      */
131     CaseInsensitiveComparator() {}
132
133     /**
134      * Compares to Strings, using
135      * <code>String.compareToIgnoreCase(String)</code>.
136      *
137      * @param o1 the first string
138      * @param o2 the second string
139      * @return &lt; 0, 0, or &gt; 0 depending on the case-insensitive
140      *         comparison of the two strings.
141      * @throws NullPointerException if either argument is null
142      * @throws ClassCastException if either argument is not a String
143      * @see #compareToIgnoreCase(String)
144      */
145     public int compare(Object o1, Object o2)
146     {
147       return ((String) o1).compareToIgnoreCase((String) o2);
148     }
149   } // class CaseInsensitiveComparator
150
151   /**
152    * A Comparator that uses <code>String.compareToIgnoreCase(String)</code>.
153    * This comparator is {@link Serializable}. Note that it ignores Locale,
154    * for that, you want a Collator.
155    *
156    * @see Collator#compare(String, String)
157    * @since 1.2
158    */
159   public static final Comparator CASE_INSENSITIVE_ORDER
160     = new CaseInsensitiveComparator();
161
162   /**
163    * Creates an empty String (length 0). Unless you really need a new object,
164    * consider using <code>""</code> instead.
165    */
166   public String()
167   {
168     data = "".data;
169     boffset = 0;
170     count = 0;
171   }
172
173   /**
174    * Copies the contents of a String to a new String. Since Strings are
175    * immutable, only a shallow copy is performed.
176    *
177    * @param str String to copy
178    * @throws NullPointerException if value is null
179    */
180   public String(String str)
181   {
182     data = str.data;
183     boffset = str.boffset;
184     count = str.count;
185     cachedHashCode = str.cachedHashCode;
186   }
187
188   /**
189    * Creates a new String using the character sequence of the char array.
190    * Subsequent changes to data do not affect the String.
191    *
192    * @param data char array to copy
193    * @throws NullPointerException if data is null
194    */
195   public String(char[] data)
196   {
197     init(data, 0, data.length, false);
198   }
199
200   /**
201    * Creates a new String using the character sequence of a subarray of
202    * characters. The string starts at offset, and copies count chars.
203    * Subsequent changes to data do not affect the String.
204    *
205    * @param data char array to copy
206    * @param offset position (base 0) to start copying out of data
207    * @param count the number of characters from data to copy
208    * @throws NullPointerException if data is null
209    * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
210    *         || offset + count &gt; data.length)
211    *         (while unspecified, this is a StringIndexOutOfBoundsException)
212    */
213   public String(char[] data, int offset, int count)
214   {
215     init(data, offset, count, false);
216   }
217
218   /**
219    * Creates a new String using an 8-bit array of integer values, starting at
220    * an offset, and copying up to the count. Each character c, using
221    * corresponding byte b, is created in the new String as if by performing:
222    *
223    * <pre>
224    * c = (char) (((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
225    * </pre>
226    *
227    * @param ascii array of integer values
228    * @param hibyte top byte of each Unicode character
229    * @param offset position (base 0) to start copying out of ascii
230    * @param count the number of characters from ascii to copy
231    * @throws NullPointerException if ascii is null
232    * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
233    *         || offset + count &gt; ascii.length)
234    *         (while unspecified, this is a StringIndexOutOfBoundsException)
235    * @see #String(byte[])
236    * @see #String(byte[], String)
237    * @see #String(byte[], int, int)
238    * @see #String(byte[], int, int, String)
239    * @deprecated use {@link #String(byte[], int, int, String)} to perform
240    *             correct encoding
241    */
242   public String(byte[] ascii, int hibyte, int offset, int count)
243   {
244     init(ascii, hibyte, offset, count);
245   }
246
247   /**
248    * Creates a new String using an 8-bit array of integer values. Each
249    * character c, using corresponding byte b, is created in the new String
250    * as if by performing:
251    *
252    * <pre>
253    * c = (char) (((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
254    * </pre>
255    *
256    * @param ascii array of integer values
257    * @param hibyte top byte of each Unicode character
258    * @throws NullPointerException if ascii is null
259    * @see #String(byte[])
260    * @see #String(byte[], String)
261    * @see #String(byte[], int, int)
262    * @see #String(byte[], int, int, String)
263    * @see #String(byte[], int, int, int)
264    * @deprecated use {@link #String(byte[], String)} to perform
265    *             correct encoding
266    */
267   public String(byte[] ascii, int hibyte)
268   {
269     init(ascii, hibyte, 0, ascii.length);
270   }
271
272   /**
273    * Creates a new String using the portion of the byte array starting at the
274    * offset and ending at offset + count. Uses the specified encoding type
275    * to decode the byte array, so the resulting string may be longer or
276    * shorter than the byte array. For more decoding control, use
277    * {@link java.nio.charset.CharsetDecoder}, and for valid character sets,
278    * see {@link java.nio.charset.Charset}. The behavior is not specified if
279    * the decoder encounters invalid characters; this implementation throws
280    * an Error.
281    *
282    * @param data byte array to copy
283    * @param offset the offset to start at
284    * @param count the number of characters in the array to use
285    * @param encoding the name of the encoding to use
286    * @throws NullPointerException if data or encoding is null
287    * @throws IndexOutOfBoundsException if offset or count is incorrect
288    *         (while unspecified, this is a StringIndexOutOfBoundsException)
289    * @throws UnsupportedEncodingException if encoding is not found
290    * @throws Error if the decoding fails
291    * @since 1.1
292    */
293   public String(byte[] data, int offset, int count, String encoding)
294     throws UnsupportedEncodingException
295   {
296     init (data, offset, count, encoding);
297   }
298
299   /**
300    * Creates a new String using the byte array. Uses the specified encoding
301    * type to decode the byte array, so the resulting string may be longer or
302    * shorter than the byte array. For more decoding control, use
303    * {@link java.nio.charset.CharsetDecoder}, and for valid character sets,
304    * see {@link java.nio.charset.Charset}. The behavior is not specified if
305    * the decoder encounters invalid characters; this implementation throws
306    * an Error.
307    *
308    * @param data byte array to copy
309    * @param encoding the name of the encoding to use
310    * @throws NullPointerException if data or encoding is null
311    * @throws UnsupportedEncodingException if encoding is not found
312    * @throws Error if the decoding fails
313    * @see #String(byte[], int, int, String)
314    * @since 1.1
315    */
316   public String(byte[] data, String encoding)
317     throws UnsupportedEncodingException
318   {
319     this(data, 0, data.length, encoding);
320   }
321
322   /**
323    * Creates a new String using the portion of the byte array starting at the
324    * offset and ending at offset + count. Uses the encoding of the platform's
325    * default charset, so the resulting string may be longer or shorter than
326    * the byte array. For more decoding control, use
327    * {@link java.nio.charset.CharsetDecoder}.  The behavior is not specified
328    * if the decoder encounters invalid characters; this implementation throws
329    * an Error.
330    *
331    * @param data byte array to copy
332    * @param offset the offset to start at
333    * @param count the number of characters in the array to use
334    * @throws NullPointerException if data is null
335    * @throws IndexOutOfBoundsException if offset or count is incorrect
336    * @throws Error if the decoding fails
337    * @see #String(byte[], int, int, String)
338    * @since 1.1
339    */
340   public String(byte[] data, int offset, int count)
341   {
342     try
343       {
344         init (data, offset, count,
345               System.getProperty("file.encoding", "8859_1"));
346       }
347     catch (UnsupportedEncodingException x1)
348       {
349         // Maybe the default encoding is bad.
350         try
351           {
352             init (data, offset, count, "8859_1");
353           }
354         catch (UnsupportedEncodingException x2)
355           {
356             // We know this can't happen.
357           }
358       }
359   }
360
361   /**
362    * Creates a new String using the byte array. Uses the encoding of the
363    * platform's default charset, so the resulting string may be longer or
364    * shorter than the byte array. For more decoding control, use
365    * {@link java.nio.charset.CharsetDecoder}.  The behavior is not specified
366    * if the decoder encounters invalid characters; this implementation throws
367    * an Error.
368    *
369    * @param data byte array to copy
370    * @throws NullPointerException if data is null
371    * @throws Error if the decoding fails
372    * @see #String(byte[], int, int)
373    * @see #String(byte[], int, int, String)
374    * @since 1.1
375    */
376   public String(byte[] data)
377   {
378     this(data, 0, data.length);
379   }
380
381   /**
382    * Creates a new String using the character sequence represented by
383    * the StringBuffer. Subsequent changes to buf do not affect the String.
384    *
385    * @param buffer StringBuffer to copy
386    * @throws NullPointerException if buffer is null
387    */
388   public String(StringBuffer buffer)
389   {
390     synchronized (buffer)
391       {
392         // Share unless buffer is 3/4 empty.
393         boolean should_copy = ((buffer.count << 2) < buffer.value.length);
394         if (! should_copy)
395           buffer.shared = true;
396         init (buffer.value, 0, buffer.count, ! should_copy);
397       }
398   }
399
400   /**
401    * Creates a new String using the character sequence represented by
402    * the StringBuilder. Subsequent changes to buf do not affect the String.
403    *
404    * @param buffer StringBuilder to copy
405    * @throws NullPointerException if buffer is null
406    */
407   public String(StringBuilder buffer)
408   {
409     this(buffer.value, 0, buffer.count);
410   }
411
412   /**
413    * Special constructor which can share an array when safe to do so.
414    *
415    * @param data the characters to copy
416    * @param offset the location to start from
417    * @param count the number of characters to use
418    * @param dont_copy true if the array is trusted, and need not be copied
419    * @throws NullPointerException if chars is null
420    * @throws StringIndexOutOfBoundsException if bounds check fails
421    */
422   String(char[] data, int offset, int count, boolean dont_copy)
423   {
424     init(data, offset, count, dont_copy);
425   }
426
427   // This is used by gnu.gcj.runtime.StringBuffer, so it must have
428   // package-private protection.  It is accessed via CNI and so avoids
429   // ordinary protection mechanisms.
430   String(gnu.gcj.runtime.StringBuffer buffer)
431   {
432     // No need to synchronize or mark the buffer, since we know it is
433     // only used once.
434     init (buffer);
435   }
436
437   /**
438    * Returns the number of characters contained in this String.
439    *
440    * @return the length of this String
441    */
442   public int length()
443   {
444     return count;
445   }
446
447   /**
448    * Returns the character located at the specified index within this String.
449    *
450    * @param index position of character to return (base 0)
451    * @return character located at position index
452    * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= length()
453    *         (while unspecified, this is a StringIndexOutOfBoundsException)
454    */
455   public native char charAt(int index);
456
457   /**
458    * Copies characters from this String starting at a specified start index,
459    * ending at a specified stop index, to a character array starting at
460    * a specified destination begin index.
461    *
462    * @param srcBegin index to begin copying characters from this String
463    * @param srcEnd index after the last character to be copied from this String
464    * @param dst character array which this String is copied into
465    * @param dstBegin index to start writing characters into dst
466    * @throws NullPointerException if dst is null
467    * @throws IndexOutOfBoundsException if any indices are out of bounds
468    *         (while unspecified, source problems cause a
469    *         StringIndexOutOfBoundsException, and dst problems cause an
470    *         ArrayIndexOutOfBoundsException)
471    */
472   public native void getChars(int srcBegin, int srcEnd,
473                               char[] dst, int dstBegin);
474
475   /**
476    * Copies the low byte of each character from this String starting at a
477    * specified start index, ending at a specified stop index, to a byte array
478    * starting at a specified destination begin index.
479    *
480    * @param srcBegin index to being copying characters from this String
481    * @param srcEnd index after the last character to be copied from this String
482    * @param dst byte array which each low byte of this String is copied into
483    * @param dstBegin index to start writing characters into dst
484    * @throws NullPointerException if dst is null and copy length is non-zero
485    * @throws IndexOutOfBoundsException if any indices are out of bounds
486    *         (while unspecified, source problems cause a
487    *         StringIndexOutOfBoundsException, and dst problems cause an
488    *         ArrayIndexOutOfBoundsException)
489    * @see #getBytes()
490    * @see #getBytes(String)
491    * @deprecated use {@link #getBytes()}, which uses a char to byte encoder
492    */
493   public native void getBytes(int srcBegin, int srcEnd,
494                               byte[] dst, int dstBegin);
495
496   /**
497    * Converts the Unicode characters in this String to a byte array. Uses the
498    * specified encoding method, so the result may be longer or shorter than
499    * the String. For more encoding control, use
500    * {@link java.nio.charset.CharsetEncoder}, and for valid character sets,
501    * see {@link java.nio.charset.Charset}. The behavior is not specified if
502    * the encoder encounters a problem; this implementation returns null.
503    *
504    * @param enc encoding name
505    * @return the resulting byte array, or null on a problem
506    * @throws NullPointerException if enc is null
507    * @throws UnsupportedEncodingException if encoding is not supported
508    * @since 1.1
509    */
510   public native byte[] getBytes(String enc)
511     throws UnsupportedEncodingException;
512
513   /**
514    * Converts the Unicode characters in this String to a byte array. Uses the
515    * encoding of the platform's default charset, so the result may be longer
516    * or shorter than the String. For more encoding control, use
517    * {@link java.nio.charset.CharsetEncoder}.  The behavior is not specified if
518    * the encoder encounters a problem; this implementation returns null.
519    *
520    * @return the resulting byte array, or null on a problem
521    * @since 1.1
522    */
523   public byte[] getBytes()
524   {
525     try
526       {
527         return getBytes (System.getProperty("file.encoding", "8859_1"));
528       }
529     catch (UnsupportedEncodingException x)
530       {
531         // This probably shouldn't happen, but could if file.encoding
532         // is somehow changed to a value we don't understand.
533         try
534           {
535             return getBytes ("8859_1");
536           }
537         catch (UnsupportedEncodingException x2)
538           {
539             // This really shouldn't happen, because the 8859_1
540             // encoding should always be available.
541             throw new InternalError ("couldn't find 8859_1 encoder");
542           }
543       }
544   }
545
546   /**
547    * Predicate which compares anObject to this. This is true only for Strings
548    * with the same character sequence.
549    *
550    * @param anObject the object to compare
551    * @return true if anObject is semantically equal to this
552    * @see #compareTo(String)
553    * @see #equalsIgnoreCase(String)
554    */
555   public native boolean equals(Object anObject);
556
557   /**
558    * Compares the given StringBuffer to this String. This is true if the
559    * StringBuffer has the same content as this String at this moment.
560    *
561    * @param buffer the StringBuffer to compare to
562    * @return true if StringBuffer has the same character sequence
563    * @throws NullPointerException if the given StringBuffer is null
564    * @since 1.4
565    */
566   public native boolean contentEquals(StringBuffer buffer);
567
568   /**
569    * Compares a String to this String, ignoring case. This does not handle
570    * multi-character capitalization exceptions; instead the comparison is
571    * made on a character-by-character basis, and is true if:<br><ul>
572    * <li><code>c1 == c2</code></li>
573    * <li><code>Character.toUpperCase(c1)
574    *     == Character.toUpperCase(c2)</code></li>
575    * <li><code>Character.toLowerCase(c1)
576    *     == Character.toLowerCase(c2)</code></li>
577    * </ul>
578    *
579    * @param anotherString String to compare to this String
580    * @return true if anotherString is equal, ignoring case
581    * @see #equals(Object)
582    * @see Character#toUpperCase(char)
583    * @see Character#toLowerCase(char)
584    */
585   public native boolean equalsIgnoreCase(String anotherString);
586
587   /**
588    * Compares this String and another String (case sensitive,
589    * lexicographically). The result is less than 0 if this string sorts
590    * before the other, 0 if they are equal, and greater than 0 otherwise.
591    * After any common starting sequence is skipped, the result is
592    * <code>this.charAt(k) - anotherString.charAt(k)</code> if both strings
593    * have characters remaining, or
594    * <code>this.length() - anotherString.length()</code> if one string is
595    * a subsequence of the other.
596    *
597    * @param anotherString the String to compare against
598    * @return the comparison
599    * @throws NullPointerException if anotherString is null
600    */
601   public native int compareTo(String anotherString);
602
603   /**
604    * Behaves like <code>compareTo(java.lang.String)</code> unless the Object
605    * is not a <code>String</code>.  Then it throws a
606    * <code>ClassCastException</code>.
607    *
608    * @param o the object to compare against
609    * @return the comparison
610    * @throws NullPointerException if o is null
611    * @throws ClassCastException if o is not a <code>String</code>
612    * @since 1.2
613    */
614   public int compareTo(Object o)
615   {
616     return compareTo((String) o);
617   }
618
619   /**
620    * Compares this String and another String (case insensitive). This
621    * comparison is <em>similar</em> to equalsIgnoreCase, in that it ignores
622    * locale and multi-characater capitalization, and compares characters
623    * after performing
624    * <code>Character.toLowerCase(Character.toUpperCase(c))</code> on each
625    * character of the string. This is unsatisfactory for locale-based
626    * comparison, in which case you should use {@link java.text.Collator}.
627    *
628    * @param str the string to compare against
629    * @return the comparison
630    * @see Collator#compare(String, String)
631    * @since 1.2
632    */
633   public int compareToIgnoreCase(String str)
634   {
635     return this.toUpperCase().toLowerCase().compareTo(
636      str.toUpperCase().toLowerCase());
637   }  
638
639   /**
640    * Predicate which determines if this String matches another String
641    * starting at a specified offset for each String and continuing
642    * for a specified length. Indices out of bounds are harmless, and give
643    * a false result.
644    *
645    * @param toffset index to start comparison at for this String
646    * @param other String to compare region to this String
647    * @param ooffset index to start comparison at for other
648    * @param len number of characters to compare
649    * @return true if regions match (case sensitive)
650    * @throws NullPointerException if other is null
651    */
652   public native boolean regionMatches(int toffset,
653                                       String other, int ooffset, int len);
654
655   /**
656    * Predicate which determines if this String matches another String
657    * starting at a specified offset for each String and continuing
658    * for a specified length, optionally ignoring case. Indices out of bounds
659    * are harmless, and give a false result. Case comparisons are based on
660    * <code>Character.toLowerCase()</code> and
661    * <code>Character.toUpperCase()</code>, not on multi-character
662    * capitalization expansions.
663    *
664    * @param ignoreCase true if case should be ignored in comparision
665    * @param toffset index to start comparison at for this String
666    * @param other String to compare region to this String
667    * @param oofset index to start comparison at for other
668    * @param len number of characters to compare
669    * @return true if regions match, false otherwise
670    * @throws NullPointerException if other is null
671    */
672   public native boolean regionMatches(boolean ignoreCase, int toffset,
673                                       String other, int ooffset, int len);
674
675   /**
676    * Predicate which determines if this String contains the given prefix,
677    * beginning comparison at toffset. The result is false if toffset is
678    * negative or greater than this.length(), otherwise it is the same as
679    * <code>this.substring(toffset).startsWith(prefix)</code>.
680    *
681    * @param prefix String to compare
682    * @param toffset offset for this String where comparison starts
683    * @return true if this String starts with prefix
684    * @throws NullPointerException if prefix is null
685    * @see #regionMatches(boolean, int, String, int, int)
686    */
687   public native boolean startsWith(String prefix, int toffset);
688
689   /**
690    * Predicate which determines if this String starts with a given prefix.
691    * If the prefix is an empty String, true is returned.
692    *
693    * @param prefix String to compare
694    * @return true if this String starts with the prefix
695    * @throws NullPointerException if prefix is null
696    * @see #startsWith(String, int)
697    */
698   public boolean startsWith(String prefix)
699   {
700     return startsWith (prefix, 0);
701   }
702
703   /**
704    * Predicate which determines if this String ends with a given suffix.
705    * If the suffix is an empty String, true is returned.
706    *
707    * @param suffix String to compare
708    * @return true if this String ends with the suffix
709    * @throws NullPointerException if suffix is null
710    * @see #regionMatches(boolean, int, String, int, int)
711    */
712   public boolean endsWith(String suffix)
713   {
714     return regionMatches (this.count - suffix.count, suffix, 0, suffix.count);
715   }
716
717   /**
718    * Computes the hashcode for this String. This is done with int arithmetic,
719    * where ** represents exponentiation, by this formula:<br>
720    * <code>s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]</code>.
721    *
722    * @return hashcode value of this String
723    */
724   public native int hashCode();
725
726   /**
727    * Finds the first instance of a character in this String.
728    *
729    * @param ch character to find
730    * @return location (base 0) of the character, or -1 if not found
731    */
732   public int indexOf(int ch)
733   {
734     return indexOf(ch, 0);
735   }
736
737   /**
738    * Finds the first instance of a character in this String, starting at
739    * a given index.  If starting index is less than 0, the search
740    * starts at the beginning of this String.  If the starting index
741    * is greater than the length of this String, -1 is returned.
742    *
743    * @param ch character to find
744    * @param fromIndex index to start the search
745    * @return location (base 0) of the character, or -1 if not found
746    */
747   public native int indexOf(int ch, int fromIndex);
748
749   /**
750    * Finds the last instance of a character in this String.
751    *
752    * @param ch character to find
753    * @return location (base 0) of the character, or -1 if not found
754    */
755   public int lastIndexOf(int ch)
756   {
757     return lastIndexOf(ch, count - 1);
758   }
759
760   /**
761    * Finds the last instance of a character in this String, starting at
762    * a given index.  If starting index is greater than the maximum valid
763    * index, then the search begins at the end of this String.  If the
764    * starting index is less than zero, -1 is returned.
765    *
766    * @param ch character to find
767    * @param fromIndex index to start the search
768    * @return location (base 0) of the character, or -1 if not found
769    */
770   public native int lastIndexOf(int ch, int fromIndex);
771
772   /**
773    * Finds the first instance of a String in this String.
774    *
775    * @param str String to find
776    * @return location (base 0) of the String, or -1 if not found
777    * @throws NullPointerException if str is null
778    */
779   public int indexOf(String str)
780   {
781     return indexOf(str, 0);
782   }
783
784   /**
785    * Finds the first instance of a String in this String, starting at
786    * a given index.  If starting index is less than 0, the search
787    * starts at the beginning of this String.  If the starting index
788    * is greater than the length of this String, -1 is returned.
789    *
790    * @param str String to find
791    * @param fromIndex index to start the search
792    * @return location (base 0) of the String, or -1 if not found
793    * @throws NullPointerException if str is null
794    */
795   public native int indexOf(String str, int fromIndex);
796
797   /**
798    * Finds the last instance of a String in this String.
799    *
800    * @param str String to find
801    * @return location (base 0) of the String, or -1 if not found
802    * @throws NullPointerException if str is null
803    */
804   public int lastIndexOf(String str)
805   {
806     return lastIndexOf(str, count - str.count);
807   }
808
809   /**
810    * Finds the last instance of a String in this String, starting at
811    * a given index.  If starting index is greater than the maximum valid
812    * index, then the search begins at the end of this String.  If the
813    * starting index is less than zero, -1 is returned.
814    *
815    * @param str String to find
816    * @param fromIndex index to start the search
817    * @return location (base 0) of the String, or -1 if not found
818    * @throws NullPointerException if str is null
819    */
820   public int lastIndexOf(String str, int fromIndex)
821   {
822     if (fromIndex >= count)
823       fromIndex = count - str.count;
824     for (;; --fromIndex)
825       {
826         if (fromIndex < 0)
827           return -1;
828         if (startsWith(str, fromIndex))
829           return fromIndex;
830       }
831   }
832
833   /**
834    * Creates a substring of this String, starting at a specified index
835    * and ending at the end of this String.
836    *
837    * @param begin index to start substring (base 0)
838    * @return new String which is a substring of this String
839    * @throws IndexOutOfBoundsException if begin &lt; 0 || begin &gt; length()
840    *         (while unspecified, this is a StringIndexOutOfBoundsException)
841    */
842   public String substring(int begin)
843   {
844     return substring(begin, count);
845   }
846
847   /**
848    * Creates a substring of this String, starting at a specified index
849    * and ending at one character before a specified index.
850    *
851    * @param begin index to start substring (inclusive, base 0)
852    * @param end index to end at (exclusive)
853    * @return new String which is a substring of this String
854    * @throws IndexOutOfBoundsException if begin &lt; 0 || end &gt; length()
855    *         || begin &gt; end (while unspecified, this is a
856    *         StringIndexOutOfBoundsException)
857    */
858   public native String substring(int begin, int end);
859
860   /**
861    * Creates a substring of this String, starting at a specified index
862    * and ending at one character before a specified index. This behaves like
863    * <code>substring(begin, end)</code>.
864    *
865    * @param begin index to start substring (inclusive, base 0)
866    * @param end index to end at (exclusive)
867    * @return new String which is a substring of this String
868    * @throws IndexOutOfBoundsException if begin &lt; 0 || end &gt; length()
869    *         || begin &gt; end
870    * @since 1.4
871    */
872   public CharSequence subSequence(int begin, int end)
873   {
874     return substring(begin, end);
875   }
876
877   /**
878    * Concatenates a String to this String. This results in a new string unless
879    * one of the two originals is "".
880    *
881    * @param str String to append to this String
882    * @return newly concatenated String
883    * @throws NullPointerException if str is null
884    */
885   public native String concat(String str);
886
887   /**
888    * Replaces every instance of a character in this String with a new
889    * character. If no replacements occur, this is returned.
890    *
891    * @param oldChar the old character to replace
892    * @param newChar the new character
893    * @return new String with all instances of oldChar replaced with newChar
894    */
895   public native String replace(char oldChar, char newChar);
896
897   /**
898    * Test if this String matches a regular expression. This is shorthand for
899    * <code>{@link Pattern}.matches(regex, this)</code>.
900    *
901    * @param regex the pattern to match
902    * @return true if the pattern matches
903    * @throws NullPointerException if regex is null
904    * @throws PatternSyntaxException if regex is invalid
905    * @see Pattern#matches(String, CharSequence)
906    * @since 1.4
907    */
908   public boolean matches(String regex)
909   {
910     return Pattern.matches(regex, this);
911   }
912
913   /**
914    * Replaces the first substring match of the regular expression with a
915    * given replacement. This is shorthand for <code>{@link Pattern}
916    *   .compile(regex).matcher(this).replaceFirst(replacement)</code>.
917    *
918    * @param regex the pattern to match
919    * @param replacement the replacement string
920    * @return the modified string
921    * @throws NullPointerException if regex or replacement is null
922    * @throws PatternSyntaxException if regex is invalid
923    * @see #replaceAll(String, String)
924    * @see Pattern#compile(String)
925    * @see Pattern#matcher(CharSequence)
926    * @see Matcher#replaceFirst(String)
927    * @since 1.4
928    */
929   public String replaceFirst(String regex, String replacement)
930   {
931     return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
932   }
933
934   /**
935    * Replaces all matching substrings of the regular expression with a
936    * given replacement. This is shorthand for <code>{@link Pattern}
937    *   .compile(regex).matcher(this).replaceAll(replacement)</code>.
938    *
939    * @param regex the pattern to match
940    * @param replacement the replacement string
941    * @return the modified string
942    * @throws NullPointerException if regex or replacement is null
943    * @throws PatternSyntaxException if regex is invalid
944    * @see #replaceFirst(String, String)
945    * @see Pattern#compile(String)
946    * @see Pattern#matcher(CharSequence)
947    * @see Matcher#replaceAll(String)
948    * @since 1.4
949    */
950   public String replaceAll(String regex, String replacement)
951   {
952     return Pattern.compile(regex).matcher(this).replaceAll(replacement);
953   }
954
955   /**
956    * Split this string around the matches of a regular expression. Each
957    * element of the returned array is the largest block of characters not
958    * terminated by the regular expression, in the order the matches are found.
959    *
960    * <p>The limit affects the length of the array. If it is positive, the
961    * array will contain at most n elements (n - 1 pattern matches). If
962    * negative, the array length is unlimited, but there can be trailing empty
963    * entries. if 0, the array length is unlimited, and trailing empty entries
964    * are discarded.
965    *
966    * <p>For example, splitting "boo:and:foo" yields:<br>
967    * <table border=0>
968    * <th><td>Regex</td> <td>Limit</td> <td>Result</td></th>
969    * <tr><td>":"</td>   <td>2</td>  <td>{ "boo", "and:foo" }</td></tr>
970    * <tr><td>":"</td>   <td>t</td>  <td>{ "boo", "and", "foo" }</td></tr>
971    * <tr><td>":"</td>   <td>-2</td> <td>{ "boo", "and", "foo" }</td></tr>
972    * <tr><td>"o"</td>   <td>5</td>  <td>{ "b", "", ":and:f", "", "" }</td></tr>
973    * <tr><td>"o"</td>   <td>-2</td> <td>{ "b", "", ":and:f", "", "" }</td></tr>
974    * <tr><td>"o"</td>   <td>0</td>  <td>{ "b", "", ":and:f" }</td></tr>
975    * </table>
976    *
977    * <p>This is shorthand for
978    * <code>{@link Pattern}.compile(regex).split(this, limit)</code>.
979    *
980    * @param regex the pattern to match
981    * @param limit the limit threshold
982    * @return the array of split strings
983    * @throws NullPointerException if regex or replacement is null
984    * @throws PatternSyntaxException if regex is invalid
985    * @see Pattern#compile(String)
986    * @see Pattern#split(CharSequence, int)
987    * @since 1.4
988    */
989   public String[] split(String regex, int limit)
990   {
991     return Pattern.compile(regex).split(this, limit);
992   }
993
994   /**
995    * Split this string around the matches of a regular expression. Each
996    * element of the returned array is the largest block of characters not
997    * terminated by the regular expression, in the order the matches are found.
998    * The array length is unlimited, and trailing empty entries are discarded,
999    * as though calling <code>split(regex, 0)</code>.
1000    *
1001    * @param regex the pattern to match
1002    * @return the array of split strings
1003    * @throws NullPointerException if regex or replacement is null
1004    * @throws PatternSyntaxException if regex is invalid
1005    * @see #split(String, int)
1006    * @see Pattern#compile(String)
1007    * @see Pattern#split(CharSequence, int)
1008    * @since 1.4
1009    */
1010   public String[] split(String regex)
1011   {
1012     return Pattern.compile(regex).split(this, 0);
1013   }
1014
1015   /**
1016    * Lowercases this String according to a particular locale. This uses
1017    * Unicode's special case mappings, as applied to the given Locale, so the
1018    * resulting string may be a different length.
1019    *
1020    * @param loc locale to use
1021    * @return new lowercased String, or this if no characters were lowercased
1022    * @throws NullPointerException if loc is null
1023    * @see #toUpperCase(Locale)
1024    * @since 1.1
1025    */
1026   public native String toLowerCase(Locale locale);
1027
1028   /**
1029    * Lowercases this String. This uses Unicode's special case mappings, as
1030    * applied to the platform's default Locale, so the resulting string may
1031    * be a different length.
1032    *
1033    * @return new lowercased String, or this if no characters were lowercased
1034    * @see #toLowerCase(Locale)
1035    * @see #toUpperCase()
1036    */
1037   public String toLowerCase()
1038   {
1039     // The JDK is a bit confused about what to do here.  If we pass in
1040     // the default Locale then special Locale handling might be
1041     // invoked.  However, the docs also say that Character.toLowerCase
1042     // rules here.  We go with the latter.
1043     return toLowerCase (null);
1044   }
1045
1046   /**
1047    * Uppercases this String according to a particular locale. This uses
1048    * Unicode's special case mappings, as applied to the given Locale, so the
1049    * resulting string may be a different length.
1050    *
1051    * @param loc locale to use
1052    * @return new uppercased String, or this if no characters were uppercased
1053    * @throws NullPointerException if loc is null
1054    * @see #toLowerCase(Locale)
1055    * @since 1.1
1056    */
1057   public native String toUpperCase(Locale locale);
1058
1059   /**
1060    * Uppercases this String. This uses Unicode's special case mappings, as
1061    * applied to the platform's default Locale, so the resulting string may
1062    * be a different length.
1063    *
1064    * @return new uppercased String, or this if no characters were uppercased
1065    * @see #toUpperCase(Locale)
1066    * @see #toLowerCase()
1067    */
1068   public String toUpperCase()
1069   {
1070     // The JDK is a bit confused about what to do here.  If we pass in
1071     // the default Locale then special Locale handling might be
1072     // invoked.  However, the docs also say that Character.toLowerCase
1073     // rules here.  We go with the latter.
1074     return toUpperCase (null);
1075   }
1076
1077   /**
1078    * Trims all characters less than or equal to <code>'\u0020'</code>
1079    * (<code>' '</code>) from the beginning and end of this String. This
1080    * includes many, but not all, ASCII control characters, and all
1081    * {@link Character#whitespace(char)}.
1082    *
1083    * @return new trimmed String, or this if nothing trimmed
1084    */
1085   public native String trim();
1086
1087   /**
1088    * Returns this, as it is already a String!
1089    *
1090    * @return this
1091    */
1092   public String toString()
1093   {
1094     return this;
1095   }
1096
1097   /**
1098    * Copies the contents of this String into a character array. Subsequent
1099    * changes to the array do not affect the String.
1100    *
1101    * @return character array copying the String
1102    */
1103   public native char[] toCharArray();
1104
1105   /**
1106    * Returns a String representation of an Object. This is "null" if the
1107    * object is null, otherwise it is <code>obj.toString()</code> (which
1108    * can be null).
1109    *
1110    * @param obj the Object
1111    * @return the string conversion of obj
1112    */
1113   public static String valueOf(Object obj)
1114   {
1115     return obj == null ? "null" : obj.toString();
1116   }
1117
1118   /**
1119    * Returns a String representation of a character array. Subsequent
1120    * changes to the array do not affect the String.
1121    *
1122    * @param data the character array
1123    * @return a String containing the same character sequence as data
1124    * @throws NullPointerException if data is null
1125    * @see #valueOf(char[], int, int)
1126    * @see #String(char[])
1127    */
1128   public static String valueOf(char[] data)
1129   {
1130     return valueOf (data, 0, data.length);
1131   }
1132
1133   /**
1134    * Returns a String representing the character sequence of the char array,
1135    * starting at the specified offset, and copying chars up to the specified
1136    * count. Subsequent changes to the array do not affect the String.
1137    *
1138    * @param data character array
1139    * @param offset position (base 0) to start copying out of data
1140    * @param count the number of characters from data to copy
1141    * @return String containing the chars from data[offset..offset+count]
1142    * @throws NullPointerException if data is null
1143    * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
1144    *         || offset + count &gt; data.length)
1145    *         (while unspecified, this is a StringIndexOutOfBoundsException)
1146    * @see #String(char[], int, int)
1147    */
1148   public static native String valueOf(char[] data, int offset, int count);
1149
1150   /**
1151    * Returns a String representing the character sequence of the char array,
1152    * starting at the specified offset, and copying chars up to the specified
1153    * count. Subsequent changes to the array do not affect the String.
1154    *
1155    * @param data character array
1156    * @param offset position (base 0) to start copying out of data
1157    * @param count the number of characters from data to copy
1158    * @return String containing the chars from data[offset..offset+count]
1159    * @throws NullPointerException if data is null
1160    * @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
1161    *         || offset + count &gt; data.length)
1162    *         (while unspecified, this is a StringIndexOutOfBoundsException)
1163    * @see #String(char[], int, int)
1164    */
1165   public static String copyValueOf(char[] data, int offset, int count)
1166   {
1167     String r = new String ();
1168     r.init(data, offset, count, false);
1169     return r;
1170   }
1171
1172   /**
1173    * Returns a String representation of a character array. Subsequent
1174    * changes to the array do not affect the String.
1175    *
1176    * @param data the character array
1177    * @return a String containing the same character sequence as data
1178    * @throws NullPointerException if data is null
1179    * @see #copyValueOf(char[], int, int)
1180    * @see #String(char[])
1181    */
1182   public static String copyValueOf(char[] data)
1183   {
1184     return copyValueOf (data, 0, data.length);
1185   }
1186
1187   /**
1188    * Returns a String representing a boolean.
1189    *
1190    * @param b the boolean
1191    * @return "true" if b is true, else "false"
1192    */
1193   public static String valueOf(boolean b)
1194   {
1195     return b ? "true" : "false";
1196   }
1197
1198   /**
1199    * Returns a String representing a character.
1200    *
1201    * @param c the character
1202    * @return String containing the single character c
1203    */
1204   public static native String valueOf(char c);
1205
1206   /**
1207    * Returns a String representing an integer.
1208    *
1209    * @param i the integer
1210    * @return String containing the integer in base 10
1211    * @see Integer#toString(int)
1212    */
1213   public static native String valueOf(int i);
1214
1215   /**
1216    * Returns a String representing a long.
1217    *
1218    * @param l the long
1219    * @return String containing the long in base 10
1220    * @see Long#toString(long)
1221    */
1222   public static String valueOf(long l)
1223   {
1224     return Long.toString(l);
1225   }
1226
1227   /**
1228    * Returns a String representing a float.
1229    *
1230    * @param f the float
1231    * @return String containing the float
1232    * @see Float#toString(float)
1233    */
1234   public static String valueOf(float f)
1235   {
1236     return Float.toString(f);
1237   }
1238
1239   /**
1240    * Returns a String representing a double.
1241    *
1242    * @param d the double
1243    * @return String containing the double
1244    * @see Double#toString(double)
1245    */
1246   public static String valueOf(double d)
1247   {
1248     return Double.toString(d);
1249   }
1250
1251   /**
1252    * Fetches this String from the intern hashtable. If two Strings are
1253    * considered equal, by the equals() method, then intern() will return the
1254    * same String instance. ie. if (s1.equals(s2)) then
1255    * (s1.intern() == s2.intern()). All string literals and string-valued
1256    * constant expressions are already interned.
1257    *
1258    * @return the interned String
1259    */
1260   public native String intern();
1261
1262
1263   private native void init(char[] chars, int offset, int count,
1264                            boolean dont_copy);
1265   private native void init(byte[] chars, int hibyte, int offset, int count);
1266   private native void init(byte[] chars, int offset, int count, String enc)
1267     throws UnsupportedEncodingException;
1268   private native void init(gnu.gcj.runtime.StringBuffer buffer);
1269 }