Paramclasses Academy - Blog

Tutorials Details

Java String Methods: 20 Useful Methods with Examples

Java String Methods: 20 Useful Methods with Examples

October 21, 2026

Introduction

Strings are one of the most commonly used concepts in Java programming. Whenever you work with names, messages, email addresses, user input, or other text, you will likely use strings.

Java provides the built-in String class with many methods that help you measure text length, search for characters, compare strings, replace text, and change letter case.

In this tutorial, you will learn 20 useful Java String methods with easy explanations, practical examples, and their outputs.

What Is a String in Java?

A String is an object that represents a sequence of characters.

You can create a string using a string literal:

String name = "Java Programming";
System.out.println(name);

Output:

Java Programming

Java strings are immutable, which means their contents cannot be changed after the string object is created. Methods such as toUpperCase() and replace() return a result; they do not modify the original string.

For example:

String text = "java";
text.toUpperCase();

System.out.println(text);

Output:

java

The original string remains unchanged because the returned value was not assigned.

To store the uppercase result, write:

text = text.toUpperCase();
System.out.println(text);

Output:

JAVA

20 Useful Java String Methods

1. length() — Find the String Length

The length() method returns the number of UTF-16 code units in a string.

String text = "Hello";
System.out.println(text.length());

Output:

5

Use: Checking the length of a username, message, or other text.

2. charAt() — Get a Character by Index

The charAt() method returns the character at a specified index. Indexing starts at 0.

String text = "Java";
System.out.println(text.charAt(0));
System.out.println(text.charAt(2));

Output:

J
v

Use: Accessing a character at a particular position.

3. substring() — Extract Part of a String

The substring() method extracts part of a string.

String text = "Programming";
System.out.println(text.substring(0, 7));

Output:

Program

The starting index is included, but the ending index is excluded. Here, characters at indexes 0 through 6 are returned.

Use: Extracting a username prefix or part of a message.

4. toUpperCase() — Convert to Uppercase

This method returns a string with lowercase letters converted to uppercase.

String text = "Hello Java";
System.out.println(text.toUpperCase());

Output:

HELLO JAVA

Use: Displaying text in uppercase or normalizing text for certain comparisons.

5. toLowerCase() — Convert to Lowercase

This method returns a lowercase version of the string.

String text = "HELLO JAVA";
System.out.println(text.toLowerCase());

Output:

hello java

Use: Case normalization, such as preparing text for a case-insensitive comparison. For language-independent identifiers, use locale-independent handling where appropriate.

6. equals() — Compare String Contents

The equals() method checks whether two strings contain the same sequence of characters.

String a = "Java";
String b = "Java";

System.out.println(a.equals(b));

Output:

true

Use: Comparing passwords, names, and other text values when exact case-sensitive equality is required.

7. equalsIgnoreCase() — Compare Without Case Sensitivity

This method compares two strings while ignoring case differences.

String a = "Java";
String b = "JAVA";

System.out.println(a.equalsIgnoreCase(b));

Output:

true

Use: Comparing text when uppercase and lowercase differences should not matter.

8. contains() — Check Whether Text Exists

The contains() method returns true if the string contains the specified character sequence.

String text = "Learn Java Programming";

System.out.println(text.contains("Java"));
System.out.println(text.contains("Python"));

Output:

true
false

Use: Checking whether a message contains a keyword.

9. indexOf() — Find the First Matching Position

This method returns the index of the first occurrence of a specified character or substring. It returns -1 if there is no match.

String text = "Java Programming";

System.out.println(text.indexOf("a"));
System.out.println(text.indexOf("Program"));
System.out.println(text.indexOf("Python"));

Output:

1
5
-1

Use: Finding where a character or word first appears.

10. lastIndexOf() — Find the Last Matching Position

This method returns the index of the last occurrence of the specified character or substring.

String text = "banana";

System.out.println(text.lastIndexOf("a"));

Output:

5

Use: Finding the last occurrence of a character, such as a dot in a filename.

11. startsWith() — Check the Beginning of a String

This method checks whether a string begins with a specified prefix.

String text = "Java Programming";

System.out.println(text.startsWith("Java"));
System.out.println(text.startsWith("Python"));

Output:

true
false

Use: Checking prefixes in filenames, labels, or text records.

12. endsWith() — Check the End of a String

This method checks whether a string ends with a specified suffix.

String file = "report.pdf";

System.out.println(file.endsWith(".pdf"));
System.out.println(file.endsWith(".jpg"));

Output:

true
false

Use: Basic filename checks. For security-sensitive file validation, do not rely on the filename extension alone.

13. replace() — Replace Characters or Text

The replace() method returns a new string in which matching characters or character sequences are replaced.

String text = "I like Python";

System.out.println(text.replace("Python", "Java"));

Output:

I like Java

Use: Replacing words or characters in text.

14. replaceAll() — Replace Using a Regular Expression

This method replaces every substring matching a regular expression.

String text = "Java123Programming456";

System.out.println(text.replaceAll("[0-9]", ""));

Output:

JavaProgramming

The pattern [0-9] matches a digit, so every digit is removed.

Use: Removing unwanted characters or formatting text with regular expressions.

15. trim() — Remove Leading and Trailing Basic Spaces

The trim() method removes leading and trailing characters whose values are at most U+0020.

String text = "   Hello Java   ";

System.out.println(text.trim());

Output:

Hello Java

Use: Removing ordinary spaces around user input. For broader Unicode whitespace handling, consider strip().

16. strip() — Remove Leading and Trailing Unicode Whitespace

The strip() method removes leading and trailing whitespace as defined by Java's Character.isWhitespace().

String text = "   Hello Java   ";

System.out.println(text.strip());

Output:

Hello Java

Use: Cleaning text when broader whitespace handling is required. This method was introduced in Java 11.

17. split() — Divide a String into Parts

The split() method divides a string around matches of a regular expression and returns a string array.

String text = "Java,Python,C++";

String[] languages = text.split(",");

for (String language : languages) {
    System.out.println(language);
}

Output:

Java
Python
C++

Use: Splitting comma-separated text into individual values.

Important: The separator is a regular expression. Special characters such as . may need escaping when you want to match them literally.

18. isEmpty() — Check Whether a String Is Empty

The isEmpty() method returns true when the string has a length of zero.

String a = "";
String b = "Java";

System.out.println(a.isEmpty());
System.out.println(b.isEmpty());

Output:

true
false

Use: Checking whether a string contains zero characters. A string containing spaces is not empty.

19. isBlank() — Check Whether a String Is Blank

The isBlank() method returns true when the string is empty or contains only whitespace characters as defined by Java's Character.isWhitespace().

String a = "";
String b = "   ";
String c = "Java";

System.out.println(a.isBlank());
System.out.println(b.isBlank());
System.out.println(c.isBlank());

Output:

true
true
false

Use: Checking whether a text field contains meaningful non-whitespace content. This method was introduced in Java 11.

20. concat() — Join Two Strings

The concat() method appends one string to the end of another and returns the combined result.

String first = "Hello";
String second = " Java";

System.out.println(first.concat(second));

Output:

Hello Java

Use: Joining two strings. For more complex string building inside loops, StringBuilder is often more suitable.

Bonus: compareTo() — Compare Strings Lexicographically

Although it is not included in the main list of 20, compareTo() is another useful String method.

String a = "Apple";
String b = "Banana";

System.out.println(a.compareTo(b));

Output:

-1

For these particular strings, the result is negative because "Apple" comes before "Banana" in lexicographic comparison. In general, compareTo() returns a negative integer, zero, or a positive integer; do not assume it always returns exactly -1, 0, or 1.

Complete Java Program Using String Methods

The following example demonstrates several String methods in one program.

public class Main {
    public static void main(String[] args) {
        String message = "  Learn Java Programming  ";

        System.out.println("Original: " + message);
        System.out.println("Length: " + message.length());
        System.out.println("Trimmed: " + message.trim());
        System.out.println("Uppercase: " + message.toUpperCase());
        System.out.println("Lowercase: " + message.toLowerCase());
        System.out.println("Contains Java: " + message.contains("Java"));
        System.out.println("Starts with spaces: " + message.startsWith("  "));
        System.out.println("Replace: " + message.replace("Java", "Core Java"));
        System.out.println("Is blank: " + message.isBlank());
    }
}

Output:

Original:   Learn Java Programming
Length: 26
Trimmed: Learn Java Programming
Uppercase:   LEARN JAVA PROGRAMMING
Lowercase:   learn java programming
Contains Java: true
Starts with spaces: true
Replace:   Learn Core Java Programming
Is blank: false

The original string contains leading and trailing spaces, which is why its length is greater than the length of the trimmed text. Methods such as trim(), toUpperCase(), and replace() return new strings rather than modifying the original object.

Difference Between equals() and == in Java

Beginners often confuse these two operators.

  • equals() compares string contents.

  • == checks whether two references point to the same object.

Example:

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

System.out.println(a.equals(b));
System.out.println(a == b);

Output:

true
false

The strings have the same content, but they are separate objects. Use equals() when comparing string contents.

Common Mistakes When Using String Methods

  1. Using == for content comparison: Use equals() when you want to compare text values.

  2. Ignoring immutability: Calling replace() or toUpperCase() does not modify the original string.

  3. Using an invalid index: charAt() and substring() can throw StringIndexOutOfBoundsException for invalid indexes.

  4. Confusing isEmpty() and isBlank(): A string containing spaces is not empty, but it can be blank.

  5. Forgetting regular expressions: split() and replaceAll() interpret patterns as regular expressions.

  6. Using newer methods on older Java versions: strip() and isBlank() require Java 11 or later.

Frequently Asked Questions (FAQs)

1. What are String methods in Java?

String methods are built-in methods provided by Java's String class for working with text, such as searching, comparing, extracting, and replacing characters.

2. Is a String mutable or immutable in Java?

A String is immutable. Once created, its contents cannot be changed; operations that produce modified text return a string result.

3. What is the difference between length() and charAt()?

length() returns the string's length in UTF-16 code units, while charAt(index) returns the UTF-16 code unit at the specified index.

4. How do you compare two strings in Java?

Use equals() for case-sensitive content comparison or equalsIgnoreCase() when case differences should be ignored.

5. What is the difference between trim() and strip()?

trim() removes leading and trailing characters up to U+0020. strip() uses Java's Unicode-aware Character.isWhitespace() definition.

6. What is the difference between isEmpty() and isBlank()?

isEmpty() checks whether the string length is zero. isBlank() also returns true for strings containing only recognized whitespace characters.

7. Which Java version supports isBlank() and strip()?

Both methods were introduced in Java 11.

Practice Exercises for Beginners

Try these exercises to practise the String methods you have learned:

  1. Write a program to convert a user's name to uppercase.

  2. Count the number of characters in a string.

  3. Check whether a sentence contains the word "Java".

  4. Replace every space in a string with a hyphen.

  5. Split a comma-separated list of names and print each name on a new line.

  6. Compare two strings using both equals() and equalsIgnoreCase().

  7. Check whether a string is empty or contains only whitespace.

Conclusion

Java String methods make text processing easier and more efficient. By learning methods such as length(), charAt(), substring(), equals(), contains(), replace(), split(), trim(), and isBlank(), you can handle common text operations in real Java applications.

Practise these examples and experiment with different strings to understand how each method behaves.