AI Hints
Home›Java Tutorial›Strings, Joining Strings and String Methods
Java · Lesson 21 of 120

String Methods

Change, search and slice.

⏱ 2 min read▶ Video at 27:23🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Strings come with many built in methods. They clean, search, slice, and change text. You call them with a dot, after the string.

  • Built-in methods
  • Clean, search, slice
  • string.method()

A tour of methods

Trim removes spaces from both ends. To upper case, and to lower case, change the letters. Contains checks if some text is inside. Index of gives the position where it starts. Substring cuts out a part, from a start position, up to, but not including, an end. With one number, it goes to the end. Replace swaps text. And starts with, and ends with, check the edges. Run it. Java starts at position nine. The first substring is learning. And the string doesn't end with an exclamation mark.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String text = "  Learning Java is fun  ";
        String clean = text.trim();
        System.out.println("[" + clean + "]");
        System.out.println(clean.toUpperCase());
        System.out.println(clean.toLowerCase());
        System.out.println(clean.contains("Java"));
        System.out.println(clean.indexOf("Java"));
        System.out.println(clean.substring(0, 8));
        System.out.println(clean.substring(9));
        System.out.println(clean.replace("fun", "great"));
        System.out.println(clean.startsWith("Learn") + " " + clean.endsWith("!"));
    }
}
Output
[Learning Java is fun]
LEARNING JAVA IS FUN
learning java is fun
true
9
Learning
Java is fun
Learning Java is great
true false

Methods to remember

Here are the most useful ones together. You don't need to memorise them all. Your editor will suggest them, as soon as you type a dot.

MethodDoes
length()count characters
trim()remove outer spaces
toUpperCase()CAPITALS
contains(x)is x inside?
indexOf(x)where x starts
substring(a, b)characters a to b-1
replace(a, b)swap text

Summary

Strings have methods to trim, change case, search, slice, and replace. Each one returns a new string. Next, comparing strings, the right way.

Key takeaways
  • trim, toUpperCase
  • contains, indexOf
  • substring, replace
Next up: Comparing Strings — equals, not ==