Task 12 of 15 · 0 solved · 15 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

1.5 Strings — comparing strings

Lesson

Why == is the wrong tool

For numbers == asks «is it the same value?». For strings it asks something else: is it the same object in memory? Two strings can hold identical characters and still be different objects — and then == answers false.

To compare the content use equals. It is not a matter of style: == on strings built while the program runs is simply a bug.


Worked example

String x = "cat";
String built = "c";
built = built + "at";      // same characters, built at run time

System.out.println(x == built);        // false — different objects!
System.out.println(x.equals(built));   // true  — same content

For ordering there is compareTo: it returns a negative number if the first string comes earlier alphabetically, 0 if they are equal, and a positive number if it comes later. Do not memorise the number itself — "apple".compareTo("apricot") gives -2, not -1. Only the sign matters.


▶ Try it: run this, then change something and run it again.



To check that two strings hold the same text, use...


compareTo returns a negative number when...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    String p = "dog";
    String q = "d";
    q = q + "og";
    System.out.println(p == q);
    System.out.println(p.equals(q));
}}

Why should you look at the sign of compareTo, not the number?


True or false?