Strings and their methods
What you'll learn:
- read a string position by position and cut a piece out of it with
charAtandsubstring; - explain why a string method does not change the string but returns a new one;
- compare strings with
equalsand explain when==givestrue; - build a string in a loop with
StringBuilderand treatcharcharacters as numbers.
Imagine a printed card with some text. The letters stand on it in a row, each in its own cell, and the cells are numbered. You can do a lot with the card: count the cells, read the letter in any of them, find a word. One thing you cannot do is erase or correct a letter: the card is printed.
A string in Java is such a card. Text is kept in a variable of type String: String name = "Anna";. Programs work with text all the time: names, messages, commands. Often the text has to be taken apart, not only printed: find its length, take the first letter, find a word, cut out a piece. A string has its own methods for that:
public class Main {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.length()); // 4
System.out.println(word.charAt(0)); // J
System.out.println(word.charAt(3)); // a
}
}Let's go through the program line by line:
String word = "Java";puts a string of four characters into the variableword.word.length()returns the length of the string,4.word.charAt(0)returns the character in cell number 0,J.word.charAt(3)returns the character in the last cell,a.
String methods
String is a class, and every string is an object of it. Like an array, a string is created by the JVM on the heap, but a string also has its own methods: actions it can perform. You call them with a dot after the string itself: word.length(). Such a method works with the string it was called on—with word, not with some other string.
The parentheses after a method's name are always needed, even empty ones: this is a call, like square(3).
Character numbers
A cell's number is the character's index. As in an array, indexes start at zero:
- the first character has index
0; - the last one has
length() - 1, which is3for"Java"; - an index past the end of the string, such as
word.charAt(4), stops the program with aStringIndexOutOfBoundsException.
charAt returns a single character, not a string: a value of type char.
Part of a string: substring
A substring is a piece of a string that runs without gaps. The method substring(begin, end) returns the substring from index begin to index end:
String text = "Hello, Java";
System.out.println(text.substring(7, 11)); // Java
System.out.println(text.substring(0, 5)); // Hello
System.out.println(text.substring(7)); // JavaThese are the rules of substring:
- the character at index
beginis included in the result; - the character at index
endis not: the substring ends right before it; - so the result holds
end - begincharacters:substring(0, 5)gives the five charactersHello; - with one argument,
substring(7), the method takes everything from index7to the end of the string.
Why leave the end out? It is convenient for splitting: substring(0, 5) and substring(5, 11) cut "Hello, Java" into two parts with no gaps and no overlap. Interviewers like to ask what substring with two arguments returns, to check whether you remember the excluded end.
The card picture is off here. You can cut a real card with scissors, and a piece stays in your hands. substring does not cut the card: it creates a new string with the characters you need, and text stays whole.
Searching and new strings
A few more methods that almost every program needs:
String raw = " Hi, Bob ";
String clean = raw.strip();
System.out.println("[" + clean + "]"); // [Hi, Bob]
System.out.println(clean.indexOf("Bob")); // 4
System.out.println(clean.indexOf("Ann")); // -1
System.out.println(clean.contains("Hi")); // true
System.out.println(clean.toUpperCase()); // HI, BOB
System.out.println(clean.replace("Bob", "Ann")); // Hi, Ann
System.out.println(" ".isBlank()); // trueLet's take them in order:
strip()removes the spaces at the start and at the end of the string. The square brackets in the output show that no spaces are left.indexOf("Bob")looks for a substring and returns the index where it starts,4. If the substring is not there, it returns-1.contains("Hi")answerstrueorfalse: whether the string holds such a substring.toUpperCase()returns the string in capital letters, andtoLowerCase()in small ones.replace("Bob", "Ann")replaces every occurrence of the first substring with the second.isBlank()givestrueif the string holds nothing but spaces. For the empty string""it givestruetoo.
Common mistake
The length of a string is requested without parentheses:
String word = "Java";
int n = word.length; // ✗error: cannot find symbolThe program does not compile. An array's length is read without parentheses, a.length, but a string's length is the method length(), and the parentheses are required. The compiler looks for a length without parentheses on the string, does not find one and reports that no such name exists. Write word.length().
Key points
- String methods are called with a dot:
word.length(),word.charAt(0); the parentheses are always needed. - Character indexes start at zero, and the last character's index is
length() - 1. substring(begin, end)includesbeginand excludesend, so the result holdsend - begincharacters.indexOfreturns the index where a substring starts, or-1if it is not there.