String Equality: Content vs Reference
Problem
Read two words, one on each line. Print equals: true if both words have exactly the same characters, else equals: false. Then print ignoring case: true if they are the same when upper and lower case letters are treated alike, else ignoring case: false.
Constraints
- Words have 1 to 100 letters or digits, no spaces
Examples
Input
Java java
Output
equals: false ignoring case: true
Solutions
In Java, == on two strings asks if they are the same object. equals asks if they have the same characters. Beginners often use == by mistake and get wrong answers.
/*
* Problem : Compare two words.
* Input : Two lines, one word on each line.
* Output : Two lines: equals and ignoring case.
* Approach: Compare the content, not the memory address.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String first = scanner.nextLine();
String second = scanner.nextLine();
// Step 1: Use equals to compare the characters. Do not use ==, it compares memory addresses.
boolean same = first.equals(second);
// Step 2: Use equalsIgnoreCase to ignore upper and lower case.
boolean sameIgnoringCase = first.equalsIgnoreCase(second);
// Step 3: Print both answers.
System.out.println("equals: " + same);
System.out.println("ignoring case: " + sameIgnoringCase);
}
}
Hints (1)
- What does == compare for objects in Java?