Cornelius Eanes's Programming Portal
Assignments (Strings)
[30] Comparing Strings

Goal: Find out how to properly compare two Strings.

/// Name: Cornelius Eanes
/// Period: 5
/// Program Name: Comparing Strings
/// File Name: ComparingStrings.java
/// Date Finished: Oct 01, 2015

import java.util.Scanner;

public class ComparingStrings {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String word, correctWord = "Evangelion";
        boolean isCorrect, isCorrectIgnoreCase, isCorrectReference;

        System.out.println("Type out the word: \"" + correctWord + "\"");
        word = input.next();

        isCorrect = correctWord.equals(word);
        isCorrectIgnoreCase = correctWord.equalsIgnoreCase(word);
        isCorrectReference = correctWord == word;

        System.out.println("Correct word typed: " + isCorrect);
        System.out.println("Correct word typed (case ignored): " + isCorrectIgnoreCase);
        System.out.println("Correct word typed (by reference): " + isCorrectReference);

    }

}

Output

Explanation

As you can see, a String variable isn't an ordinary variable. Integers and doubles can only hold a single value, while Strings actually hold lots of numbers, known as chars (characters). The String variable isn't a variable at all, but rather an object. When comparing single-valued variables (known technically as primitive data types), Java checks their actual value, while with objects, Java checks if it's the same object with the same memory addresses being compared. Of course, the only way this could result in true is the following statement: isCorrectReference = word == word, which isn't useful in any way.