🌱BeginnerWorking with Strings

String Methods

Master the most useful String methods in Java - length, charAt, substring, indexOf, replace, split, contains, and more.

Overview

Strings are objects in Java, and the String class provides a rich set of methods for querying and transforming text. Since Strings are immutable, every method returns a new String - the original is never modified. Learning the core String methods is essential because text processing is everywhere: validating user input, parsing data, building messages, and manipulating file paths.

Key Points

  • •length() - number of characters (not .length without parentheses - that's for arrays)
  • •charAt(i) - character at index i (zero-based)
  • •substring(start) or substring(start, end) - extract part of the string
  • •indexOf("x") - first occurrence index, or -1 if not found
  • •contains("x") - true if the string contains the substring
  • •replace("old", "new") - returns a new string with all occurrences replaced
  • •split("regex") - splits into a String[] at each match
  • •trim() / strip() - removes leading and trailing whitespace
  • •startsWith / endsWith - check beginning/end
  • •isEmpty() / isBlank() - check for empty or whitespace-only

Examples

Length, charAt, and substring

public class Main {
    public static void main(String[] args) {
        String s = "Hello, World!";

        System.out.println(s.length());       // 13
        System.out.println(s.charAt(0));      // H
        System.out.println(s.charAt(7));      // W
        System.out.println(s.substring(7));   // World!
        System.out.println(s.substring(7, 12)); // World (end index exclusive)
        System.out.println(s.indexOf("World")); // 7
        System.out.println(s.indexOf("xyz"));   // -1 (not found)
    }
}

substring(start, end) is exclusive at end: "Hello"[1,4] = "ell", not "ello".

Searching and replacing

public class Main {
    public static void main(String[] args) {
        String email = "  user@example.com  ";
        String clean = email.trim();
        System.out.println(clean);          // user@example.com
        System.out.println(clean.contains("@"));        // true
        System.out.println(clean.startsWith("user"));   // true
        System.out.println(clean.endsWith(".com"));     // true

        String sentence = "I love cats. Cats are great.";
        System.out.println(sentence.replace("cats", "dogs"));
        // I love dogs. Cats are great. (only replaces the first "cats" - lowercase)
        System.out.println(sentence.replaceAll("(?i)cats", "dogs"));
        // case-insensitive replace: I love dogs. dogs are great.
    }
}

replace() is case-sensitive. Use replaceAll() with regex flag (?i) for case-insensitive replacement.

Splitting strings and checking emptiness

public class Main {
    public static void main(String[] args) {
        // Split CSV line
        String csv = "Alice,30,Engineer,London";
        String[] fields = csv.split(",");
        for (String f : fields) {
            System.out.println(f);
        }
        // Alice  30  Engineer  London

        // Check emptiness
        String empty = "";
        String blank = "   ";
        System.out.println(empty.isEmpty());  // true
        System.out.println(blank.isEmpty());  // false - has spaces
        System.out.println(blank.isBlank());  // true  - only whitespace

        // Join words
        String joined = String.join(", ", "red", "green", "blue");
        System.out.println(joined); // red, green, blue
    }
}

isBlank() (Java 11+) is better than isEmpty() when whitespace should count as empty.

Common Mistakes

  • Using .length instead of .length() - Strings use the method .length(), not the field .length (arrays use .length)
  • Forgetting substring end is exclusive: "Hello".substring(1, 4) = "ell", not "ello"
  • Not checking indexOf != -1 before using the result - if indexOf returns -1, using it as an index will throw an exception

Note

Chain String methods: `input.trim().toLowerCase().replace(" ", "_")` cleans and formats in one readable line. Since each method returns a new String, chains read naturally left to right.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What does `"Hello".substring(2, 4)` return?