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 includedshow.toUpperCase()andshow.toLowerCase()change the caseshow.substring(0, 5)takes positions 0 to 4: the end isn't includedshow.indexOf("P")finds where something starts, or gives -1show.charAt(6)gives the char at one positionshow.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
PStrings 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 PIRATESTip
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.