- All Implemented Interfaces:
Serializable,CharSequence,Comparable<String>,Constable,ConstantDesc
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2, 3);
String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters
are represented by surrogate pairs
(see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
- Implementation Note:
- The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the
javaccompiler may implement the operator withStringBuffer,StringBuilder, orjava.lang.invoke.StringConcatFactorydepending on the JDK version. The implementation of string conversion is typically through the methodtoString, defined byObjectand inherited by all classes in Java. - See Java Language Specification:
- Moved out of a link with destination https://docs.oracle.com/javase/specs/jls/se20/html/jls-15.html#jls-15.18.1.Moved to a link with destination https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.18.1. Moved out of a link with destination https://docs.oracle.com/javase/specs/jls/se20/html/jls-15.html#jls-15.18.1.Moved to a link with destination https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.18.1.15.18.1 String Concatenation Operator +
- Since:
- 1.0
- See Also:
Fields
- ✓public static final java.util.Comparator<java.lang.String> CASE_INSENSITIVE_ORDER
Constructors
- ✓public String()
- ✓public String(byte[] arg0)
- ✓@Deprecated(since="1.1")
public String(byte[] arg0, int arg1) - ✓public String(byte[] arg0, int arg1, int arg2)
- ✓@Deprecated(since="1.1")
public String(byte[] arg0, int arg1, int arg2, int arg3) - ✓public String(byte[] arg0, int arg1, int arg2, java.lang.String arg3) throws java.io.UnsupportedEncodingException
- ✓public String(byte[] arg0, int arg1, int arg2, java.nio.charset.Charset arg3)
- ✓public String(byte[] arg0, java.lang.String arg1) throws java.io.UnsupportedEncodingException
- ✓public String(byte[] arg0, java.nio.charset.Charset arg1)
- ✓public String(int[] arg0, int arg1, int arg2)
- ✓public String(char[] arg0)
- ✓public String(char[] arg0, int arg1, int arg2)
- ✓public String(java.lang.String arg0)
- ✓public String(java.lang.StringBuffer arg0)
- ✓public String(java.lang.StringBuilder arg0)
Methods
- ✓public char charAt(int arg0)
- ✗public java.util.stream.IntStream chars()Comparing jdk-20-ga and jdk-21+35
chars
Returns a stream ofintzero-extending thecharvalues from this sequence. Any char which maps to a Moved out of a link with destination ../../../java.base/java/lang/Character.html#unicode.Moved to a link with destination Character.html#unicode.surrogate code pointMoved out of a link with destination ../../../java.base/java/lang/Character.html#unicode.Moved to a link with destination Character.html#unicode. is passed through uninterpreted.- Specified by:
charsin interfaceCharSequence- Returns:
- an IntStream of char values from this sequence
- Since:
- 9
- ✓public int codePointAt(int arg0)
- ✓public int codePointBefore(int arg0)
- ✓public int codePointCount(int arg0, int arg1)
- ✓public java.util.stream.IntStream codePoints()
- ✓public int compareTo(java.lang.String arg0)
- ✓public int compareToIgnoreCase(java.lang.String arg0)
- ✓public java.lang.String concat(java.lang.String arg0)
- ✓public boolean contains(java.lang.CharSequence arg0)
- ✓public boolean contentEquals(java.lang.CharSequence arg0)
- ✓public boolean contentEquals(java.lang.StringBuffer arg0)
- ✓public static java.lang.String copyValueOf(char[] arg0)
- ✓public static java.lang.String copyValueOf(char[] arg0, int arg1, int arg2)
- ✓public java.util.Optional<java.lang.String> describeConstable()
- ✓public boolean endsWith(java.lang.String arg0)
- ✓public boolean equals(java.lang.Object arg0)
- ✓public boolean equalsIgnoreCase(java.lang.String arg0)
- ✓public static java.lang.String format(java.lang.String arg0, java.lang.Object[] arg1)
- ✓public static java.lang.String format(java.util.Locale arg0, java.lang.String arg1, java.lang.Object[] arg2)
- ✓public java.lang.String formatted(java.lang.Object[] arg0)
- ✓public byte[] getBytes()
- ✓@Deprecated(since="1.1")
public void getBytes(int arg0, int arg1, byte[] arg2, int arg3) - ✓public byte[] getBytes(java.lang.String arg0) throws java.io.UnsupportedEncodingException
- ✓public byte[] getBytes(java.nio.charset.Charset arg0)
- ✓public void getChars(int arg0, int arg1, char[] arg2, int arg3)
- ✓public int hashCode()
- ✓public java.lang.String indent(int arg0)
- ✓public int indexOf(int arg0)
- ✗public int indexOf(int arg0, int arg1)Comparing jdk-20-ga and jdk-21+35
indexOf
public int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.If a character with value
choccurs in the character sequence represented by thisStringobject at an index no smaller thanfromIndex, then the index of the first such occurrence is returned. For values ofchin the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:
is true. For other values of(this.charAt(k) == ch)
&&(k >= fromIndex)ch, it is the smallest value k such that:
is true. In either case, if no such character occurs in this string at or after position(this.codePointAt(k) == ch)
&&(k >= fromIndex)fromIndex, then-1is 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:-1is returned.All indices are specified in
charvalues (Unicode code units).- API Note:
- Unlike
substring(int), for example, this method does not throw an exception whenfromIndexis outside the valid range. Rather, it returns -1 whenfromIndexis larger than the length of the string. This result is, by itself, indistinguishable from a genuine absence ofchin the string. If stricter behavior is needed,indexOf(int, int, int)should be considered instead. On aStrings, for example,s.indexOf(ch, fromIndex, s.length())would throw iffromIndexwere larger than the string length, or were negative. - Parameters:
ch- a character (Unicode code point).fromIndex- the index to start the search from.- Returns:
- the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to
fromIndex, or-1if the character does not occur.
- ①Only in: jdk-21+35; not in: jdk-20-ga.public int indexOf(int arg0, int arg1, int arg2)Not in jdk-20-ga; only in jdk-21+35
indexOf
public int indexOf(int ch, int beginIndex, int endIndex) Returns the index within this string of the first occurrence of the specified character, starting the search atbeginIndexand stopping beforeendIndex.If a character with value
choccurs in the character sequence represented by thisStringobject at an index no smaller thanbeginIndexbut smaller thanendIndex, then the index of the first such occurrence is returned. For values ofchin the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:
is true. For other values of(this.charAt(k) == ch) && (beginIndex <= k < endIndex)
ch, it is the smallest value k such that:
is true. In either case, if no such character occurs in this string at or after position(this.codePointAt(k) == ch) && (beginIndex <= k < endIndex)
beginIndexand before positionendIndex, then-1is returned.All indices are specified in
charvalues (Unicode code units).- Parameters:
ch- a character (Unicode code point).beginIndex- the index to start the search from (included).endIndex- the index to stop the search at (excluded).- Returns:
- the index of the first occurrence of the character in the
character sequence represented by this object that is greater
than or equal to
beginIndexand less thanendIndex, or-1if the character does not occur. - Throws:
StringIndexOutOfBoundsException- ifbeginIndexis negative, orendIndexis larger than the length of thisStringobject, orbeginIndexis larger thanendIndex.- Since:
- 21
- ✓public int indexOf(java.lang.String arg0)
- ✗public int indexOf(java.lang.String arg0, int arg1)Comparing jdk-20-ga and jdk-21+35
indexOf
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.The returned index is the smallest value
kfor which:
If no such value ofk >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)kexists, then-1is returned.- API Note:
- Unlike
substring(int), for example, this method does not throw an exception whenfromIndexis outside the valid range. Rather, it returns -1 whenfromIndexis larger than the length of the string. This result is, by itself, indistinguishable from a genuine absence ofstrin the string. If stricter behavior is needed,indexOf(String, int, int)should be considered instead. OnStringsand a non-emptystr, for example,s.indexOf(str, fromIndex, s.length())would throw iffromIndexwere larger than the string length, or were negative. - Parameters:
str- the substring to search for.fromIndex- the index from which to start the search.- Returns:
- the index of the first occurrence of the specified substring, starting at the specified index, or
-1if there is no such occurrence.
- ①Only in: jdk-21+35; not in: jdk-20-ga.public int indexOf(java.lang.String arg0, int arg1, int arg2)Not in jdk-20-ga; only in jdk-21+35
indexOf
Returns the index of the first occurrence of the specified substring within the specified index range ofthisstring.This method returns the same result as the one of the invocation
if the index returned bys.substring(beginIndex, endIndex).indexOf(str) + beginIndexindexOf(String)is non-negative, and returns -1 otherwise. (No substring is instantiated, though.)- Parameters:
str- the substring to search for.beginIndex- the index to start the search from (included).endIndex- the index to stop the search at (excluded).- Returns:
- the index of the first occurrence of the specified substring
within the specified index range,
or
-1if there is no such occurrence. - Throws:
StringIndexOutOfBoundsException- ifbeginIndexis negative, orendIndexis larger than the length of thisStringobject, orbeginIndexis larger thanendIndex.- Since:
- 21
- ✗public java.lang.String intern()Comparing jdk-20-ga and jdk-21+35
intern
Returns a canonical representation for the string object.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
Stringobject as determined by theequals(Object)method, then the string from the pool is returned. Otherwise, thisStringobject is added to the pool and a reference to thisStringobject is returned.It follows that for any two strings
sandt,s.intern() == t.intern()istrueif and only ifs.equals(t)istrue.All literal strings and string-valued constant expressions are interned. String literals are defined in section Moved out of a link with destination https://docs.oracle.com/javase/specs/jls/se20/html/jls-3.html#jls-3.10.5.Moved to a link with destination https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.5.3.10.5Moved out of a link with destination https://docs.oracle.com/javase/specs/jls/se20/html/jls-3.html#jls-3.10.5.Moved to a link with destination https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.5. of the The Java Language Specification .
- Returns:
- a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
- ✓public boolean isBlank()
- ✓public boolean isEmpty()
- ✓public static java.lang.String join(java.lang.CharSequence arg0, java.lang.CharSequence[] arg1)
- ✓public static java.lang.String join(java.lang.CharSequence arg0, java.lang.Iterable<? extends java.lang.CharSequence> arg1)
- ✓public int lastIndexOf(int arg0)
- ✓public int lastIndexOf(int arg0, int arg1)
- ✓public int lastIndexOf(java.lang.String arg0)
- ✓public int lastIndexOf(java.lang.String arg0, int arg1)
- ✓public int length()
- ✓public java.util.stream.Stream<java.lang.String> lines()
- ✓public boolean matches(java.lang.String arg0)
- ✓public int offsetByCodePoints(int arg0, int arg1)
- ✓public boolean regionMatches(boolean arg0, int arg1, java.lang.String arg2, int arg3, int arg4)
- ✓public boolean regionMatches(int arg0, java.lang.String arg1, int arg2, int arg3)
- ✓public java.lang.String repeat(int arg0)
- ✓public java.lang.String replace(char arg0, char arg1)
- ✓public java.lang.String replace(java.lang.CharSequence arg0, java.lang.CharSequence arg1)
- ✓public java.lang.String replaceAll(java.lang.String arg0, java.lang.String arg1)
- ✓public java.lang.String replaceFirst(java.lang.String arg0, java.lang.String arg1)
- ✓public java.lang.String resolveConstantDesc(java.lang.invoke.MethodHandles.Lookup arg0)
- ✓public java.lang.String[] split(java.lang.String arg0)
- ✓public java.lang.String[] split(java.lang.String arg0, int arg1)
- ①Only in: jdk-21+35; not in: jdk-20-ga.public java.lang.String[] splitWithDelimiters(java.lang.String arg0, int arg1)Not in jdk-20-ga; only in jdk-21+35
splitWithDelimiters
Splits this string around matches of the given regular expression and returns both the strings and the matching delimiters.The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. Each substring is immediately followed by the subsequence (the delimiter) that matches the given expression, except for the last substring, which is not followed by anything. The substrings in the array and the delimiters are in the order in which they occur in the input. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring nor the empty delimiter.
The
limitparameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.- If the limit is positive then the pattern will be applied at most limit - 1 times, the array's length will be no greater than 2 × limit - 1, and the array's last entry will contain all input beyond the last matched delimiter.
- If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
- If the limit is negative then the pattern will be applied as many times as possible and the array can have any length.
The input
"boo:::and::foo", for example, yields the following results with these parameters:Regex Limit Result :+ 2 { "boo", ":::", "and::foo" }5 { "boo", ":::", "and", "::", "foo" }-1 { "boo", ":::", "and", "::", "foo" }o 5 { "b", "o", "", "o", ":::and::f", "o", "", "o", "" }-1 { "b", "o", "", "o", ":::and::f", "o", "", "o", "" }0 { "b", "o", "", "o", ":::and::f", "o", "", "o" }- API Note:
- An invocation of this method of the form
str.
splitWithDelimiters(regex,n)yields the same result as the expressionPattern.compile(regex).splitWithDelimiters(str, n) - Parameters:
regex- the delimiting regular expressionlimit- the result threshold, as described above- Returns:
- the array of strings computed by splitting this string around matches of the given regular expression, alternating substrings and matching delimiters
- Since:
- 21
- ✓public boolean startsWith(java.lang.String arg0)
- ✓public boolean startsWith(java.lang.String arg0, int arg1)
- ✓public java.lang.String strip()
- ✓public java.lang.String stripIndent()
- ✓public java.lang.String stripLeading()
- ✓public java.lang.String stripTrailing()
- ✓public java.lang.CharSequence subSequence(int arg0, int arg1)
- ✓public java.lang.String substring(int arg0)
- ✓public java.lang.String substring(int arg0, int arg1)
- ✓public char[] toCharArray()
- ✗public java.lang.String toLowerCase()Comparing jdk-20-ga and jdk-21+35
toLowerCase
Converts all of the characters in thisStringto lower case using the rules of the default locale. This method is equivalent totoLowerCase(Locale.getDefault()).Moved out of a paragraph.- API Moved out of a division with class block.Moved out of a paragraph.Bold style removed.Moved to a definition list with class notes.Moved to a definition term.Note: Moved out of a division with class block.Moved out of a paragraph.Bold style removed.Moved to a definition list with class notes.Moved to a definition term.
- Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition.This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance,
Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition."TITLE".toLowerCase()Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition. in a Turkish locale returnsMoved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition."t\u0131tle"Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition., where '\u0131' is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, useMoved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition.toLowerCase(Locale.ROOT)Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition..
- Returns:
- the
String, converted to lowercase. - See Also:
- ✓public java.lang.String toLowerCase(java.util.Locale arg0)
- ✓public java.lang.String toString()
- ✗public java.lang.String toUpperCase()Comparing jdk-20-ga and jdk-21+35
toUpperCase
Converts all of the characters in thisStringto upper case using the rules of the default locale. This method is equivalent totoUpperCase(Locale.getDefault()).Moved out of a paragraph.- API Moved out of a division with class block.Moved out of a paragraph.Bold style removed.Moved to a definition list with class notes.Moved to a definition term.Note: Moved out of a division with class block.Moved out of a paragraph.Bold style removed.Moved to a definition list with class notes.Moved to a definition term.
- Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition.This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance,
Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition."title".toUpperCase()Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition. in a Turkish locale returnsMoved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition."T\u0130TLE"Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition., where '\u0130' is the LATIN CAPITAL LETTER I WITH DOT ABOVE character. To obtain correct results for locale insensitive strings, useMoved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition.toUpperCase(Locale.ROOT)Moved out of a division with class block.Moved out of a paragraph.Moved to a definition list with class notes.Moved to a definition..
- Returns:
- the
String, converted to uppercase. - See Also:
- ✓public java.lang.String toUpperCase(java.util.Locale arg0)
- ✓public <R> R transform(java.util.function.Function<? super java.lang.String, ? extends R> arg0)
- ✗public java.lang.String translateEscapes()Comparing jdk-20-ga and jdk-21+35
translateEscapes
Returns a string whose value is this string, with escape sequences translated as if in a string literal.Escape sequences are translated as follows;
Escape Name Translation \bbackspace U+0008\thorizontal tab U+0009\nline feed U+000A\fform feed U+000C\rcarriage return U+000D\sspace U+0020\"double quote U+0022\'single quote U+0027\\backslash U+005C\0 - \377octal escape code point equivalents \<line-terminator>continuation discard - Implementation Note:
- This method does not
translate Unicode escapes such as "
\u2022". Unicode escapes are translated by the Java compiler when reading input characters and are not part of the string literal specification. - Returns:
- String with escape sequences translated.
- Throws:
IllegalArgumentException- when an escape sequence is malformed.- See Java Language Specification:
- Moved out of a link with destination https://docs.oracle.com/javase/specs/jls/se20/html/jls-3.html#jls-3.10.7.Moved to a link with destination https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.7. Moved out of a link with destination https://docs.oracle.com/javase/specs/jls/se20/html/jls-3.html#jls-3.10.7.Moved to a link with destination https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.7.3.10.7 Escape Sequences
- Since:
- 15
- ✓public java.lang.String trim()
- ✓public static java.lang.String valueOf(boolean arg0)
- ✓public static java.lang.String valueOf(int arg0)
- ✓public static java.lang.String valueOf(long arg0)
- ✓public static java.lang.String valueOf(char arg0)
- ✓public static java.lang.String valueOf(float arg0)
- ✓public static java.lang.String valueOf(double arg0)
- ✓public static java.lang.String valueOf(char[] arg0)
- ✓public static java.lang.String valueOf(char[] arg0, int arg1, int arg2)
- ✓public static java.lang.String valueOf(java.lang.Object arg0)
Serialized Form
✓serialVersionUID
✓-6849794470754667710Summary
| Elements | Comments | Descriptions | Total | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Added | Changed | Removed | Added | Changed | Removed | Added | Changed | Removed | ||
| String | 1 | 1 | ||||||||
| chars() | 2 | 2 | ||||||||
| indexOf(int,int) | 1 | 1 | ||||||||
| indexOf(int,int,int) | 1 | 1 | 2 | |||||||
| indexOf(String,int) | 1 | 1 | ||||||||
| indexOf(String,int,int) | 1 | 1 | 2 | |||||||
| intern() | 2 | 2 | ||||||||
| splitWithDelimiters(String,int) | 1 | 1 | 2 | |||||||
| toLowerCase() | 1 | 2 | 3 | |||||||
| toUpperCase() | 1 | 2 | 3 | |||||||
| translateEscapes() | 1 | 1 | ||||||||
| Total | 3 | 7 | 10 | 20 | ||||||