Java Notes
Java String methods read, search, compare, extract, and transform text. Because String is immutable, methods that change text return a new String.
String methods let you work with text without manually looping through every character. Read the method name as a question: does it return information, or does it return a new String?
Read and search text
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
length() returns the number of characters. charAt(0) reads the first character because indexing starts at zero. indexOf() returns the starting position of text or -1 when it is absent. contains() gives a simple true/false answer.
Extract part of a String
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
substring(start, end) includes start and excludes end. The one-argument form, substring(start), continues to the end. Find the @ first so the code works for different user names.
Transform text
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
trim() removes edge spaces, toLowerCase() normalises case, and replace() changes matching text. Method chaining is safe here because each method returns a new String. Notice that rawName keeps its original value.
Split text into pieces
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
split() returns an array. Its separator is a regular expression, so simple punctuation such as a comma works directly, while characters such as . and | need escaping.
Compare text safely
Use equals() for an exact match and equalsIgnoreCase() when case should not matter. Avoid ==; it compares object references rather than the characters.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Continue the lesson path