0

I'm trying to create a program which takes user input of two words and determines whether or not these words are the same.

import java.util.Scanner;
public class L7E3 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System. in );
        String word1, word2;

        System.out.println("Please enter a word: ");
        word1 = keyboard.nextLine();
        System.out.println("Please enter a word: ");
        word2 = keyboard.nextLine();

        if (word1 == word2) {
            System.out.println("The words are " + word1 + " and " + word2 + ". These words are the same.");
        } else {
            System.out.println("The words are " + word1 + " and " + word2 + ". These words are not the same.");
        }
    }
}

I figured that word1==word2 would have worked to determine whether the two strings were equal, I'm using JGrasp and it goes directly to my else option regardless of input. Am I doing something wrong with strings?

Samuel O'Malley
  • 3,471
  • 1
  • 23
  • 41
Jeremy Stone
  • 350
  • 4
  • 12
  • 29

3 Answers3

0
if(word1.equals(word2))

== doesn't do what you think it does. == essentially compares the memory locations of the two String variables and returns true only if they're located at the same memory location. The String.equals method compares the contents of the strings and returns true if they hold the same characters.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
0

Short answer: use String#equals(Object) instead:

word1.equals(word2)

For a super detailed explanation to the reasoning why: check out this.

Community
  • 1
  • 1
Josh M
  • 11,611
  • 7
  • 39
  • 49
0

For Strings you need to use the .equals() function rather than the == equality operator.

if(word1.equals(word2))

If you wanted to test if two words are the same, while ignoring case ("This" is the same as "this) then you need to do something like this:

if (word1.toLowerCase().equals(word2.toLowerCase()))

Also in your specific example you might want to remove unnecesary whitespace from before and after the word (" word1 " should becomes "word1"). You can do this using the trim() function:

word1 = word.trim();

Samuel O'Malley
  • 3,471
  • 1
  • 23
  • 41