Java Arena
Step 3 of 6

Comparing text with equals

Text is compared with equals, not with ==:

Scanner scanner = new Scanner(System.in);
String first = scanner.nextLine();
String second = scanner.nextLine();
System.out.println(first.equals(second));
System.out.println(first == second);
Input
cat
cat
Output
true
false

Both lines are cat, yet == says false. For Strings, == doesn't check whether the texts are the same: it checks whether the two variables refer to the very same String object in memory. Every nextLine() that reads some text makes a new String, so two reads of the same word aren't ==. first.equals(second) compares the characters, which is what you want. Module 22 explains objects and references properly.

To compare with a fixed word, write the text in quotes: command.equals("quit"). Capitals count: "Quit".equals("quit") is false. equalsIgnoreCase ignores them.

Your task

Challenge 1 of 3

Ask for a password and print Welcome! when it's exactly swordfish (capitals count, so Swordfish is wrong), otherwise Wrong password. For the input swordfish the program prints:

Password:
Welcome!

Challenge 2

Read two words and print Same when they're exactly the same text (capitals count: apple and Apple are different), otherwise Different. For the input apple and apple the program prints:

Same

Challenge 3

A tiny command menu. Read a command and answer:

  • help prints Commands: help, hello, quit
  • hello prints Hi there!
  • quit prints Bye!
  • anything else prints Unknown command: and the command

For the input hello the program prints Hi there!.