Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 201 ยท Strings

String Methods

A practical tour of Java String methods - substring, indexOf, contains, replace vs replaceAll, split, join, strip, repeat, chars and lines - with their pitfalls.

The String class has more than 60 methods, but you'll use about twenty of them every day: to find text, cut out a piece, clean up input, change case, replace words and split a line into fields. This lesson walks through those methods in groups, with runnable examples and the edge cases that cause bugs, such as off-by-one substring indexes, replaceAll treating a dot as "any character", and split quietly dropping empty fields.

Keep one rule from Strings in mind throughout: strings are immutable. None of these methods changes the string you call it on. Each one returns a result, usually a new string, that you must store or use.

Quick reference

Task Methods
Find text indexOf, lastIndexOf, contains, startsWith, endsWith
Cut out text substring, charAt, toCharArray
Change case toUpperCase, toLowerCase
Remove whitespace strip, stripLeading, stripTrailing, trim
Replace replace, replaceAll, replaceFirst
Split and join split, String.join, lines
Build repeat, concat
Iterate chars, toCharArray, lines

Searching: indexOf, contains and friends

indexOf returns the position of the first match, and lastIndexOf returns the position of the last one. Both return -1 when nothing is found, so always check for that before using the result. Each has a version that takes a starting position, which lets you find every match in a loop.

contains, startsWith and endsWith answer yes-or-no questions and return a boolean.

Java Finding text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All of these methods are case-sensitive: endsWith(".JPG") is false for a lowercase extension. For a case-insensitive check, convert both sides first, for example name.toLowerCase().endsWith(".jpg").

Extracting text with substring

substring(begin) returns everything from begin to the end. substring(begin, end) returns the characters from begin up to but not including end. That half-open range has a handy property: the length of the result is always end - begin.

TEXT
 index:  0 1 2 3 4 5 6 7 8 9
 text:   J a v a S c r i p t

 substring(0, 4)  ->  "Java"    (indexes 0..3)
 substring(4)     ->  "Script"  (index 4 to the end)

Most real uses combine substring with indexOf: find a separator, then take the parts around it.

Java substring with indexOf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The dot == -1 check matters. Without it, a file name with no dot would call substring(0) (because -1 + 1 is 0) and return the whole name as the "extension", a quiet bug instead of a crash.

When you need the part between two markers, find both positions first: int start = s.indexOf('[') + 1; int end = s.indexOf(']', start); and then s.substring(start, end). Searching for the second marker from start avoids matching one that appears earlier.

Changing case

toUpperCase() and toLowerCase() return converted copies. They're useful for display and for case-insensitive comparisons and lookups:

Java
String command = "Quit";
if (command.toLowerCase().equals("quit")) { ... }   // works
if (command.equalsIgnoreCase("quit")) { ... }       // simpler for a single comparison

Case conversion uses the computer's default language settings, and a few languages have special rules. In Turkish, the uppercase of i is ฤฐ (with a dot), which can break code like key.toUpperCase().equals("TITLE"). For identifiers, keys and protocol text, pass Locale.ROOT: key.toUpperCase(Locale.ROOT). Locales and Internationalization explains this in depth.

Removing whitespace: strip vs trim

Text from users and files often has stray spaces, tabs or newlines at the edges. strip() removes whitespace from both ends; stripLeading() and stripTrailing() remove it from one side only. None of them touch spaces in the middle.

The older trim() does nearly the same job, but its idea of whitespace is "any character with a code up to 32", which misses Unicode spaces such as the non-breaking and em spaces that appear in text copied from web pages and word processors. strip() (Java 11+) uses Character.isWhitespace and handles them. Prefer strip() in new code.

Java strip, trim and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Replacing text: replace vs replaceAll

This pair is one of the most misunderstood parts of the String API, because the names suggest the wrong difference.

  • replace(target, replacement) replaces every occurrence of plain, literal text. There's also a replace(char, char) version.
  • replaceAll(regex, replacement) also replaces every occurrence, but the first argument is a regular expression.
  • replaceFirst(regex, replacement) replaces only the first regex match.

So both replace and replaceAll replace all matches. The real difference is literal text versus a pattern. In a regex, characters like ., *, +, ?, |, (, [, $ and \ have special meanings:

Java replace vs replaceAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second line prints five dashes, because every character matches .. In a Java string literal you need a double backslash, "\\.", to produce the regex \., which means a literal dot. When you just want to swap one piece of text for another, use replace: it's clearer and can't be surprised by special characters. Reach for replaceAll when you genuinely need a pattern, and see Regular Expressions for the full syntax.

Splitting and joining

split(regex) breaks a string into an array of parts wherever the pattern matches. String.join(delimiter, parts) does the opposite: it glues parts together with a separator between each pair.

Because split takes a regex, the same special-character rule applies. And it has a surprising default: trailing empty strings are removed from the result.

Java split and join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

(Compact source files like these examples can use Arrays and List without an import, because they automatically import the whole java.base module. In a regular class you would write import java.util.Arrays;.)

The trailing-empty rule bites when parsing CSV-like data: a line like "Sam,42,," with two empty columns at the end comes back with only two fields. Pass a limit of -1 whenever empty fields carry meaning. And split("|") without escaping splits between every character, because an empty alternative matches everywhere.

For more advanced joining, with a prefix and suffix or from a stream, see StringBuffer, StringJoiner and StringTokenizer.

Building and iterating: repeat, toCharArray, chars, lines

A few more methods round out the toolkit:

  • repeat(n) (Java 11+) returns the string repeated n times. Great for separators and simple text layouts.
  • toCharArray() returns a new char[] copy of the characters, which you can sort or modify freely.
  • chars() returns an IntStream of the character codes, handy with streams.
  • lines() (Java 11+) returns a stream of lines, splitting on \n, \r\n or \r.
Java repeat, toCharArray, chars and lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The :: and -> syntax in that example comes from Lambda Expressions and Method References; for now, read filter(Character::isDigit) as "keep only the digits".

Chaining methods

Because most string methods return a new String, you can call another method on the result right away. A whole cleaning pipeline fits on a few lines:

Java A cleaning pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Format long chains with one call per line, as above, so each step is easy to read and to comment.

Chaining fails if any step returns null, and some methods throw on bad input: substring and charAt throw StringIndexOutOfBoundsException, and repeat throws IllegalArgumentException for a negative count. Validate indexes, especially ones that come from indexOf and might be -1.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "Programming".substring(3, 7) return?

    substring(3, 7) takes indexes 3, 4, 5 and 6 (the end index is excluded), which are g, r, a, m. The length is 7 - 3 = 4.
  2. 2. What does "a.b.c".replaceAll(".", "_") return?

    replaceAll treats its first argument as a regex, and . matches any character, so all five characters are replaced. Use replace(".", "_") for a literal dot.
  3. 3. How many elements are in "x,y,,".split(",")?

    split removes trailing empty strings by default, so the result is ["x", "y"]. Use split(",", -1) to keep them.
  4. 4. What does "banana".indexOf("an", 2) return?

    The search starts at index 2 ("nana"), so the first "an" it finds starts at index 3.
  5. 5. Why prefer strip() over trim() in new code?

    trim() only removes characters with codes up to 32, while strip() uses Character.isWhitespace and handles Unicode spaces. Neither touches inner spaces or changes the original.

Summary

  • indexOf and lastIndexOf return a position or -1; contains, startsWith and endsWith return booleans. All are case-sensitive.
  • substring(begin, end) excludes end, so its length is end - begin. Combine it with indexOf, and check for -1 first.
  • Use toUpperCase(Locale.ROOT) / toLowerCase(Locale.ROOT) for keys and identifiers.
  • strip() is the modern, Unicode-aware replacement for trim().
  • replace swaps literal text everywhere; replaceAll and replaceFirst take a regex, so escape ., | and friends.
  • split takes a regex and drops trailing empty fields unless you pass -1; String.join reverses it.
  • repeat, toCharArray, chars and lines cover building and iterating, and every method returns a new value that you can chain.

Next: Formatting Strings, where you'll line up columns, control decimal places and format numbers for different countries.