Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Java String Methods

The String class provides a large set of methods for inspecting, comparing, transforming, and splitting text. Because Strings are immutable, every method that seems to change a String actually returns a new String object with the result, leaving the original unchanged.

Why it matters

Most everyday string work — trimming input, checking a prefix, splitting a line, comparing ignoring case — is one method call if you know the method exists. The details matter, though: indexes start at 0, the end index of substring is exclusive, and split takes a regular expression. Getting one of those wrong gives an off-by-one result or a runtime exception.

Inspecting and Accessing Characters

These methods let you read information about a String without altering it.

  • length() — returns the number of characters (not a field, so it is called with parentheses, unlike arrays).
  • charAt(int index) — returns the character at a given zero-based index; throws StringIndexOutOfBoundsException if the index is invalid.
  • indexOf(String str) / lastIndexOf(String str) — return the position of the first or last occurrence of a substring, or -1 if not found.
  • substring(int begin) and substring(int begin, int end) — extract part of the String; "end" is exclusive.

Comparing Strings

Java gives you several comparison methods, and choosing the wrong one is a very common source of bugs. equals() compares character content exactly (case-sensitive). equalsIgnoreCase() compares content while ignoring case differences. compareTo() compares Strings lexicographically and returns a negative, zero, or positive int, which is useful for sorting. Crucially, == compares object references, not content, so it should never be used to check whether two Strings "say the same thing."

Transforming and Splitting

These methods return new Strings (or arrays of Strings) derived from the original.

  • toUpperCase() / toLowerCase() — return a new String with case changed.
  • trim() removes leading/trailing ASCII whitespace; strip() (Java 11+) is Unicode-aware and preferred in modern code.
  • replace(char/CharSequence old, char/CharSequence new) — replaces all occurrences of one character or sequence with another.
  • split(String regex) — splits the String into a String[] using a regular expression delimiter.
  • String.format(String pattern, Object... args) — builds a formatted String using placeholders like %s, %d, and %.2f.

Example

Common String methods used together

Java
public class StringMethodsDemo {
    public static void main(String[] args) {
        String text = "  Java Programming  ";

        System.out.println(text.trim());
        System.out.println(text.trim().length());
        System.out.println(text.trim().toUpperCase());
        System.out.println(text.trim().indexOf("Programming"));
        System.out.println(text.trim().substring(0, 4));
        System.out.println("Java".equals("java"));
        System.out.println("Java".equalsIgnoreCase("java"));

        String[] words = text.trim().split(" ");
        System.out.println(words.length);

        String formatted = String.format("Score: %d/%d (%.1f%%)", 45, 50, 90.0);
        System.out.println(formatted);
    }
}
Output
Java Programming
16
JAVA PROGRAMMING
5
Java
false
true
2
Score: 45/50 (90.0%)

Common Mistakes

  • Using == instead of .equals() to compare String content, which compares references and often gives a misleading result.
  • Forgetting that substring(begin, end) excludes the character at "end", leading to off-by-one errors.
  • Calling a String method and discarding its return value, expecting the original variable to be modified (e.g. writing "text.trim();" alone instead of "text = text.trim();").
  • Using trim() when the input contains non-ASCII whitespace (like a non-breaking space) and being surprised it is not removed — strip() handles that correctly.

Exercise

Write a method that decides whether a phrase is a palindrome, ignoring spaces and upper or lower case.

Expected output: true for "Never odd or even", then false for "WebNest".

Java · starter code
public class Palindrome {

    static boolean isPalindrome(String text) {
        // TODO: remove spaces, ignore case, then compare characters from both ends
        return false;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Never odd or even"));
        System.out.println(isPalindrome("WebNest"));
    }
}
Show hints
  • text.replace(" ", "").toLowerCase() gives you a clean string to compare.
  • Compare charAt(i) with charAt(length - 1 - i) for the first half of the string.
Show solution
Java · solution
public class Palindrome {

    static boolean isPalindrome(String text) {
        String clean = text.replace(" ", "").toLowerCase();
        for (int i = 0; i < clean.length() / 2; i++) {
            if (clean.charAt(i) != clean.charAt(clean.length() - 1 - i)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Never odd or even")); // true
        System.out.println(isPalindrome("WebNest"));           // false
    }
}

Quick quiz

1. What does "Hello".substring(1, 3) return?

  • A. Hel
  • B. ell
  • C. el
  • D. He
Show answer

C. The start index is inclusive and the end index is exclusive, so you get the characters at index 1 and 2: "el".

2. What is the length of the array returned by "a,b,,c".split(",")?

  • A. 3
  • B. 2
  • C. 5
  • D. 4
Show answer

D. The result is "a", "b", an empty string and "c". Empty strings in the middle are kept; only trailing empty strings are removed.

3. What does " hi ".trim().length() return?

  • A. 2
  • B. 4
  • C. 3
  • D. 5
Show answer

A. trim() removes leading and trailing whitespace, leaving "hi", which has length 2.

Interview questions

What is the difference between equals(), equalsIgnoreCase() and compareTo()?

Show answer

equals() returns true only when both strings have exactly the same characters. equalsIgnoreCase() does the same but treats upper and lower case as equal. compareTo() returns an int for ordering: negative if the string sorts before the argument, zero if they are equal, and positive if it sorts after. Use it for sorting, not for a simple equality check.

How do you avoid a NullPointerException when comparing a String that may be null?

Show answer

Call equals on the value you know is not null, for example "ADMIN".equals(role), which simply returns false when role is null. Alternatively use Objects.equals(a, b), which handles null on either side.

Key Points to Remember

  • All String methods return new values; none modify the String in place.
  • Use .equals()/.equalsIgnoreCase() for content comparison, and compareTo() for ordering — never == for content.
  • substring(begin, end) treats "end" as exclusive; split() uses a regular expression.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering