String Methods
The String class provides more than sixty methods for examining and transforming text. This lesson is a guided tour of the ones used most often, grouped by purpose, with the rules that apply to all of them. Several groups (comparison, searching, replacing, splitting, formatting) have their own detailed lessons; here the goal is to know what exists and when to reach for it.
Two Rules That Apply to Every Method
1. Strings are immutable. No method changes the string it is called on. Methods that transform text return a new string, which you must store or use:
String name = " ada ";
name.strip(); // result thrown away; name is unchanged
name = name.strip(); // correct: keep the result
2. Indexes are zero-based, and end indexes are exclusive. In substring(2, 5), the character at index 2 is included and the one at index 5 is not, so the result has 5 - 2 = 3 characters. Indexes outside 0–length() throw StringIndexOutOfBoundsException.
Because transforming methods return strings, they can be chained:
String cleaned = " Hello, World! ".strip().toLowerCase().replace("!", ""); // "hello, world"
Examining Characters and Size
| Method | Returns | Example | Result |
|---|---|---|---|
length() | Number of char values | "Java".length() | 4 |
charAt(i) | The char at index i | "Java".charAt(2) | 'v' |
isEmpty() | length() == 0 | "".isEmpty() | true |
isBlank() | Empty or only whitespace (Java 11) | " ".isBlank() | true |
toCharArray() | A new char[] copy | "ab".toCharArray() | ['a', 'b'] |
chars() | IntStream of the characters | "aab".chars().filter(c -> c == 'a').count() | 2 |
codePointAt(i), codePointCount(b, e) | Unicode code points | See String Length |
Changing Case
"Java".toUpperCase(); // "JAVA"
"Java".toLowerCase(); // "java"
Case conversion depends on the locale for a few languages. In Turkish, for example, "TITLE".toLowerCase() produces a dotless ı. For identifiers, keys, file extensions, and protocol values that are not shown to users, pass Locale.ROOT so the result is the same on every machine:
String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT);
There is no built-in "capitalize" method; combine substring with case conversion:
String word = "chennai";
String capitalized = word.substring(0, 1).toUpperCase() + word.substring(1); // "Chennai"
Removing Whitespace
| Method | Removes |
|---|---|
strip() | Leading and trailing whitespace (Unicode-aware, Java 11) |
stripLeading() / stripTrailing() | One side only |
trim() | Leading and trailing characters with code ≤ U+0020 (older, ASCII-oriented) |
String s = " Hello, Java World ";
System.out.println("[" + s.strip() + "]"); // [Hello, Java World]
Prefer strip() in new code. trim() does not remove Unicode whitespace such as the non-breaking space (U+00A0) or ideographic space (U+3000), which often arrive in text copied from web pages.
To remove all whitespace, including inside the string, use a regular expression: s.replaceAll(" 0 s+", "").
Extracting Parts
String path = "reports/2026/november/sales.csv";
path.substring(8); // "2026/november/sales.csv"
path.substring(0, 7); // "reports"
path.substring(path.lastIndexOf('/') + 1); // "sales.csv"
substring combined with indexOf or lastIndexOf is the standard way to pull out a segment around a delimiter. split (its own lesson) breaks a string into all its parts at once.
Searching
| Method | Returns |
|---|---|
contains(s) | true if s appears anywhere |
startsWith(prefix), endsWith(suffix) | Whether the string begins or ends with the text |
indexOf(s) / indexOf(s, from) | First position of s (optionally starting at from), or -1 |
lastIndexOf(s) | Last position, or -1 |
matches(regex) | Whether the whole string matches a regular expression |
String s = " Hello, Java World ";
s.contains("Java"); // true
s.indexOf('o'); // 6
s.lastIndexOf('o'); // 15
s.strip().startsWith("Hello"); // true
All of these are case-sensitive. The String Search lesson covers them in depth.
Comparing
| Method | Purpose |
|---|---|
equals(other) | Same characters, case-sensitive |
equalsIgnoreCase(other) | Same characters, ignoring case |
compareTo(other) | Ordering: negative, zero, or positive |
compareToIgnoreCase(other) | Ordering, ignoring case |
contentEquals(CharSequence) | Compare with a StringBuilder or other CharSequence |
"Java".equalsIgnoreCase("JAVA"); // true
"java".compareTo("Java"); // 32: 'j' (106) minus 'J' (74)
Never compare string content with ==. The String Compare lesson explains why.
Replacing
| Method | Replaces |
|---|---|
replace(char, char) | Every occurrence of a character |
replace(CharSequence, CharSequence) | Every occurrence of literal text |
replaceAll(regex, replacement) | Every match of a regular expression |
replaceFirst(regex, replacement) | The first match only |
"banana".replace('a', 'o'); // "bonono"
"2026-11-11".replace("-", "/"); // "2026/11/11"
"a1b22c333".replaceAll("\\d+", "#"); // "a#b#c#"
replace with text is literal; replaceAll treats its first argument as a regular expression, so characters such as ., $, and + have special meanings there.
Splitting and Joining
"red,green,blue".split(","); // ["red", "green", "blue"]
"a,b,,c".split(",").length; // 4: the empty field between commas is kept
String.join("|", List.of("x", "y")); // "x|y"
"line1\nline2".lines().count(); // 2
split takes a regular expression. lines() (Java 11) splits on any line terminator (\n, \r\n, or \r) and returns a stream.
Building and Formatting
| Method | Example | Result |
|---|---|---|
repeat(n) (Java 11) | "ab".repeat(3) | "ababab" |
String.join(sep, parts) | String.join("-", "2026", "11", "11") | "2026-11-11" |
String.format(fmt, args) | String.format("%05.1f", 3.14159) | "003.1" |
formatted(args) (Java 15) | "%d items".formatted(3) | "3 items" |
concat(s) | "Java".concat("21") | "Java21" |
String.valueOf(x) | String.valueOf(3.5) | "3.5" |
Other Useful Methods
| Method | Purpose |
|---|---|
indent(n) (Java 12) | Add (or remove, if negative) n spaces at the start of each line |
stripIndent() (Java 15) | Remove common leading indentation from all lines |
translateEscapes() (Java 15) | Interpret escape sequences such as \n written as text |
intern() | The pooled instance of the string |
getBytes(charset) | Encode to bytes in a given character set |
regionMatches(...) | Compare a region of one string with a region of another |
Practical Example: URL Slugs and Initials
Blogs and course platforms turn titles into URL-friendly "slugs," and user interfaces often show a person's initials in an avatar.
import java.text.Normalizer;
import java.util.List;
public class Slug {
static String slugify(String title) {
String s = Normalizer.normalize(title.strip(), Normalizer.Form.NFD)
.replaceAll("\\p{M}", "") // drop accents: é -> e
.toLowerCase()
.replaceAll("[^a-z0-9]+", "-") // anything else becomes a hyphen
.replaceAll("^-|-$", ""); // no leading or trailing hyphen
return s.length() > 40 ? s.substring(0, 40).replaceAll("-$", "") : s;
}
static String initials(String fullName) {
StringBuilder sb = new StringBuilder();
for (String part : fullName.strip().split("\\s+")) {
sb.append(Character.toUpperCase(part.charAt(0)));
}
return sb.toString();
}
public static void main(String[] args) {
List<String> titles = List.of(
" Java Strings: The Complete Guide ",
"Café & Crème — Résumé Tips!",
"C++ vs. C# in 2026?",
"Understanding Java's String.format(), String.join() and Text Blocks in Depth"
);
for (String t : titles) {
System.out.println(slugify(t));
}
System.out.println(initials(" ada king lovelace "));
}
}
Output:
java-strings-the-complete-guide
cafe-creme-resume-tips
c-vs-c-in-2026
understanding-java-s-string-format-strin
AKL
slugify is a chain of string methods, each returning a new string for the next step:
strip()removes outer whitespace.Normalizer.normalize(..., NFD)splits accented letters into a base letter plus a combining mark, andreplaceAll(" 0 p{M}", "")deletes the marks, turningéintoe.toLowerCase()lowercases the text.replaceAll("[^a-z0-9]+", "-")turns every run of other characters (spaces, punctuation, symbols) into a single hyphen.- A final
replaceAlltrims hyphens at either end. - Long slugs are cut with
substring, and any trailing hyphen left by the cut is removed.
The output also shows the limits of a simple approach. C++ and C# both become c, and the long title is cut mid-word. Real systems often keep a small table of special cases and cut at the last hyphen before the limit. initials uses split(" 0 s+") to break the name on runs of whitespace (so extra spaces do no harm), then charAt(0) and Character.toUpperCase to build the result.