JavaBasicsbeginner

Java String Methods List with Examples

A task-wise list of Java string methods with tested output, a sample program and a cheat sheet.

Published
TL;DR – Quick Answer

Java string methods are functions of the String class for reading, comparing, searching, cutting and changing text. Common ones are length, charAt, substring, equals, indexOf, replace, split and strip. Strings never change, so always store the returned value.

On This Page

Java string methods are the built-in functions of the String class that read, search, compare, cut and change text. This page lists the ones you will use, with the real output of each call and the mistakes to avoid.

All code was run on Java 17. Put any short block inside a main method to try it. For how strings are stored in memory, read Java strings and the string pool. This page is about the methods.

Java string methods list

Use this Java string methods list to choose by task.

Task Methods
Length and characters length, charAt, isEmpty, isBlank, toCharArray, chars
Compare equals, equalsIgnoreCase, compareTo, compareToIgnoreCase
Search contains, indexOf, lastIndexOf, startsWith, endsWith, matches
Cut substring, split, lines
Change replace, replaceAll, replaceFirst, concat, repeat
Clean and change case trim, strip, toUpperCase, toLowerCase
Join and format String.join, String.format, formatted
Convert String.valueOf, getBytes, intern

One rule covers them all. A String never changes. Methods that seem to change text return a new string, so you must store the result.

String s = "java";
s.toUpperCase();
System.out.println(s); // java

s = s.toUpperCase();
System.out.println(s); // JAVA

The first call made "JAVA" and threw it away.

Common mistake: Calling name.trim(); on its own line and expecting name to change. Write name = name.trim();.

Length and character methods

String s = "CodeBegun";

System.out.println(s.length()); // 9
System.out.println(s.charAt(0)); // C
System.out.println(s.charAt(s.length() - 1)); // n
System.out.println("".isEmpty()); // true
System.out.println("  ".isEmpty()); // false
System.out.println("  ".isBlank()); // true
System.out.println(Arrays.toString("abc".toCharArray())); // [a, b, c]

Positions start at 0, so the last position is length() - 1. Calling charAt(9) here throws a StringIndexOutOfBoundsException. isBlank came in Java 11 and treats spaces as empty.

Note the difference between length() for a string, length for an array and size() for a list. Interviewers ask about it often.

Methods to compare strings

String a = "Java";
String b = new String("Java");

System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(a.equalsIgnoreCase("JAVA")); // true
System.out.println("apple".compareTo("banana")); // -1
System.out.println("cat".compareTo("car")); // 2
System.out.println("app".compareTo("apple")); // -2

== asks "is this the same object?" and equals asks "is this the same text?". For text, use equals.

compareTo returns a negative number, zero or a positive number. It finds the first different character and subtracts: t minus r is 2. If one string is the start of the other, it subtracts the lengths: 3 minus 5 is -2.

Pro tip: Write "admin".equals(role) instead of role.equals("admin"). If role is null, the first form gives false. The second throws a NullPointerException.

Methods to search in a string

String s = "learn java, love java";

System.out.println(s.contains("java")); // true
System.out.println(s.indexOf("java")); // 6
System.out.println(s.indexOf("java", 7)); // 17
System.out.println(s.lastIndexOf("java")); // 17
System.out.println(s.indexOf("python")); // -1
System.out.println(s.startsWith("learn")); // true
System.out.println(s.endsWith(".pdf")); // false
System.out.println("9876543210".matches("[0-9]{10}")); // true

indexOf returns -1 when nothing is found, so check before you cut. matches must match the whole string, not a part of it.

Methods to cut and split

String s = "2026-12-03";

System.out.println(s.substring(5)); // 12-03
System.out.println(s.substring(0, 4)); // 2026
System.out.println(Arrays.toString(s.split("-"))); // [2026, 12, 03]
System.out.println("a.b.c".split(".").length); // 0
System.out.println("a.b.c".split("\\.").length); // 3
System.out.println("a,b,,".split(",").length); // 2
System.out.println("a,b,,".split(",", -1).length); // 4

Three points to remember:

  1. substring(0, 4) includes index 0 and stops before index 4. Its length is 4 minus 0.
  2. split takes a regular expression. A dot means "any character", so write "\\." for a real dot. The pipe sign needs "\\|".
  3. split drops empty parts at the end. Pass -1 to keep them, which matters for CSV rows.

Methods to change, clean and join

System.out.println("banana".replace('a', 'o')); // bonono
System.out.println("a1b22".replaceAll("[0-9]+", "#")); // a#b#
System.out.println("a1b22".replaceFirst("[0-9]+", "#")); // a#b22
System.out.println("[" + "  hi ".strip() + "]"); // [hi]
System.out.println("ab".repeat(3)); // ababab
System.out.println("Hi ".concat("Asha")); // Hi Asha
System.out.println(String.join("-", "a", "b", "c")); // a-b-c
System.out.println(String.join(", ", List.of("SQL", "Git"))); // SQL, Git
System.out.println(String.format("%s scored %.1f", "Ravi", 82.456)); // Ravi scored 82.5
System.out.println("%d items".formatted(3)); // 3 items
System.out.println(String.valueOf(45) + 5); // 455

replace works on plain text and changes every match. replaceAll also changes every match, but it reads the first part as a regular expression. Use replace unless you need a pattern.

strip (Java 11) understands all Unicode spaces. trim is older and removes characters with codes up to that of a normal space. In new code, prefer strip.

The last line prints 455 because the number became text before the plus.

Java string methods program: use them together

This Java string methods program checks a sentence for four common tasks: counting words, counting vowels, reversing and testing a palindrome.

public class StringTasks {
    static int countWords(String s) {
        return s.isBlank() ? 0 : s.strip().split("\\s+").length;
    }

    static long countVowels(String s) {
        return s.toLowerCase().chars()
                .filter(c -> "aeiou".indexOf(c) >= 0)
                .count();
    }

    static String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    static boolean isPalindrome(String s) {
        String t = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        return t.equals(reverse(t));
    }

    public static void main(String[] args) {
        System.out.println(countWords("  Java is  fun ")); // 3
        System.out.println(countVowels("Education")); // 5
        System.out.println(reverse("code")); // edoc
        System.out.println(isPalindrome("Nurses run")); // true
        System.out.println(isPalindrome("Java")); // false
    }
}

\\s+ means one or more spaces, so double spaces do not add empty words. String has no reverse method, which is why the code uses StringBuilder.

Many interviewers ask you to do these without built-in methods. Practise that too with reverse a string without built-in methods and check a string palindrome.

How to choose the right method

Some pairs look alike. This table settles the common doubts.

Doubt Choose
== or equals equals for text, always
contains or matches contains for part of the text, matches for a pattern over the whole text
indexOf or contains indexOf when you need the position, contains when you need yes or no
replace or replaceAll replace for plain text, replaceAll for a pattern
trim or strip strip on Java 11 and later
isEmpty or isBlank isBlank for user input, because spaces count as empty
concat or + + in most code, since concat throws an error on null
+ or StringBuilder StringBuilder inside loops

A null string is a separate case. Calling any method on null throws a NullPointerException. So test for null first, then for blank: if (name != null && !name.isBlank()). The order matters, because && stops as soon as the first test is false.

Methods added in newer Java versions

Version Methods
Java 8 String.join, chars (from CharSequence)
Java 11 isBlank, strip, stripLeading, stripTrailing, lines, repeat
Java 12 indent, transform
Java 15 formatted, stripIndent, translateEscapes, text blocks (a language feature)
System.out.println("a\nb\nc".lines().count()); // 3
System.out.println("  x ".stripLeading().length()); // 2
String loud = "java".transform(t -> t + "!");
System.out.println(loud); // java!

If your company uses Java 8, the Java 11 and later methods will not compile.

Interview note: "Why is adding strings in a loop slow?" Each + in the loop copies all the old text into a new object. For n pieces the total copying grows like n squared. Use one StringBuilder and call append.

Java string methods cheat sheet

This Java string methods cheat sheet uses s = "Hello".

Call Result
s.length() 5
s.charAt(1) 'e'
s.substring(1, 3) "el"
s.indexOf('l') 2
s.lastIndexOf('l') 3
s.contains("ell") true
s.replace('l', 'L') "HeLLo"
s.toUpperCase() "HELLO"
s.concat("!") "Hello!"
s.equals("hello") false
s.equalsIgnoreCase("hello") true
s.compareTo("Help") -4
s.repeat(2) "HelloHello"
s.isEmpty() false

Some people call these Java string functions. In Java, a function inside a class is called a method, so the two names mean the same thing here.

You now have Java string methods with examples for daily coding. Next, solve count character frequency, then prepare answers from string handling interview questions. To learn Java through projects, see the Java full stack course.

Frequently Asked Questions

What are the most used string methods in Java?
length, charAt, substring, equals, indexOf, contains, replace, split, toLowerCase and strip cover most daily work. join and format are also useful.
What is the difference between equals and == for strings?
equals checks whether the text is the same. == checks whether both variables point to the same object, so it can be false for equal text.
What is the difference between trim and strip?
trim removes characters with codes up to that of a normal space. strip, added in Java 11, removes all white space defined by Unicode.
Does Java have a string reverse method?
No. Use new StringBuilder(s).reverse().toString(), or loop from the last character to the first.
Why does split with a dot return an empty array?
split reads its argument as a regular expression, and a dot matches any character. Escape it as two backslashes and a dot inside the Java string, or use Pattern.quote.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Java Full Stack program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 3 December 2026 LinkedIn
Chat with us