Beginner 5 min

Strings and text comparisons

A Java String stores text and offers methods to inspect or transform it.

How it works

Trace a slice using zero-based indexes. The start is included and the end is excluded, so "books".substring(1, 4) gives ook. A String never changes in place. Operations such as trim return a value that you can store or pass onward.

Walk through an example

Call title.length() to get its length and title.substring(0, 3) to take its first three positions. Use title.equals(other) to compare text values.

What to watch for

The == operator compares references when used with objects. Two different String objects can contain exactly the same characters.

Code example

public class Main {
    public static void main(String[] args) {
        String left = new String("cat");
        String right = new String("cat");
        System.out.println(left.equals(right));
    }
}

Check your understanding

Which comparison checks that their text matches?

See the example and explanation
Worked example
Given new String("cat") and another new String("cat")
Answer equals

Both objects contain the same characters, so equals returns true.

Open practice problem
Next lessonReading and validating console input