Codiqo

Learn Java · lesson 7 of 61 · about 7 minutes

String Methods

Make a booking code from the film's title with substring and toUpperCase, and find out why a String never changes by itself.

What you'll learn

  • Measure and slice Strings
  • Change case and trim spaces
  • Store the String a method returns

The String toolkit

A String comes with methods: actions you call with a dot.

  • show.length() counts the characters, spaces included
  • show.toUpperCase() and show.toLowerCase() change the case
  • show.substring(0, 5) takes positions 0 to 4: the end isn't included
  • show.indexOf("P") finds where something starts, or gives -1
  • show.charAt(6) gives the char at one position
  • show.trim() removes spaces at both ends

Positions start at 0, so in Space Pirates the S is at 0 and the P is at 6.

Using the toolkit

public class Main {
    public static void main(String[] args) {
        String show = "Space Pirates";
        System.out.println(show.length());
        System.out.println(show.toUpperCase());
        System.out.println(show.substring(0, 5));
        System.out.println(show.indexOf("Pirates"));
        System.out.println(show.charAt(6));
    }
}

Output

13
SPACE PIRATES
Space
6
P

Strings never change

A String can't be changed. show.toUpperCase() makes a new String in capitals and hands it back; show stays as it was. If you don't store what comes back, it's lost.

Store the result

public class Main {
    public static void main(String[] args) {
        String show = "Space Pirates";
        show.toUpperCase();
        System.out.println(show);
        String loud = show.toUpperCase();
        System.out.println(loud);
    }
}

Output

Space Pirates
SPACE PIRATES

Tip

Methods can be chained: show.substring(0, 5).toUpperCase() takes Space, then makes it SPACE.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.