Java String methods help inspect, compare and transform text, but strings remain immutable. A method such as trim or replace returns a value instead of editing the original string. This reference explains common methods through concrete results, index rules and Unicode boundaries.
Review the related foundation lesson when you need a prerequisite. The complete programs below use Java 17-compatible syntax.
Length and substring indices
length, charAt and substring inspect text using UTF-16 indices. substring begins at an inclusive start and ends before an exclusive end.
length reports UTF-16 code units, and charAt returns one such unit at an index. Many familiar characters occupy one unit, but some Unicode characters need a surrogate pair. A user-visible character can involve still more code points, such as combining marks. Therefore length is not a universal visible-character count. Use codePointCount when the requirement concerns Unicode code points rather than raw code units.
Whitespace, search and extraction boundaries
strip removes leading and trailing Unicode whitespace. trim follows an older narrower rule. isBlank asks whether the whole string contains only whitespace.
substring takes a beginning index inclusive and an end index exclusive. indexOf returns the first matching position or minus one when no match exists. Check that result before using it as a substring boundary. startsWith, endsWith and contains answer different containment questions; they do not interpret regular expressions. A successful search does not automatically validate the entire string's format.
Equality and case conversion
equals compares content; equalsIgnoreCase handles simple case-insensitive comparisons. toLowerCase should use an explicit locale when stable technical identifiers are needed.
Use equals for content equality, not ==, which tests reference identity. equalsIgnoreCase ignores case using its documented comparison rules but is not a full locale-sensitive language comparison. For deliberate case normalization, choose an appropriate Locale, often Locale.ROOT for identifiers. Natural String comparison is lexicographic over UTF-16 units, not a universal human-language dictionary order.
Literal and regex replacement
contains, startsWith, endsWith and replace support common text tasks. replace uses literal replacement, while replaceAll interprets a regular expression and replacement syntax.
replace with character sequences performs literal replacement, while replaceAll and split use regular expressions. A dot in a regex means any character unless escaped, so splitting a filename on a literal dot requires the appropriate escape. strip handles Unicode whitespace according to Character.isWhitespace, while trim uses its older limited rule. Every transformation returns a string value; keep that result if you need it.
Running the examples
Save name.java, compile it with javac --release 17 name.java, and run java name. Use each program's own public class name and filename.
How BadgeStringMethods produces its output
strip removes the surrounding spaces and returns Orchard Team, which is stored in clean. substring(0, 7) then returns Orchard because positions zero through six are included. startsWith("Orchard") returns true. The three output lines show the clean full text, its seven-unit prefix and the prefix check. badge itself still contains the original spaces.
How StringTransformations produces its output
strip returns the surrounding-whitespace-free value River. toUpperCase with Locale.ROOT transforms that returned value to RIVER, which is stored in cleaned. original still contains its two spaces on each side. Printing brackets makes those preserved spaces visible and shows why simply calling a transformation without retaining the result can seem ineffective.
How StringBoundaries produces its output
indexOf locates the colon at position four. Adding one begins the suffix immediately after it, producing north. substring(0, 4) includes positions zero through three and excludes the colon. The nonnegative check prevents using a missing delimiter as if it were found, although a real parser may also need to reject empty sides.
Choose literal or pattern-based operations deliberately
Suppose a configuration value contains route.east. contains(".") checks for that literal punctuation, while split(".") treats the dot as a regular expression matching almost any character. To split on a literal dot in Java source, the regex backslash must itself be escaped in the string literal. A reference example should show both the Java string and the intended pattern when escapes are involved. For practice, parse a label with a colon only after checking indexOf. Test text with no colon, an initial colon and a final colon. A found delimiter alone does not prove that both fields are nonempty.
Empty strings, null and Unicode are different cases
An empty string is a valid String whose length is zero. null is a reference with no String object, so calling length on it throws. A whitespace-only string can be nonempty while isBlank returns true. These distinctions should follow the input contract instead of being collapsed by an automatic trim. For Unicode input, a single supplementary code point occupies two UTF-16 units, so charAt can return only one half of its surrogate pair. A code-point traversal is more appropriate when a rule concerns Unicode code points. Even that does not automatically count user-perceived grapheme clusters, which can combine several code points.
Java Summary
- length, charAt and substring inspect text using UTF-16 indices. substring begins at an inclusive start and ends before an exclusive end.
- strip removes leading and trailing Unicode whitespace. trim follows an older narrower rule. isBlank asks whether the whole string contains only whitespace.
- equals compares content; equalsIgnoreCase handles simple case-insensitive comparisons. toLowerCase should use an explicit locale when stable technical identifiers are needed.
- contains, startsWith, endsWith and replace support common text tasks. replace uses literal replacement, while replaceAll interprets a regular expression and replacement syntax.
- Continue with Java exercises, Java quizzes and the Java study roadmap.
Java Examples
Each example shows the code, the output it produces and what each part does.
Java String Methods Reference in a complete program
public class BadgeStringMethods {
public static void main(String[] args) {
String badge = " Orchard Team ";
String clean = badge.strip();
System.out.println(clean);
System.out.println(clean.substring(0, 7));
System.out.println(clean.startsWith("Orchard"));
}
}Orchard Team
Orchard
trueLine-by-line explanation
- Line 5Evaluates
cleanand printsOrchard Team. - Line 6Evaluates
clean.substring(0, 7)and printsOrchard. - Line 7Evaluates
clean.startsWith("Orchard")and printstrue.
Transformations return new values
public class StringTransformations {
public static void main(String[] args) {
String original = " River ";
String cleaned = original.strip().toUpperCase(java.util.Locale.ROOT);
System.out.println("[" + original + "]");
System.out.println(cleaned);
}
}[ River ]
RIVERLine-by-line explanation
- Line 5Evaluates
"[" + original + "]"and prints[ River ]. - Line 6Evaluates
cleanedand printsRIVER.
Search before extracting a substring
public class StringBoundaries {
public static void main(String[] args) {
String label = "zone:north";
int colon = label.indexOf(':');
if (colon >= 0) System.out.println(label.substring(colon + 1));
System.out.println(label.substring(0, 4));
}
}north
zoneLine-by-line explanation
- Line 5Evaluates
label.substring(colon + 1)and printsnorth. - Line 6Evaluates
label.substring(0, 4)and printszone.
Java FAQ
Why is == unreliable for string content?
It compares references. Interned literals can make some identity comparisons appear to work, while separately constructed equal strings may be different objects. Use equals for content and Objects.equals when either value may be null.
Does split preserve trailing empty fields?
The default split overload discards trailing empty strings. Use a negative limit when they are meaningful, such as split(",", -1). This still is not a complete CSV parser, because quoted commas and embedded line breaks require format-aware parsing.
How do I check whether a string contains only digits?
Use text.matches("\\d+"), which requires at least one digit, or !text.isEmpty() && text.chars().allMatch(Character::isDigit). Note that allMatch alone returns true for an empty string. If you're about to convert the value, Integer.parseInt inside a try checks the range as well.
How do I count how many times a character appears?
Loop over the characters and count matches, or use text.chars().filter(c -> c == 'a').count(), which gives 3 for "banana". To count a longer piece of text, search repeatedly with indexOf(target, from), moving from past each match.
How do I capitalise the first letter of a string?
Combine two substrings: text.substring(0, 1).toUpperCase() + text.substring(1). Check that the string isn't empty first, or substring(0, 1) throws an exception. For proper title case in different languages, a library or locale-aware rules are needed.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What does substring(1, 4) include?
Which method compares text contents?
Java Quiz
2 questions to check what you learned.
Why save the result of strip?
- String is immutable and strip returns a value
- strip changes only static strings
- strip requires a mutable array
Which method interprets its pattern as a regular expression?
- replaceAll
- replace with CharSequence arguments
- contains