String Methods
Java’s String class ships with over 60 methods that let you inspect, transform, search, and split text — all without writing a single loop in most cases. This page walks through the most useful ones grouped by what they do, with working examples for each.
Inspection Methods
These methods tell you something about a string without changing it.
length()
Returns the number of UTF-16 code units in the string (for everyday ASCII text this is the same as character count).
String s = "Hello";
System.out.println(s.length()); // 5
Output:
5
charAt(int index)
Returns the char at a zero-based position. Throws StringIndexOutOfBoundsException if the index is out of range.
String s = "Java";
char c = s.charAt(2);
System.out.println(c); // v
Output:
v
indexOf() and lastIndexOf()
Find the first (or last) occurrence of a character or substring. Return -1 when not found.
String s = "banana";
System.out.println(s.indexOf('a')); // 1
System.out.println(s.lastIndexOf('a')); // 5
System.out.println(s.indexOf("nan")); // 2
System.out.println(s.indexOf('z')); // -1
Output:
1
5
2
-1
contains(CharSequence target)
Returns true if the string contains the given sequence anywhere inside it.
String sentence = "Learning Java is fun";
System.out.println(sentence.contains("Java")); // true
System.out.println(sentence.contains("Ruby")); // false
isEmpty() and isBlank()
isEmpty() checks whether length() == 0. isBlank() (added in Java 11) also returns true for strings that contain only whitespace.
System.out.println("".isEmpty()); // true
System.out.println(" ".isEmpty()); // false
System.out.println(" ".isBlank()); // true (Java 11+)
startsWith() and endsWith()
String file = "report.pdf";
System.out.println(file.startsWith("report")); // true
System.out.println(file.endsWith(".pdf")); // true
Comparison Methods
Java strings must be compared with methods, not ==. See String Comparison for the full story.
equals() and equalsIgnoreCase()
String a = "hello";
String b = "HELLO";
System.out.println(a.equals(b)); // false
System.out.println(a.equalsIgnoreCase(b)); // true
compareTo() and compareToIgnoreCase()
Returns a negative, zero, or positive integer — useful for sorting. Internally used by Comparable implementations.
System.out.println("apple".compareTo("banana")); // negative (a < b)
System.out.println("cat".compareTo("cat")); // 0
System.out.println("zoo".compareTo("ant")); // positive
matches(String regex)
Tests whether the entire string matches a regular expression. See Regular Expressions for full regex syntax.
String email = "[email protected]";
System.out.println(email.matches("[\\w.]+@[\\w.]+\\.[a-z]{2,}")); // true
Extraction Methods
substring(int beginIndex) / substring(int beginIndex, int endIndex)
Returns a new string that is a portion of the original. The endIndex is exclusive. Learn more at Substring.
String s = "DevCraftly";
System.out.println(s.substring(3)); // Craftly
System.out.println(s.substring(3, 8)); // Craft
Output:
Craftly
Craft
toCharArray()
Converts the string into a char[], useful when you need direct character-by-character manipulation.
char[] chars = "Java".toCharArray();
for (char c : chars) {
System.out.print(c + " ");
}
Output:
J a v a
split(String regex) / split(String regex, int limit)
Splits the string around matches of the given regular expression and returns a String[].
String csv = "red,green,blue";
String[] colors = csv.split(",");
for (String color : colors) {
System.out.println(color);
}
Output:
red
green
blue
The optional limit parameter controls the maximum number of pieces:
String[] parts = "a:b:c:d".split(":", 2);
// parts = ["a", "b:c:d"]
Tip:
split("\\s+")is a handy way to split on any run of whitespace, including tabs and multiple spaces.
Transformation Methods
These return a new string — remember, String is immutable.
toUpperCase() and toLowerCase()
System.out.println("Hello World".toUpperCase()); // HELLO WORLD
System.out.println("Hello World".toLowerCase()); // hello world
For locale-sensitive work (Turkish, German, etc.) use the overloads that accept a Locale.
trim() and strip()
trim() removes ASCII whitespace (\u0000– ) from both ends. strip() (Java 11+) uses Unicode’s definition of whitespace and is the preferred modern alternative.
String padded = " hello ";
System.out.println("|" + padded.trim() + "|"); // |hello|
System.out.println("|" + padded.strip() + "|"); // |hello| (Java 11+)
stripLeading() and stripTrailing() strip only the left or right side respectively.
replace(), replaceFirst(), replaceAll()
| Method | Pattern type | Replaces |
|---|---|---|
replace(char, char) | Literal char | All occurrences |
replace(CharSequence, CharSequence) | Literal string | All occurrences |
replaceFirst(String regex, String repl) | Regex | First match only |
replaceAll(String regex, String repl) | Regex | All matches |
String s = "foo bar foo";
System.out.println(s.replace("foo", "baz")); // baz bar baz
System.out.println(s.replaceFirst("foo", "baz")); // baz bar foo
System.out.println(s.replaceAll("[aeiou]", "*")); // f** b*r f**
concat(String str)
Appends another string and returns the result. The + operator is more common and more readable, but concat avoids boxing overhead in tight inner loops because it never goes through StringBuilder wrapping at compile time.
String result = "Hello".concat(", World!");
System.out.println(result); // Hello, World!
intern()
Forces the string into the String Pool, returning the canonical pooled reference. Useful for reducing memory when storing millions of identical strings.
String a = new String("hello").intern();
String b = "hello";
System.out.println(a == b); // true
Static Utility Methods
String.valueOf(…)
Converts any primitive or object to its string representation.
System.out.println(String.valueOf(42)); // 42
System.out.println(String.valueOf(3.14)); // 3.14
System.out.println(String.valueOf(true)); // true
System.out.println(String.valueOf('Z')); // Z
String.format(String format, Object… args)
Produces a formatted string using printf-style placeholders. A clean alternative to messy concatenation.
String msg = String.format("Hello, %s! You are %d years old.", "Alice", 30);
System.out.println(msg);
Output:
Hello, Alice! You are 30 years old.
Common format specifiers: %s (string), %d (integer), %f (float), %n (newline), %05d (zero-padded integer).
Tip: In Java 15+ you can use Text Blocks for multi-line strings, and
String.formatted()as a fluent alternative toString.format().
String.join(CharSequence delimiter, CharSequence… elements)
Joins multiple strings with a separator — much cleaner than a manual loop.
String joined = String.join(", ", "red", "green", "blue");
System.out.println(joined); // red, green, blue
Works with any Iterable<? extends CharSequence> too (e.g., a List<String>).
String.repeat(int count) — Java 11+
System.out.println("ha".repeat(3)); // hahaha
Under the Hood
Every String in Java is backed by a char[] (or more precisely, a byte[] since Java 9’s Compact Strings optimization — Latin-1 strings use one byte per character, halving memory for typical Western text). Because strings are immutable, all transformation methods like substring() and replace() allocate a new object on the heap rather than modifying the original.
A few performance details worth knowing:
substring()before Java 7u6 shared the underlyingchar[]with the original string, which could cause memory leaks. Modern JVMs copy the data.+concatenation in a loop compiles to repeatedStringBuilder.append()calls, which is fine for a handful of iterations but becomes O(n²) for large loops. Prefer StringBuilder explicitly when building strings in loops.split()compiles the regex on every call unless it is a one-character literal. Cache aPatternobject when splitting in a hot path.intern()stores the string in a hash table inside the JVM’s permanent generation (or Metaspace on Java 8+). It is fast to look up but the table has a fixed initial size; over-interning thousands of unique strings can cause GC pressure.
Quick Reference Table
| Method | Returns | Notes |
|---|---|---|
length() | int | UTF-16 code unit count |
charAt(i) | char | 0-based index |
indexOf(s) | int | -1 if not found |
contains(s) | boolean | |
isEmpty() | boolean | length == 0 |
isBlank() | boolean | Java 11+; whitespace-only |
equals(o) | boolean | Content equality |
equalsIgnoreCase(o) | boolean | |
compareTo(s) | int | Lexicographic order |
substring(b, e) | String | endIndex exclusive |
split(regex) | String[] | |
toUpperCase() | String | |
toLowerCase() | String | |
trim() / strip() | String | strip is Unicode-aware (Java 11+) |
replace(old, new) | String | Literal replacement |
replaceAll(regex, r) | String | Regex replacement |
valueOf(x) | String | Static; any type |
format(fmt, args) | String | Static; printf-style |
join(delim, parts) | String | Static |
repeat(n) | String | Java 11+ |
intern() | String | Pool canonical reference |
Related Topics
- Strings — the foundation: how strings are created and why they are immutable
- String Immutability — understand why every transformation returns a new object
- String Pool & intern() — how the JVM deduplicates string literals in memory
- StringBuilder — mutable string building for performance-sensitive code
- String Comparison —
equals()vs==, andcompareTo()explained in depth - Regular Expressions — master the regex syntax used by
matches(),replaceAll(), andsplit()