Java Arena
Step 2 of 8

Comparing strings

Module 6 showed that text is compared with equals. Here's the rule once more, with the reason behind it. == asks whether two variables refer to one and the same String object in memory, while equals compares the characters:

answer == "yes"         // wrong: are they the very same object?
answer.equals("yes")    // right: do they have the same characters?

What makes == tricky is that it sometimes seems to work. Java may reuse one String object for equal texts written in the code, and whether two strings end up as the same object depends on where they came from and on Java's own internals. So a program that compares text with == can pass a quick test and then fail on real input. With equals, the result depends only on the text. (For int and char values, which aren't objects, == is the right tool.)

Ignoring capitals

equals counts capitals: "Yes".equals("yes") is false. When capitals shouldn't matter, use equalsIgnoreCase:

Scanner scanner = new Scanner(System.in);
System.out.println("Play again? (yes/no)");
String answer = scanner.nextLine();
if (answer.equalsIgnoreCase("yes")) {
    System.out.println("New game!");
} else {
    System.out.println("Thanks for playing");
}
Input
YES
Output
Play again? (yes/no)
New game!

Two more tools go well with comparing:

  • ! in front turns the result around: if (!answer.equals("no")) runs its block for every answer except no.
  • People sometimes type a space before or after a word without noticing. answer.trim().equalsIgnoreCase("yes") trims first and then compares, so " Yes " counts too.

A method can return the result of a comparison as a boolean:

public class Main {
    public static void main(String[] args) {
        System.out.println(isWeekend("Sunday"));
        System.out.println(isWeekend("monday"));
        System.out.println(isWeekend("SATURDAY"));
    }

    public static boolean isWeekend(String day) {
        return day.equalsIgnoreCase("saturday") || day.equalsIgnoreCase("sunday");
    }
}
Output
true
false
true

Your task

Challenge 1 of 3

A shop's checkout takes one discount code, SPRING10, and capitals don't matter: spring10 and Spring10 work too. Ask for the code, read it, and print Code accepted for the right code, otherwise Unknown code. For the input spring10 the program prints:

Discount code:
Code accepted

Challenge 2

Write a method isYes(String answer) that returns true when the answer is yes or y, in any capitals and with or without spaces around it, and false for anything else. The check runs System.out.println(isYes(" Yes ")); and expects:

true

Challenge 3

Read words, one per line, until a word is the same as the one just before it (capitals count). Then print Said twice: and that word. For the input red, green, blue and blue the program prints:

Said twice: blue