String Methods in Java

Naveen AnamaneniUpdated · 4 min read
easyJava 25javastrings

String has more than 60 methods, but a dozen of them do almost all the work in real programs: finding text, checking text, changing case, replacing and splitting. This lesson groups them by the job you're trying to do, so you know where to look. Remember one rule throughout: strings never change, so every method that "modifies" text returns a new string.

Finding Things in a String

indexOf searches from the left, lastIndexOf from the right; -1 means not found
Find.java▶ Try it
public class Find {
    public static void main(String[] args) {
        String t = "Navika Anamaneni, Hyderabad";
 
        System.out.println(t.length());
        System.out.println(t.charAt(7));
        System.out.println(t.indexOf("a") + " " + t.lastIndexOf("a"));
        System.out.println(t.indexOf('a', 2) + " " + t.indexOf("x"));
        System.out.println(t.contains("Hyd") + " " + t.startsWith("Nav")
            + " " + t.endsWith("bad"));
    }
}
Output
27
A
1 25
5 -1
true true true

How it works

  1. length() counts every character, including spaces and the comma: 27.
  2. charAt(7) reads one character; position 7 is the A of "Anamaneni".
  3. indexOf returns the first position of the text, lastIndexOf the last. Both count from 0.
  4. indexOf('a', 2) starts looking at position 2. When nothing is found, the answer is -1.
  5. contains, startsWith and endsWith give a simple true or false.

Changing Text into a New String

Change.java▶ Try it
import java.util.Arrays;
 
public class Change {
    public static void main(String[] args) {
        String raw = "  Navika Anamaneni, Hyderabad  ";
        String t = raw.trim();
        System.out.println("[" + t + "]");
 
        System.out.println(t.toUpperCase());
        System.out.println(t.replace('a', '@'));
        System.out.println(t.replace("Hyderabad", "Pune"));
        System.out.println(Arrays.toString(t.split(", ")));
        System.out.println(Arrays.toString("abc".toCharArray()));
    }
}
Output
[Navika Anamaneni, Hyderabad]
NAVIKA ANAMANENI, HYDERABAD
N@vik@ An@m@neni, Hyder@b@d
Navika Anamaneni, Pune
[Navika Anamaneni, Hyderabad]
[a, b, c]

How it works

  1. trim() removes spaces at both ends. The brackets show exactly where the text starts and stops.
  2. toUpperCase() and toLowerCase() change case.
  3. replace swaps every match, whether a single character or a piece of text.
  4. split(", ") breaks the text into an array wherever ", " appears.
  5. toCharArray() gives a copy of the characters as a char[].

Quick Reference by Job

JobMethods
Size and single characterslength(), charAt(i), isEmpty(), isBlank()
SearchingindexOf, lastIndexOf, contains, startsWith, endsWith
Comparingequals, equalsIgnoreCase, compareTo (see "String Comparison in Java")
Cuttingsubstring (see "Substring in Java"), split
Changing casetoUpperCase(), toLowerCase()
Replacingreplace (plain text), replaceAll and replaceFirst (patterns)
Removing spacestrim(), strip(), stripLeading(), stripTrailing()
ConvertingtoCharArray(), chars(), String.valueOf(x), getBytes()
Joining and repeatingString.join, repeat, concat

Common Mistakes

Ignoring the return value. s.replace("a", "b"); alone changes nothing.

Splitting on ., | or + without escaping. They're special in patterns; use "\\.", "\\|" or "\\+".

Forgetting that indexOf returns -1. Check before using the position.

Practice

  1. Easy: For the sentence "Java is fun and Java is fast", print the first and last positions of "Java", and the sentence with "Java" replaced by "Kotlin".
  2. Harder: Given "Navika:91,Srihitha:88,Advitha:95", split it into name-score pairs and print each on its own line as Navika scored 91.

Quick check: String methods

4 questions
1What does "Hello".indexOf("z") return?
2What does " hi ".trim() return?
3What does "a-b-c".split("-") give?
4Which treats its argument as plain text, not a pattern?

Key Takeaways

Was this tutorial helpful?

Lesson 194 of 482