Java String Methods

Introduction

Strings are one of the most commonly used data types in Java programming. Whether you are processing user input, validating data, reading files, working with databases, or developing web applications, you will frequently perform operations on strings.

The Java String class provides a rich collection of built-in methods that make it easy to manipulate, compare, search, split, replace, and format text. Since the String class is immutable, these methods do not modify the original String. Instead, they return a new String with the desired changes.

The String class belongs to the java.lang package, which is automatically imported into every Java program.

What are Java String Methods?

Java String methods are predefined methods provided by the String class to perform various operations on strings.

These methods help developers:

  • Find the length of a string
  • Access characters
  • Compare strings
  • Search text
  • Replace characters
  • Extract substrings
  • Convert case
  • Remove spaces
  • Split strings
  • Join strings

Instead of writing complex code manually, you can use these built-in methods to simplify string manipulation.

Creating a String

Before using String methods, you need to create a String object.


String message = "Welcome to Java";

Now you can call various methods on the message object.

1. length() Method

The length() method returns the number of characters in a string.

Syntax


string.length();

Example


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

Output

11

Use Cases

  • Password validation
  • Input length checking
  • Character counting

2. charAt() Method

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

Syntax


string.charAt(index);

Example


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

Output

J
v

Note: Indexing starts from 0.

3. substring() Method

The substring() method extracts a portion of a string.

Example


String text = "Java Programming";
System.out.println(text.substring(5));

Output

Programming

Extract between two indexes:


System.out.println(text.substring(0, 4));

Output

Java

4. equals() Method

The equals() method compares the contents of two strings.

Example


String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2));

Output

true

Unlike the == operator, equals() compares actual text rather than object references.

5. equalsIgnoreCase() Method

This method compares two strings while ignoring letter case.

Example


String s1 = "JAVA";
String s2 = "java";
System.out.println(s1.equalsIgnoreCase(s2));

Output

true

6. compareTo() Method

The compareTo() method compares strings alphabetically.

Example


String s1 = "Apple";
String s2 = "Banana";
System.out.println(s1.compareTo(s2));

Output

-1
  • Negative value → First string comes before the second.
  • Positive value → First string comes after the second.
  • Zero → Both strings are equal.

7. contains() Method

Checks whether a string contains specific text.

Example


String text = "Java Programming";
System.out.println(text.contains("Program"));

Output

true

Useful for searching keywords.

8. startsWith() Method

Checks whether a string begins with specific text.

Example


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

Output

true

9. endsWith() Method

Checks whether a string ends with specific text.

Example


String text = "document.pdf";
System.out.println(text.endsWith(".pdf"));

Output

true

Useful for validating file extensions.

10. indexOf() Method

Returns the position of the first occurrence of a character or substring.

Example


String text = "Java Programming";
System.out.println(text.indexOf("Program"));

Output

5

If the text is not found, it returns -1.

11. lastIndexOf() Method

Returns the position of the last occurrence.

Example


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

Output

5

12. replace() Method

Replaces characters or substrings.

Example


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

Output

Python Programming

13. toUpperCase() Method

Converts all characters to uppercase.

Example


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

Output

JAVA

14. toLowerCase() Method

Converts all characters to lowercase.

Example


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

Output

java

15. trim() Method

Removes leading and trailing spaces.

Example


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

Output

Java

Useful when processing user input.

16. split() Method

Splits a string into an array.

Example


String colors = "Red,Green,Blue";
String[] list = colors.split(",");
for(String color : list)
{
    System.out.println(color);
}

Output

Red
Green
Blue

17. concat() Method

Joins two strings.

Example


String first = "Java ";
String second = "Tutorial";
System.out.println(first.concat(second));

Output

Java Tutorial

18. isEmpty() Method

Checks whether a string is empty.

Example


String text = "";
System.out.println(text.isEmpty());

Output

true

19. isBlank() Method (Java 11)

Checks whether a string contains only whitespace.

Example


String text = "   ";
System.out.println(text.isBlank());

Output

true

Unlike isEmpty(), this method considers whitespace-only strings as blank.

Summary of Common String Methods

Method Description
length() Returns string length
charAt() Returns a character
substring() Extracts part of a string
equals() Compares content
equalsIgnoreCase() Ignores letter case
compareTo() Lexicographical comparison
contains() Searches text
startsWith() Checks prefix
endsWith() Checks suffix
indexOf() Finds first occurrence
lastIndexOf() Finds last occurrence
replace() Replaces text
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
trim() Removes surrounding spaces
split() Splits into an array
concat() Joins strings
isEmpty() Checks for an empty string
isBlank() Checks for blank text (Java 11+)

Real-Life Example

Suppose you are building an online registration system.


String email = "student@example.com";
System.out.println(email.contains("@"));
System.out.println(email.endsWith(".com"));
System.out.println(email.toUpperCase());

Output

true
true
STUDENT@EXAMPLE.COM

String methods make validation and formatting much easier in real-world applications.

Advantages of String Methods

  • Easy to use
  • Reduce coding effort
  • Improve readability
  • Highly optimized by Java
  • Suitable for text processing
  • Rich collection of built-in functionality
  • Used extensively in enterprise applications

Common Mistakes

1. Using == Instead of equals()

Incorrect:


String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);

Correct:


System.out.println(s1.equals(s2));

2. Forgetting That Strings Are Immutable

Incorrect:


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

Output

java

Correct:


text = text.toUpperCase();

3. Accessing an Invalid Index

Incorrect:


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

This throws a StringIndexOutOfBoundsException.

Always ensure the index is within the valid range.

4. Ignoring Null Values


String name = null;
// name.length(); // Causes NullPointerException

Always check for null before calling String methods.

Best Practices

📖
Best Practices:
  • Use equals() instead of == for comparing string contents.
  • Validate indexes before using charAt() or substring().
  • Remember that String methods return new objects because Strings are immutable.
  • Use trim() before validating user input.
  • Use StringBuilder when performing many string modifications.
  • Handle null values safely to avoid runtime exceptions.

Conclusion

The Java String class provides a comprehensive set of methods that simplify text manipulation and make Java programming more efficient. Whether you need to compare strings, search for text, extract substrings, replace characters, or validate user input, these built-in methods eliminate the need for complex custom logic.

Since Strings are immutable, every modification returns a new object, ensuring safety and reliability in Java applications. By understanding the most commonly used String methods and following best practices—such as using equals() for comparison, validating indexes, and using StringBuilder for repeated modifications—you can write cleaner, faster, and more maintainable Java programs.

Related Java Tutorials