1. Introduction
Java's String class provides many methods for searching text, extracting portions of a string, replacing content, splitting text into parts, changing letter case, removing whitespace, and combining strings. These methods are useful when processing product names, order references, email addresses, file names, form input, and other everyday text.
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockA central rule applies to the methods covered in this guide: they do not modify the original String object. Instead, methods that transform text return a new string. Always use the returned value if you want to keep the transformed result.
Examples in this article use public class Main and public static void main(String[] args) so complete programs can run in a typical online Java compiler.
2. Learning Objectives
By the end of this guide, you will be able to:
- Search for characters and substrings with
indexOf()andlastIndexOf(). - Extract text using
substring()and handle its index boundaries correctly. - Choose between literal replacement and regular-expression replacement.
- Split strings and join collections of strings.
- Change case and remove leading or trailing whitespace.
- Check whether text contains a value or begins or ends with a specific sequence.
- Use
repeat()andchars()appropriately.
3. Searching Inside a String
3.1 indexOf()
indexOf() returns the index of the first occurrence of a character or substring. Java string indexes start at 0. If the target is not found, the method returns -1.
3.2 lastIndexOf()
lastIndexOf() returns the index of the last occurrence of the target. This is useful when extracting a file extension or finding the final separator in a path.
Output
0
10
-1
Both methods also have overloads that accept a fromIndex. For indexOf(), the search begins at or after that position. For lastIndexOf(), fromIndex is the rightmost position at which the backward search may begin.
Output
1
3
5
Last a at or before index 3: 3
Always check for -1 before using a search result in index arithmetic or passing it to another method.
4. Extracting Text with substring()
substring() returns a portion of a string. It has two common forms:
substring(beginIndex)returns the text frombeginIndexthrough the end.substring(beginIndex, endIndex)returns text frombeginIndex(inclusive) toendIndex(exclusive).
The length of a substring produced by the two-index form is endIndex - beginIndex.
Output
2024-58
2024
58
4.1 Extracting a File Extension
Combine lastIndexOf() and substring() when the location of a delimiter is not fixed.
Output
Extension: pdfThe + 1 skips the dot. The check also avoids treating a missing dot or a final dot as a normal extension.
Valid boundaries satisfy:
0 <= beginIndex <= endIndex <= string.length()
Invalid boundaries cause StringIndexOutOfBoundsException. Calling substring(0, s.length()) is valid, and calling substring(s.length()) returns an empty string.
5. Replacing Text
Java offers literal replacement methods and regular-expression replacement methods. Choose the correct family for the task.
5.1 Literal replacement with replace()
replace(char oldChar, char newChar)replaces every occurrence of a character.replace(CharSequence target, CharSequence replacement)replaces every matching literal sequence.
Output
12 Park Street, Park City
987 654 3210
12 Main Street, Main City
The original address remains unchanged.
5.2 Regex replacement with replaceAll() and replaceFirst()
replaceAll(regex, replacement)replaces every match of a regular expression.replaceFirst(regex, replacement)replaces only the first match.
Output
Item # costs #.## and item # costs #.##
Item ORDER costs 29.99 and item 13 costs 39.99
In a regular expression, a dot (.) means “any character,” not a literal dot. For a fixed literal replacement, prefer replace().
Output
29,99
29,99
Both work here, but the first is simpler for literal text. Other regex metacharacters include *, +, ?, (, ), [, ], {, }, |, ^, $, and backslash.
6. Splitting a String with split()
split(String regex) divides a string wherever the regular expression matches and returns a String[] array.
Output
[Books, Games, Electronics]
Books
Games
Electronics
The argument is a regular expression. A comma has no special regex meaning, so split(",") works directly. A dot does have special meaning, so split on a literal dot with split("\\.").
Output
[invoice, pdf]6.1 Trailing Empty Values
By default, split(regex) discards trailing empty strings. Use the two-argument form with a negative limit to preserve them.
Output
[alice, bob]
[alice, bob, , ]
If the same regex is used repeatedly in a performance-critical loop, consider compiling a Pattern once and reusing it.
7. Changing Letter Case
toUpperCase() and toLowerCase() return new strings with letters converted to upper or lower case. Non-letter characters generally remain unchanged.
Output
WIRELESS MOUSE - BLACK
wireless mouse - black
Wireless Mouse - Black
title
The no-argument methods use the JVM's default locale. For locale-independent normalization—such as technical identifiers or case-normalized comparisons—use toLowerCase(Locale.ROOT) where appropriate. Case conversion is not always a simple one-character-to-one-character transformation in every language.
8. Removing Whitespace: trim() and strip()
Text from forms, CSV files, or copy-and-paste operations can contain unwanted whitespace at the beginning or end.
trim()removes leading and trailing characters whose values are at or below U+0020.strip()removes leading and trailing characters recognized as whitespace byCharacter.isWhitespace().stripLeading()removes whitespace only at the beginning.stripTrailing()removes whitespace only at the end.
strip(), stripLeading(), and stripTrailing() were introduced in Java 11.
Output
[Java String Methods]
[Java String Methods]
[Java String Methods ]
[ Java String Methods]
For ordinary ASCII spaces, trim() and strip() often appear identical. With Unicode whitespace, their behavior can differ. Prefer strip() in new Java 11+ code when Unicode whitespace handling is desired.
9. Checking String Content
These methods answer whether a string contains a sequence or matches a prefix or suffix:
contains(CharSequence target)checks whether the target occurs anywhere.startsWith(String prefix)checks the beginning of the string.startsWith(String prefix, int offset)checks for a prefix at a specified position.endsWith(String suffix)checks the end of the string.
Output
true
true
true
true
startsWith(prefix, offset) can avoid creating a temporary substring just to compare a segment. These checks are case-sensitive. Java does not provide a containsIgnoreCase() method; one practical approach is to normalize both strings with a consistent locale before checking.
Output
true10. Repeating a String with repeat()
Java 11 introduced repeat(int count), which returns the original string repeated the requested number of times. A count of zero returns an empty string. A negative count throws IllegalArgumentException.
Output
----------hahaha0
This is convenient for dividers or repeated padding. On Java versions before 11, similar output can be built using a loop and StringBuilder.
11. Joining Text with String.join()
String.join() combines several character sequences with a delimiter between adjacent elements. It supports varargs and an Iterable, such as a list.
Output
store/orders/2024sale, popular, new
The delimiter appears only between elements, not at the beginning or end. An empty iterable produces an empty string; a one-element iterable produces that element without a delimiter. String.join() is generally clearer than repeatedly concatenating strings with += in a loop.
12. Inspecting Characters with chars()
chars() returns an IntStream of the string's UTF-16 char values converted to integers. It can be useful with stream operations such as filter() and count().
Output
Digits: 6For beginner-friendly character-by-character processing, a for loop using length() and charAt(i) is also a useful option. Note that chars() processes UTF-16 code units; supplementary Unicode characters may require codePoints() when working with full Unicode code points.
13. String Method Reference Table
| Method | Return type | Purpose |
|---|---|---|
indexOf(char) / indexOf(String) | int | Index of first match, or -1 |
indexOf(target, fromIndex) | int | First match at or after a starting index |
lastIndexOf(target) | int | Index of last match, or -1 |
lastIndexOf(target, fromIndex) | int | Last match at or before the specified index |
substring(beginIndex) | String | Text from the given index to the end |
substring(beginIndex, endIndex) | String | Text from begin (inclusive) to end (exclusive) |
replace(char, char) | String | Literal character replacement |
replace(CharSequence, CharSequence) | String | Literal sequence replacement |
replaceAll(regex, replacement) | String | Replace every regex match |
replaceFirst(regex, replacement) | String | Replace the first regex match |
split(regex) | String[] | Split around regex matches |
toUpperCase() | String | Convert to uppercase |
toLowerCase() | String | Convert to lowercase |
trim() | String | Remove limited whitespace from both ends |
strip() | String | Remove recognized whitespace from both ends (Java 11+) |
stripLeading() | String | Remove leading whitespace (Java 11+) |
stripTrailing() | String | Remove trailing whitespace (Java 11+) |
contains(target) | boolean | Check whether a sequence occurs |
startsWith(prefix) | boolean | Check the beginning |
startsWith(prefix, offset) | boolean | Check a prefix at a position |
endsWith(suffix) | boolean | Check the ending |
repeat(count) | String | Repeat text (Java 11+) |
chars() | IntStream | Stream of UTF-16 char values as integers |
String.join(delimiter, ...) | String | Join pieces with a delimiter |
14. Common Mistakes to Avoid
- Assuming a method changes the original string. Assign the returned value if you want to keep it:
text = text.strip();. - Treating
-1as a valid search index. Check whetherindexOf()orlastIndexOf()found a match before using the result. - Forgetting that
substring()excludesendIndex. The second index marks the position just after the final character to include. - Forgetting to skip a delimiter. Use
delimiterIndex + 1when extracting text after a one-character delimiter. - Using
replaceAll()for fixed literal text. Regex metacharacters may match more than intended; preferreplace()for literal replacements. - Forgetting that
split()accepts a regex. Escape special regex characters such as a literal dot. - Ignoring trailing empty fields. Use
split(regex, -1)when trailing empty strings must be retained. - Assuming case checks ignore case.
contains(),startsWith(), andendsWith()are case-sensitive. - Using Java 11 methods on older runtimes.
strip(),repeat(), and related methods require Java 11 or later.
15. Best Practices
- Prefer
contains()when you only need a yes/no answer, rather than the exact index. - Use
replace()for literal replacement and regex methods only when a pattern is required. - Validate search results before passing their indexes into
substring(). - Choose
strip()for Unicode-aware whitespace removal in Java 11+ applications. - Use
Locale.ROOTfor locale-independent case normalization when appropriate. - Use
String.join()when joining an existing collection of strings. - Preserve trailing empty fields with
split(regex, -1)if they are meaningful data. - Avoid repeated string slicing or concatenation in performance-sensitive loops; measure the real workload and consider alternatives where necessary.
16. Quick Revision
indexOf()finds the first match;lastIndexOf()finds the last. Both return-1if absent.substring(begin, end)includesbeginand excludesend.replace()performs literal replacement;replaceAll()andreplaceFirst()use regex patterns.split()uses a regex and normally discards trailing empty fields; a negative limit preserves them.toUpperCase()andtoLowerCase()return converted strings without modifying the source.trim()handles a limited range of characters;strip()handles whitespace recognized byCharacter.isWhitespace().contains(),startsWith(), andendsWith()return booleans and are case-sensitive.repeat()andstrip()were added in Java 11.String.join()places a delimiter between elements.chars()exposes UTF-16charvalues as anIntStream.
17. Conclusion
Java String methods make common text operations easier to express and read. Learn the difference between searching and slicing, literal and regex replacement, and trim() and strip(). Most importantly, remember that strings are immutable: transformation methods return results rather than changing the original object. With careful index checks and the right method for each job, you can process text reliably in Java applications.