JOOPs Through Java
Challenge roadmap
0/30 Days Completed 0 Learning Days

Day 12 of 30 · Week 2 — Building Java Basics

More useful String methods

1 Learn

substring(start, end) cuts out part of a String — from start up to (not including) end.

contains(), indexOf(), replace(), trim() and equalsIgnoreCase() are used all the time.

Strings are immutable: methods return a new String instead of changing the old one.

Want more detail? Open the full lesson

2 See the Code

Java
public class Text {
    public static void main(String[] args) {
        String s = "  Learn Java  ";
        String t = s.trim();
        System.out.println(t);
        System.out.println(t.substring(0, 5));
        System.out.println(t.contains("Java"));
        System.out.println(t.indexOf("J"));
        System.out.println(t.replace("Java", "OOPS"));
        System.out.println("java".equalsIgnoreCase("JAVA"));
    }
}
  • trim() removes spaces at both ends.
  • substring(0, 5) takes indexes 0 to 4: Learn.
  • indexOf("J") is 6 because counting starts at 0.

Output

Learn Java
Learn
true
6
Learn OOPS
true

3 Practice

  • Count how many times the letter a appears in "banana" using a loop and charAt().

Try it in your own Java setup or write it in the Practice Notebook.

4 Quick Check

  1. 1. "Hello".substring(1, 3) is?

  2. 2. What does 'immutable' mean for Strings?

Step 5

Answer and check the Quick Check above to unlock this.