JB Header

Essential Java String Methods with Examples

Introduction The 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 of str (or a char), or -1 if it is not found. indexOf(str, from) starts searching at index from.
  • lastIndexOf(str) - the index of the last occurrence, or -1.
  • contains(str) - true if str appears 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);
  }
}
 OUTPUT of the above code
indexOf('@')          : 9
indexOf("o")          : 1
indexOf("o", 2)       : 5
lastIndexOf('.')      : 21
indexOf("xyz")        : -1
contains("brahman")   : true
Number of 'a's        : 4
The loop at the end uses 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 index begin to the end.
  • substring(begin, end) - from begin up to, but not including, end. Its length is end - begin.
  • charAt(index) - the single character at index.
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);
  }
}
 OUTPUT of the above code
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.
Changing case and trimming whitespace
  • toUpperCase() and toLowerCase() - convert every letter.
  • strip() - removes whitespace from both ends. stripLeading() and stripTrailing() remove it from one end only.
  • trim() - the older version of strip(). It removes only ASCII spaces and control characters, while strip() (since Java 11) understands all Unicode whitespace. Prefer strip() 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);
  }
}
 OUTPUT of the above code
[   HELLO, JAVA WORLD   ]
[   hello, java world   ]
[Hello, Java World]
[Hello, Java World   ]
[   Hello, Java World]
confirmed: true
Calls can be chained, as in 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("-", "/"));
  }
}
 OUTPUT of the above code
I like coffee. Tea is great. More coffee!
I like tea! Tea is great! More tea!
Too many spaces here
****-****-****-1234
2026/10-22
Explanation of the code
  • 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 in replaceAll().
Splitting and joining - split() and String.join() 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));
  }
}
 OUTPUT of the above code
[Tom, 32, London] - 3 fields
Name: Tom, age next year: 33
[Java, is, fun]
[src, main, java]
[] - '.' means any character!
Tom / 32 / London
Because 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() - true if the length is 0.
  • isBlank() (Java 11+) - true if the string is empty or contains only whitespace. Better for validating input.
  • startsWith(prefix) and endsWith(suffix) - check the beginning or end.
  • matches(regex) - true if 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}"));
  }
}
 OUTPUT of the above code
[] 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 methods worth knowing Recent Java versions added several convenient methods -
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")));
  }
}
 OUTPUT of the above code
====================
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.