Essential Java String Methods with Examples
Introduction
The
(Note - Remember that strings are immutable: every method which "changes" a string returns a new one. See Java String Basics and ImmutabilityClick to read tutorial: Java String Basics and Why Strings Are Immutable.) Finding text - indexOf(), lastIndexOf() and contains()
OUTPUT of the above code
The loop at the end uses
OUTPUT of the above code
Changing case and trimming whitespace
OUTPUT of the above code
Calls can be chained, as in
OUTPUT of the above code
Explanation of the code
Splitting and joining - split() and String.join()
OUTPUT of the above code
Because
OUTPUT of the above code
Newer methods worth knowing
Recent Java versions added several convenient methods -
OUTPUT of the above code
String class has dozens of methods, but a core set of around twenty covers almost everything you will do with text. This tutorial goes through the essential Java String methods with examples, grouped by what they do. We will start with methods for finding text inside a string, and for extracting parts of it. We will then change case and clean up whitespace, replace text, and split a string into parts. Next we will check what a string contains - empty, blank, starting or ending with something. Lastly, we will look at a few useful methods added in newer Java versions.(Note - Remember that strings are immutable: every method which "changes" a string returns a new one. See Java String Basics and ImmutabilityClick to read tutorial: Java String Basics and Why Strings Are Immutable.) Finding text - indexOf(), lastIndexOf() and contains()
indexOf(str)- the index of the first occurrence ofstr(or achar), or -1 if it is not found.indexOf(str, from)starts searching at indexfrom.lastIndexOf(str)- the index of the last occurrence, or -1.contains(str)-trueifstrappears anywhere.
Finding text in a String
//FindingText.java
public class FindingText {
public static void main(String[] args) {
String email = "tom.jones@javabrahman.com";
System.out.println("indexOf('@') : " + email.indexOf('@'));
System.out.println("indexOf(\"o\") : " + email.indexOf("o"));
System.out.println("indexOf(\"o\", 2) : " + email.indexOf("o", 2));
System.out.println("lastIndexOf('.') : " + email.lastIndexOf('.'));
System.out.println("indexOf(\"xyz\") : " + email.indexOf("xyz"));
System.out.println("contains(\"brahman\") : " + email.contains("brahman"));
int count = 0;
for (int i = email.indexOf('a'); i >= 0; i = email.indexOf('a', i + 1)) {
count++;
}
System.out.println("Number of 'a's : " + count);
}
}
indexOf('@') : 9
indexOf("o") : 1
indexOf("o", 2) : 5
lastIndexOf('.') : 21
indexOf("xyz") : -1
contains("brahman") : true
Number of 'a's : 4
indexOf(ch, from) to jump from one occurrence to the next - a common way to count or find every occurrence.
Extracting parts - substring() and charAt()
substring(begin)- from indexbeginto the end.substring(begin, end)- frombeginup to, but not including,end. Its length isend - begin.charAt(index)- the single character atindex.
Extracting parts of a String
//Extracting.java
public class Extracting {
public static void main(String[] args) {
String email = "tom.jones@javabrahman.com";
int at = email.indexOf('@');
String user = email.substring(0, at);
String domain = email.substring(at + 1);
System.out.println("user : " + user);
System.out.println("domain : " + domain);
String fileName = "report.final.pdf";
String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
System.out.println("extension : " + extension);
String word = "java";
String capitalized = Character.toUpperCase(word.charAt(0)) + word.substring(1);
System.out.println("capitalized : " + capitalized);
}
}
user : tom.jones domain : javabrahman.com extension : pdf capitalized : Java
indexOf() and substring() are usually used together: find where something is, then cut around it.
toUpperCase()andtoLowerCase()- convert every letter.strip()- removes whitespace from both ends.stripLeading()andstripTrailing()remove it from one end only.trim()- the older version ofstrip(). It removes only ASCII spaces and control characters, whilestrip()(since Java 11) understands all Unicode whitespace. Preferstrip()in new code.
Changing case and trimming whitespace
//CaseAndWhitespace.java
public class CaseAndWhitespace {
public static void main(String[] args) {
String input = " Hello, Java World ";
System.out.println("[" + input.toUpperCase() + "]");
System.out.println("[" + input.toLowerCase() + "]");
System.out.println("[" + input.strip() + "]");
System.out.println("[" + input.stripLeading() + "]");
System.out.println("[" + input.stripTrailing() + "]");
String answer = " YES ";
boolean confirmed = answer.strip().equalsIgnoreCase("yes");
System.out.println("confirmed: " + confirmed);
}
}
[ HELLO, JAVA WORLD ] [ hello, java world ] [Hello, Java World] [Hello, Java World ] [ Hello, Java World] confirmed: true
answer.strip().equalsIgnoreCase("yes") - each method is called on the string returned by the one before.
Replacing text - replace() and replaceAll()
replace(old, new)- replaces every occurrence of a character or of literal text.replaceAll(regex, replacement)- replaces every match of a regular expression, a pattern language for text."\\s+"means "one or more whitespace characters", and"[0-9]"means "any digit".replaceFirst(regex, replacement)- replaces only the first match.
Replacing text
//ReplacingText.java
public class ReplacingText {
public static void main(String[] args) {
String text = "I like tea. Tea is great. More tea!";
System.out.println(text.replace("tea", "coffee"));
System.out.println(text.replace('.', '!'));
String messy = "Too many spaces here";
System.out.println(messy.replaceAll("\\s+", " "));
String card = "4111-1111-1111-1234";
System.out.println(card.replaceAll("[0-9](?=.{4})", "*"));
System.out.println("2026-10-22".replaceFirst("-", "/"));
}
}
I like coffee. Tea is great. More coffee! I like tea! Tea is great! More tea! Too many spaces here ****-****-****-1234 2026/10-22
replace("tea", "coffee")replaced both lower-case occurrences, but not"Tea"- replacement is case-sensitive.replaceAll("\\s+", " ")collapsed each run of spaces into one. The backslash is doubled because\must be escaped inside a Java string.- The card-masking pattern replaces every digit which still has at least four characters after it, leaving only the last four digits visible.
- Use
replace()for plain text. Characters such as.,*and$have special meanings inreplaceAll().
split(regex) breaks a string into an array of parts, at each match of a regular expression. String.join() does the reverse.
Splitting and joining strings
//SplitJoin.java
import java.util.Arrays;
public class SplitJoin {
public static void main(String[] args) {
String csv = "Tom,32,London";
String[] fields = csv.split(",");
System.out.println(Arrays.toString(fields) + " - " + fields.length + " fields");
System.out.println("Name: " + fields[0] + ", age next year: " + (Integer.parseInt(fields[1]) + 1));
String sentence = "Java is fun";
System.out.println(Arrays.toString(sentence.split("\\s+")));
String path = "src.main.java";
System.out.println(Arrays.toString(path.split("\\.")));
System.out.println(Arrays.toString(path.split(".")) + " - '.' means any character!");
System.out.println(String.join(" / ", fields));
}
}
[Tom, 32, London] - 3 fields Name: Tom, age next year: 33 [Java, is, fun] [src, main, java] [] - '.' means any character! Tom / 32 / London
split() takes a regular expression, splitting on a dot needs "\\.". A plain "." matches every character, so every piece is empty, and the result is an empty array.
Checking strings - isEmpty(), isBlank(), startsWith() and endsWith()
isEmpty()-trueif the length is 0.isBlank()(Java 11+) -trueif the string is empty or contains only whitespace. Better for validating input.startsWith(prefix)andendsWith(suffix)- check the beginning or end.matches(regex)-trueif the whole string matches a pattern.
Checking what a String contains
//CheckingStrings.java
public class CheckingStrings {
public static void main(String[] args) {
String[] inputs = {"", " ", "Hello"};
for (String s : inputs) {
System.out.println("[" + s + "] isEmpty=" + s.isEmpty() + ", isBlank=" + s.isBlank());
}
String url = "https://www.javabrahman.com/index.html";
System.out.println("secure link : " + url.startsWith("https://"));
System.out.println("HTML page : " + url.endsWith(".html"));
String pin = "4821";
System.out.println("valid 4-digit PIN : " + pin.matches("[0-9]{4}"));
}
}
[] isEmpty=true, isBlank=true [ ] isEmpty=false, isBlank=true [Hello] isEmpty=false, isBlank=false secure link : true HTML page : true valid 4-digit PIN : true
Newer String methods
//NewerMethods.java
public class NewerMethods {
public static void main(String[] args) {
System.out.println("=".repeat(20)); // Java 11
String poem = "Roses are red\nViolets are blue\n\nJava is fun";
System.out.println("Non-blank lines: " + poem.lines().filter(l -> !l.isBlank()).count()); // Java 11
System.out.println("Order %d for %s".formatted(42, "Tom")); // Java 15
System.out.println("tea".chars().filter(c -> c == 'e').count() + " letter e in tea");
System.out.println("level".contentEquals(new StringBuilder("level")));
}
}
==================== Non-blank lines: 3 Order 42 for Tom 1 letter e in tea true
repeat() repeats a string, lines() splits text into a stream of lines, and formatted() works like String.format()Click to read tutorial: Java Console Output: println, printf and String.format. chars() gives a stream of the characters' codes, and contentEquals() compares a string with any sequence of characters, such as a StringBuilder.
Summary
In this tutorial we went through the essential String methods. We first found text with indexOf(), lastIndexOf() and contains(), and extracted parts with substring() and charAt(). We then changed case with toUpperCase() and toLowerCase(), cleaned whitespace with strip(), and replaced text with replace() and replaceAll(). Next we split strings with split() - remembering that it takes a regular expression - and joined them with String.join(). We then checked strings with isEmpty(), isBlank(), startsWith(), endsWith() and matches(). Lastly, we looked at newer methods such as repeat(), lines() and formatted(). In the next tutorial, we will see how to build strings efficiently with StringBuilder and StringBufferClick to read tutorial: String vs StringBuilder vs StringBuffer in Java.Java Fundamentals Tutorials
Java String Comparison: == vs equals() vs compareTo()Click to read tutorial: Java String Comparison: == vs equals() vs compareTo() String vs StringBuilder vs StringBuffer in JavaClick to read tutorial: String vs StringBuilder vs StringBuffer in Java Java String Basics and Why Strings Are ImmutableClick to read tutorial: Java String Basics and Why Strings Are Immutable Java String Pool: String Literals vs new String()Click to read tutorial: Java String Pool: String Literals vs new String() Java Text Blocks: Multi-line Strings with ExamplesClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples Common Java String Programs with ExamplesClick to read tutorial: Common Java String Programs with Examples What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses
Java String Comparison: == vs equals() vs compareTo()Click to read tutorial: Java String Comparison: == vs equals() vs compareTo() String vs StringBuilder vs StringBuffer in JavaClick to read tutorial: String vs StringBuilder vs StringBuffer in Java Java String Basics and Why Strings Are ImmutableClick to read tutorial: Java String Basics and Why Strings Are Immutable Java String Pool: String Literals vs new String()Click to read tutorial: Java String Pool: String Literals vs new String() Java Text Blocks: Multi-line Strings with ExamplesClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples Common Java String Programs with ExamplesClick to read tutorial: Common Java String Programs with Examples What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses