W3docs

Java String Methods

A reference of common Java String methods — length, charAt, substring, indexOf, replace, split, toUpperCase, trim, and more.

The String class ships with dozens of methods. This chapter is a working reference of the ones you'll actually use, grouped by what they do.

Remember: strings are immutable. Every method below returns a new string (or another value), never mutating the receiver.

Inspecting a string

MethodWhat it returns
length()number of UTF-16 code units
isEmpty()true if length is 0
isBlank() (Java 11+)true if length is 0 or only whitespace
charAt(int i)the character at index i
codePointAt(int i)the Unicode code point at index i
"hello".length();      // 5
"".isEmpty();          // true
"   ".isBlank();       // true
"hello".charAt(1);     // 'e'

Comparing strings

MethodWhat it returns
equals(other)true if contents are equal
equalsIgnoreCase(other)case-insensitive equality
compareTo(other)negative / 0 / positive lexicographic ordering
compareToIgnoreCase(other)same, ignoring case
"hi".equals("hi");                  // true
"HI".equalsIgnoreCase("hi");        // true
"apple".compareTo("banana");        // negative

Always prefer .equals() over == for content comparison (Comparison Operators).

Searching

MethodWhat it returns
contains(seq)true if seq appears anywhere
indexOf(seq)first index where seq starts, or -1
indexOf(seq, fromIndex)same, starting at fromIndex
lastIndexOf(seq)last index where seq starts, or -1
startsWith(prefix)true if string begins with prefix
endsWith(suffix)true if string ends with suffix
String s = "abc-xyz-abc";
s.contains("xyz");       // true
s.indexOf("abc");        // 0
s.lastIndexOf("abc");    // 8
s.startsWith("abc");     // true
s.endsWith("xyz");       // false

Slicing

MethodWhat it returns
substring(start)from index start to end
substring(start, end)from start (inclusive) to end (exclusive)
String s = "Hello, World!";
s.substring(7);        // "World!"
s.substring(7, 12);    // "World"

Negative indexes are not allowed — they throw StringIndexOutOfBoundsException.

Transforming

MethodWhat it returns
toUpperCase()uppercase copy
toLowerCase()lowercase copy
trim()copy without leading/trailing ASCII whitespace
strip() (Java 11+)copy without leading/trailing Unicode whitespace
replace(old, new)every literal match replaced
replaceAll(regex, replacement)regex-based replace
replaceFirst(regex, replacement)regex, first match only
repeat(n) (Java 11+)the string repeated n times
concat(other)identical to s + other
"  hello  ".strip();                 // "hello"
"banana".replace("a", "_");          // "b_n_n_"
"hello".repeat(3);                   // "hellohellohello"
"abc 123".replaceAll("\\d", "*");    // "abc ***"

Splitting and joining

MethodWhat it returns
split(regex)array of substrings
split(regex, limit)same, but limited to limit pieces
String.join(sep, parts...)static method — joins with separator
chars()IntStream of UTF-16 code units
lines() (Java 11+)Stream<String> of lines
"a,b,c".split(",");                     // ["a","b","c"]
String.join("-", "a", "b", "c");        // "a-b-c"
String.join(",", List.of("a","b"));     // "a,b"
"line1\nline2\nline3".lines().count();  // 3

split takes a regex, not a plain string — so escape regex meta-characters: split("\\.") to split on a dot.

Conversion

MethodWhat it returns
toCharArray()char[] of the string's characters
getBytes()UTF-8 byte array (or platform encoding, depending on overload)
String.valueOf(any)static — converts any value to a string
Integer.parseInt(s)parses a string into an int
Double.parseDouble(s)parses a string into a double
Boolean.parseBoolean(s)parses a string into a boolean
String.valueOf(42);              // "42"
Integer.parseInt("42");          // 42
Double.parseDouble("3.14");      // 3.14
"hello".toCharArray();           // {'h','e','l','l','o'}

Formatting

MethodWhat it returns
String.format(fmt, args...)static — printf-style formatted string
formatted(args...) (Java 15+)instance method, same as format with this as fmt
String.format("%s is %d", "Ada", 36);     // "Ada is 36"
"%s is %d".formatted("Ada", 36);          // "Ada is 36"

A combined demonstration

java— editable, runs on the server

What's next

Java String Concatenation digs into +, concat, and StringBuilder, including when each is the right tool.

Practice

Practice

Which method returns true if a string contains only whitespace?