Share via


20.12 The Class java.lang.String

An object of type String, once created, is immutable. It represents a fixed-length sequence of characters. Compare this to the class StringBuffer(§20.13), which represents a modifiable, variable-length sequence of characters.

The class String has methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, for creating a copy of a string with all characters translated to uppercase or to lowercase, and so on.

public final class String {
 public String();
    public String(String value)
     throws NullPointerException;
    public String(StringBuffer buffer)
     throws NullPointerException;
    public String(char[] value)
     throws NullPointerException;
 public String(char[] value, int offset, int count)
        throws NullPointerException, IndexOutOfBoundsException;
 public String(byte[] ascii, int hibyte)
        throws NullPointerException;
 public String(byte[] ascii, int hibyte,
            int offset, int count)
        throws NullPointerException, IndexOutOfBoundsException;
 public String toString();
 public boolean equals(Object anObject);
 public int hashCode();
 public int length();
 public char charAt(int index);
 public void getChars(int srcBegin, int srcEnd,
            char dst[], int dstBegin)

        throws NullPointerException, IndexOutOfBoundsException;
 public void getBytes(int srcBegin, int srcEnd,
            byte dst[], int dstBegin)
        throws NullPointerException, IndexOutOfBoundsException;
 public char[] toCharArray();
 public boolean equalsIgnoreCase(String anotherString);
 public int compareTo(String anotherString)
        throws NullPointerException;
    public boolean regionMatches(int toffset, String other,

            int ooffset, int len)
     throws NullPointerException;
    public boolean regionMatches(boolean ignoreCase, int toffset,

            String other, int ooffset, int len)
     throws NullPointerException;
    public boolean startsWith(String prefix)
     throws NullPointerException;
    public boolean startsWith(String prefix, int toffset)
     throws NullPointerException;
    public boolean endsWith(String suffix)
     throws NullPointerException;
 public int indexOf(int ch);
 public int indexOf(int ch, int fromIndex);
    public int indexOf(String str)
     throws NullPointerException;
    public int indexOf(String str, int fromIndex)
     throws NullPointerException;
 public int lastIndexOf(int ch);
 public int lastIndexOf(int ch, int fromIndex);
    public int lastIndexOf(String str)
     throws NullPointerException;
    public int lastIndexOf(String str, int fromIndex)
     throws NullPointerException;
 public String substring(int beginIndex);
 public String substring(int beginIndex, int endIndex);
    public String concat(String str)
     throws NullPointerException;
 public String replace(char oldChar, char newChar);
 public String toLowerCase();
 public String toUpperCase();
 public String trim();
 public static String valueOf(Object obj);
    public static String valueOf(char[] data)
     throws NullPointerException;
 public static String valueOf(char[] data,
            int offset, int count)
        throws NullPointerException, IndexOutOfBoundsException;
 public static String valueOf(boolean b);
 public static String valueOf(char c);
 public static String valueOf(int i);
 public static String valueOf(long l);
 public static String valueOf(float f);
 public static String valueOf(double d);
 public String intern();
}

20.12.1 public String()

This constructor initializes a newly created String object so that it represents an empty character sequence.

20.12.2 public String(String value)

This constructor initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

20.12.3 public String(StringBuffer buffer)throws NullPointerException

This constructor initializes a newly created String object so that it represents the sequence of characters that is currently contained in the StringBuffer argument (§20.13). The contents of the string buffer are copied; subsequent modification of the string buffer does not affect the newly created string.

If buffer is null, then a NullPointerException is thrown.

20.12.4 public String(char[] data)throws NullPointerException

This constructor initializes a newly created String object so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

If data is null, then a NullPointerException is thrown.

20.12.5 public String(char[] data, int offset, int count)throws NullPointerException, IndexOutOfBoundsException

This constructor initializes a newly created String object so that it represents the sequence of characters currently contained in a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string.

If data is null, then a NullPointerException is thrown.

If offset is negative, or count is negative, or offset+count is larger than data.length, then an IndexOutOfBoundsException is thrown.

20.12.6 public String(byte[] ascii, int hibyte)throws NullPointerException

This constructor initializes a newly created String object so that it represents a sequence of characters constructed from an array of 8-bit integer values. Each character c in the result string is constructed from the corresponding element b of the byte array in such a way that:

c == ((hibyte & 0xff) << 8) | (b & 0xff)

If ascii is null, then a NullPointerException is thrown.

20.12.7 public String(byte[] ascii, int hibyte, int offset, int count) throws NullPointerException, IndexOutOfBoundsException

This constructor initializes a newly created String object so that it represents the sequence of characters constructed from a subarray of an array of 8-bit integer values. The offset argument is the index of the first byte of the subarray and the count argument specifies the length of the subarray. Each character c in the result string is constructed from the corresponding element b of the byte subarray in such a way that:

c == ((hibyte & 0xff) << 8) | (b & 0xff)

If ascii is null, then a NullPointerException is thrown.

If offset is negative, or count is negative, or offset+count is larger than ascii.length, then an IndexOutOfBoundsException is thrown.

20.12.8 public String toString()

A reference to this object (which is, after all, already a String) is returned.

Overrides the toString method of Object(§20.1.2).

20.12.9 public boolean equals(Object anObject)

The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this String object.

Overrides the equals method of Object(§20.1.3).

See also the methods equalsIgnoreCase(§20.12.16) and compareTo(§20.12.17).

20.12.10 public int hashCode()

The hashcode for a String object is computed in one of two ways, depending on its length. Let n be the length (§20.12.11) of the character sequence and let mean the character with index i.

  • If , then the hashcode is computed as
    using int arithmetic.
  • If , then the hashcode is computed as
    using int arithmetic, where and , sampling only eight or nine characters of the string.

Overrides the hashCode method of Object(§20.1.4).

20.12.11 public int length()

The length of the sequence of characters represented by this String object is returned.

20.12.12 public char charAt(int index)throws IndexOutOfBoundsException

This method returns the character indicated by the index argument within the sequence of characters represented by this String. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the index argument is negative or not less than the length (§20.12.11) of this string, then an IndexOutOfBoundsException is thrown.

20.12.13 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)throws NullPointerException, IndexOutOfBoundsException

Characters are copied from this String object into the destination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index dstbegin+(srcEnd-srcBegin)-1.

If dst is null, then a NullPointerException is thrown.

An IndexOutOfBoundsException is thrown if any of the following is true:

  • srcBegin is negative
  • srcBegin is greater than srcEnd
  • srcEnd is greater than the length of this String
  • dstBegin is negative
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

20.12.14 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin)throws NullPointerException, IndexOutOfBoundsException

Characters are copied from this String object into the destination byte array dst. Each byte receives only the eight low-order bits of the corresponding character. The eight high-order bits of each character are not copied and do not participate in the transfer in any way. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters, converted to bytes, are copied into the subarray of dst starting at index dstBegin and ending at index dstbegin+(srcEnd-srcBegin)-1.

If dst is null, then a NullPointerException is thrown.

An IndexOutOfBoundsException is thrown if any of the following is true:

  • srcBegin is negative
  • srcBegin is greater than srcEnd
  • srcEnd is greater than the length of this String
  • dstBegin is negative
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

20.12.15 public char[] toCharArray()

A new character array is created and returned. The length of the array is equal to the length (§20.12.11) of this String object. The array is initialized to contain the character sequence represented by this String object.

20.12.16 public boolean equalsIgnoreCase(String anotherString)

The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this String object, where case is ignored.

Two characters are considered the same, ignoring case, if at least one of the following is true:

  • The two characters are the same (as compared by the == operator).
  • Applying the method Character.toUppercase(§20.5.21) to each character produces the same result.
  • Applying the method Character.toLowercase(§20.5.20) to each character produces the same result.

Two sequences of characters are the same, ignoring case, if the sequences have the same length and corresponding characters are the same, ignoring case.

See also the method equals(§20.12.9).

20.12.17 public int compareTo(String anotherString)throws NullPointerException

The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals method (§20.12.9) would return true.

If anotherString is null, then a NullPointerException is thrown.

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two strings- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings-that is, the value:

this.length()-anotherString.length()

20.12.18 public boolean regionMatches(int toffset, String other, int ooffset, int len)throws NullPointerException

A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent identical character sequences. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true:

  • toffset is negative.
  • ooffset is negative.
  • toffset+len is greater than the length of this String object.
  • ooffset+len is greater than the length of the other argument.
  • There is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k)

If other is null, then a NullPointerException is thrown.

20.12.19 public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)throws NullPointerException

A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true:

  • toffset is negative.
  • ooffset is negative.
  • toffset+len is greater than the length of this String object.
  • ooffset+len is greater than the length of the other argument.
  • There is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k)
  • ignoreCase is true and there is some nonnegative integer k less than len such that:
Character.toLowerCase(this.charAt(toffset+k)) !=
    Character.toLowerCase(other.charAt(ooffset+k))
Character.toUpperCase(this.charAt(toffset+k)) !=
    Character.toUpperCase(other.charAt(ooffset+k))

If other is null, then a NullPointerException is thrown.

20.12.20 public boolean startsWith(String prefix)throws NullPointerException

The result is true if and only if the character sequence represented by the argument is a prefix of the character sequence represented by this String object.

If prefix is null, a NullPointerException is thrown.

Note that the result will be true if the argument is an empty string or is equal to this String object as determined by the equals method (§20.12.9).

20.12.21 public boolean startsWith(String prefix, int toffset)throws NullPointerException

The result is true if and only if the character sequence represented by the argument is a prefix of the substring of this String object starting at index toffset.

If prefix is null, then a NullPointerException is thrown.

The result is false if toffset is negative or greater than the length of this String object; otherwise, the result is the same as the result of the expression

this.subString(toffset).startsWith(prefix)

20.12.22 public boolean endsWith(String suffix)throws NullPointerException

The result is true if and only if the character sequence represented by the argument is a suffix of the character sequence represented by this String object.

If suffix is null, then a NullPointerException is thrown.

Note that the result will be true if the argument is an empty string or is equal to this String object as determined by the equals method (§20.12.9).

20.12.23 public int indexOf(int ch)

If a character with value ch occurs in the character sequence represented by this String object, then the index of the first such occurrence is returned-that is, the smallest value k such that:

this.charAt(k) == ch

is true. If no such character occurs in this string, then -1 is returned.

20.12.24 public int indexOf(int ch, int fromIndex)

If a character with value ch occurs in the character sequence represented by this String object at an index no smaller than fromIndex, then the index of the first such occurrence is returned-that is, the smallest value k such that:

(this.charAt(k) == ch) && (k >= fromIndex)

is true. If no such character occurs in this string at or after position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.

20.12.25 public int indexOf(String str)throws NullPointerException

If the string str occurs as a substring of this String object, then the index of the first character of the first such substring is returned-that is, the smallest value k such that:

this.startsWith(str, k)

is true. If str does not occur as a substring of this string, then -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.26 public int indexOf(String str, int fromIndex)throws NullPointerException

If the string str occurs as a substring of this String object starting at an index no smaller than fromIndex, then the index of the first character of the first such substring is returned-that is, the smallest value k such that:

this.startsWith(str, k) && (k >= fromIndex)

is true. If str does not occur as a substring of this string at or after position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.27 public int lastIndexOf(int ch)

If a character with value ch occurs in the character sequence represented by this String object, then the index of the last such occurrence is returned-that is, the largest value k such that:

this.charAt(k) == ch

is true. If no such character occurs in this string, then -1 is returned.

20.12.28 public int lastIndexOf(int ch, int fromIndex)

If a character with value ch occurs in the character sequence represented by this String object at an index no larger than fromIndex, then the index of the last such occurrence is returned-that is, the largest value k such that:

(this.charAt(k) == ch) && (k <= fromIndex)

is true. If no such character occurs in this string at or before position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is greater than or equal to the length of this string, it has the same effect as if it were equal to one less than the length of this string: this entire string may be searched. If it is negative, it has the same effect as if it were -1: -1 is returned.

20.12.29 public int lastIndexOf(String str)throws NullPointerException

If the string str occurs as a substring of this String object, then the index of the first character of the last such substring is returned-that is, the largest value k such that:

this.startsWith(str, k)

is true. If str does not occur as a substring of this string, then -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.30 public int lastIndexOf(String str, int fromIndex)throws NullPointerException

If the string str occurs as a substring of this String object starting at an index no larger than fromIndex, then the index of the first character of the last such substring is returned-that is, the largest value k such that:

this.startsWith(str, k) && (k <= fromIndex)

is true. If str does not occur as a substring of this string at or before position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: this entire string may be searched. If it is negative, it has the same effect as if it were -1: -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.31 public String substring(int beginIndex)throws IndexOutOfBoundsException

The result is a newly created String object that represents a subsequence of the character sequence represented by this String object; this subsequence begins with the character at position beginIndex and extends to the end of the character sequence.

If beginIndex is negative or larger than the length of this String object, then an IndexOutOfBoundsException is thrown.

Examples:

"unhappy".substring(2) returns "happy"


"Harbison".substring(3) returns "bison"

"emptiness".substring(9) returns "" (an empty string)

20.12.32 public String substring(int beginIndex, int endIndex)throws IndexOutOfBoundsException

The result is a newly created String object that represents a subsequence of the character sequence represented by this String object; this subsequence begins with the character at position beginIndex and ends with the character at position endIndex-1. Thus, the length of the subsequence is endIndex-beginIndex.

If beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex, then this method throws an IndexOutOfBoundsException.

Examples:

"hamburger".substring(4, 8) returns "urge"

"smiles".substring(1, 5) returns "mile"

20.12.33 public String concat(String str)throws NullPointerException

If the length of the argument string is zero, then a reference to this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Examples:

"cares".concat("s") returns "caress"
"to".concat("get").concat("her") returns "together"

If str is null, a NullPointerException is thrown.

20.12.34 public String replace(char oldChar, char newChar)

If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

Examples:

"mesquite in your cellar".replace('e', 'o')
                    returns "mosquito in your collar"
"the war of baronets".replace('r', 'y')
                    returns "the way of bayonets"
"sparring with a purple porpoise".replace('p', 't')
                    returns "starring with a turtle tortoise"
"JonL".replace('q', 'x') returns "JonL" (no change)

20.12.35 public String toLowerCase()

If this String object does not contain any character that is mapped to a different character by the method Character.toLowerCase(§20.5.20), then a reference to this String object is returned. Otherwise, this method creates a new String object that represents a character sequence identical in length to the character sequence represented by this String object, with every character equal to the result of applying the method Character.toLowerCase to the corresponding character of this String object.

Examples:

"French Fries".toLowerCase() returns "french fries" "".toLowerCase() returns ""

20.12.36 public String toUpperCase()

If this String object does not contain any character that is mapped to a different character by the method Character.toUpperCase(§20.5.21), then a reference to this String object is returned. Otherwise, this method creates a new String object representing a character sequence identical in length to the character sequence represented by this String object and with every character equal to the result of applying the method Character.toUpperCase to the corresponding character of this String object.

Examples:

"Fahrvergnügen".toUpperCase() returns "FAHRVERGNÜGEN"

"Visit Ljubinje!".toUpperCase() returns "VISIT LJUBINJE!"

20.12.37 public String trim()

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than \u0020 (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than \u0020 in the string, then a new String object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than \u0020, and let m be the index of the last character in the string whose code is greater than \u0020. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

This method may be used to trim whitespace (§20.5.19) from the beginning and end of a string; in fact, it trims all ASCII control characters as well.

20.12.38 public static String valueOf(Object obj)

If the argument is null, then a string equal to "null" is returned. Otherwise, the value of obj.toString() is returned. See the toString method (§20.1.2).

20.12.39 public static String valueOf(char[] data)throws NullPointerException

A string is created and returned. The string represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

20.12.40 public static String valueOf(char[] data, int offset, int count) throws NullPointerException, IndexOutOfBoundsException

A string is created and returned. The string represents the sequence of characters currently contained in a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string.

If data is null, then a NullPointerException is thrown.

If offset is negative, or count is negative, or offset+count is larger than data.length, then an IndexOutOfBoundsException is thrown.

20.12.41 public static String valueOf(boolean b)

A string representation of b is returned.

If the argument is true, the string "true" is returned.

If the argument is false, the string "false" is returned.

20.12.42 public static String valueOf(char c)

A string is created and returned. The string contains one character, equal to c.

20.12.43 public static String valueOf(int i)

A string is created and returned. The string is computed exactly as if by the method Integer.toString of one argument (§20.7.12).

20.12.44 public static String valueOf(long l)

A string is created and returned. The string is computed exactly as if by the method Long.toString of one argument (§20.8.12).

20.12.45 public static String valueOf(float f)

A string is created and returned. The string is computed exactly as if by the method Float.toString of one argument (§20.9.16).

20.12.46 public static String valueOf(double d)

A string is created and returned. The string is computed exactly as if by the method Double.toString of one argument (§20.10.15).

20.12.47 public String intern()

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals method (§20.12.9), then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned (§3.10.5).