Java 25 (LTS) reference · 16 entries

Java String Methods

Java String methods: length(), charAt(), substring(), indexOf(), split(), join(), strip(), equals(), formatted() and more, with signatures and complete programs that run.

Strings are immutable: every method returns a new string. Compare text with equals(), never ==.

NameDescriptionSince
string.length() Return the number of characters (UTF-16 code units) in a string. An empty string has length 0. Java 1.0
string.charAt() Return the character at an index (0-based). Throws StringIndexOutOfBoundsException for an invalid index. Java 1.0
string.substring() Return part of a string from a start index up to (not including) an end index. The original is unchanged. Java 1.0
string.indexOf() Return the index of the first occurrence of a character or substring, or -1 if it isn't found. Java 1.0
string.contains() Return true if the string contains a sequence of characters. Case-sensitive. Java 5
string.startsWith() Return true if the string begins with a prefix. endsWith() checks the end the same way. Java 1.0
string.toUpperCase() Return a copy of the string in upper case. toLowerCase() does the opposite. Java 1.0
string.strip() Remove leading and trailing whitespace, including Unicode spaces. Prefer it to the older trim(). Java 11
string.isBlank() Return true if the string is empty or contains only whitespace. isEmpty() is true only for "". Java 11
string.split() Split a string around matches of a regular expression and return the parts as an array. Java 1.0
String.join() Join strings or a collection of strings into one string, with a separator between them. Java 8
string.replace() Replace every occurrence of a character or text with another. replaceAll() uses a regular expression instead. Java 1.0
string.equals() Compare the contents of two strings. Never use == for strings: it compares object identity, not text. Java 1.0
string.compareTo() Compare two strings alphabetically: negative if this comes first, 0 if equal, positive if it comes after. Java 1.0
string.repeat() Return the string repeated n times. Handy for padding, separators and simple text art. Java 11
string.formatted() Fill a format string's placeholders such as %s, %d and %.2f with values. Same as String.format(). Java 15

Was this page helpful?