Java String Methods — Complete Reference with Examples
Java’s String class has over 60 methods. This chapter covers every method you’ll use regularly, grouped by category.
Length and Emptiness
String s = "Hello";
s.length() // 5
s.isEmpty() // false (true when length == 0)
s.isBlank() // false (true when only whitespace — Java 11+)
"".isEmpty() // true
"".isBlank() // true
" ".isEmpty() // false
" ".isBlank() // true
Accessing Characters
String s = "Java";
s.charAt(0) // 'J'
s.charAt(3) // 'a'
// s.charAt(10) ← StringIndexOutOfBoundsException
Convert to char array:
char[] chars = s.toCharArray(); // ['J', 'a', 'v', 'a']
Substring
String s = "Hello, World!";
s.substring(7) // "World!" (from index 7 to end)
s.substring(0, 5) // "Hello" (from 0, up to but not including 5)
Tip:
substring(start, end)—startis inclusive,endis exclusive.
Searching
indexOf() and lastIndexOf()
String s = "banana";
s.indexOf('a') // 1 (first occurrence)
s.lastIndexOf('a') // 5 (last occurrence)
s.indexOf("nan") // 2
s.indexOf('z') // -1 (not found)
s.indexOf('a', 3) // 3 (search from index 3)
contains()
"Hello, World".contains("World") // true
"Hello, World".contains("world") // false (case-sensitive)
startsWith() and endsWith()
String file = "report.pdf";
file.startsWith("report") // true
file.endsWith(".pdf") // true
file.endsWith(".csv") // false
Case Conversion
"Hello".toUpperCase() // "HELLO"
"Hello".toLowerCase() // "hello"
These are locale-sensitive. For locale-independent conversion:
"Hello".toUpperCase(Locale.ROOT)
Trimming Whitespace
String s = " Hello ";
s.trim() // "Hello" (removes chars ≤ U+0020)
s.strip() // "Hello" (removes all Unicode whitespace — Java 11+)
s.stripLeading() // "Hello " (Java 11+)
s.stripTrailing()// " Hello" (Java 11+)
Prefer
strip()overtrim()in modern Java — it handles Unicode whitespace correctly.
Replacing
String s = "foo bar foo baz foo";
s.replace("foo", "qux") // "qux bar qux baz qux"
s.replace('o', '0') // "f00 bar f00 baz f00"
s.replaceFirst("foo", "QUX") // "QUX bar foo baz foo" (regex)
s.replaceAll("fo+", "X") // "X bar X baz X" (regex)
Splitting
String csv = "Alice,Bob,Charlie";
String[] names = csv.split(",");
// ["Alice", "Bob", "Charlie"]
String text = "one two three";
String[] words = text.split("\\s+"); // regex: one or more whitespace
// ["one", "two", "three"]
Limit the number of splits:
"a:b:c:d".split(":", 2) // ["a", "b:c:d"]
Joining
String joined = String.join(", ", "Alice", "Bob", "Charlie");
// "Alice, Bob, Charlie"
List<String> items = List.of("X", "Y", "Z");
String result = String.join(" | ", items);
// "X | Y | Z"
Comparing
"abc".equals("abc") // true
"abc".equals("ABC") // false
"abc".equalsIgnoreCase("ABC") // true
"apple".compareTo("banana") // negative (apple < banana)
"banana".compareTo("apple") // positive
"apple".compareTo("apple") // 0
compareTo() returns:
-
Negative if
this < other - Zero if equal
-
Positive if
this > other
Method Chaining
Since every String method returns a new String, you can chain them:
String result = " Hello, World! "
.strip()
.toLowerCase()
.replace("world", "java");
// "hello, java!"
Java 11+ Additions
" ".isBlank() // true
" Hi ".strip() // "Hi"
"Ha".repeat(3) // "HaHaHa"
"line1\nline2\nline3".lines()
.forEach(System.out::println);
// line1
// line2
// line3
Java 12+ indent() and transform()
"Hello".indent(4)
// " Hello\n"
"hello".transform(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
// "Hello"
Quick Reference Table
| Method | Purpose | Example |
|---|---|---|
length() |
Character count |
"Hi".length() → 2 |
charAt(i) |
Char at index |
"Hi".charAt(0) → ‘H’ |
substring(s,e) |
Extract portion |
"Hello".substring(0,3) → “Hel” |
indexOf(x) |
First position |
"banana".indexOf('n') → 2 |
contains(x) |
Presence check |
"abc".contains("b") → true |
equals(x) |
Content equality |
"a".equals("a") → true |
toUpperCase() |
Upper case |
"hi".toUpperCase() → “HI” |
trim() / strip()
|
Remove whitespace |
" x ".strip() → “x” |
replace(a,b) |
Replace all |
"aa".replace("a","b") → “bb” |
split(regex) |
Split to array |
"a,b".split(",") → [“a”,”b”] |
join(d, ...) |
Join strings |
String.join("-","a","b") → “a-b” |
Common Mistakes
| Mistake | Why | Fix |
|---|---|---|
| Ignoring return value | Strings are immutable | Assign: s = s.trim()
|
split(".") |
. is regex for “any char” |
Use split("\\.")
|
substring off-by-one |
End index is exclusive | Remember: [start, end)
|
Case-sensitive contains
|
No built-in ignore-case | Convert both to lower first |
Key Takeaways
- Strings are immutable — every method returns a new String.
- Use
strip()overtrim()in modern Java. -
split()takes a regex — escape special characters. - Use
String.join()to combine strings with a delimiter. - Method chaining produces clean, readable code.
What’s Next?
Next: StringBuilder and StringBuffer — mutable string builders for when performance matters.