1

Possible Duplicate:
How do I compare strings in Java?

import java.util.Scanner;

 public class stringComparer {
    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        System.out.println ("Enter 1 word here - ");
        String word1 = scan.next();

    System.out.println ("Enter another word here - ");
    String word2 = scan.next();

    if (word1 == word2) {
        System.out.println("They are the same");
    }
}
}

I had it working about 10 minutes ago, changed something and it now it doesn't display "They are the same" for some reason? Its really simple yet I can't see where I've gone wrong.

Thanks!

Community
  • 1
  • 1
user1554786
  • 247
  • 2
  • 9
  • 21

3 Answers3

1

The == operator compares objects by reference.

To find out whether two different String instances hold the same value, call .equals().

Therefore, replace

if (word1 == word2)

with

if (word1.equals(word2))
pstanton
  • 35,033
  • 24
  • 126
  • 168
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Please Try this it will work, String is not primitive so when u check == it will check the references .

import java.util.Scanner;
/**
 * This program compares two strings
 * @author Andrew Gault
 * @version 28.10.2012
 */
 public class stringComparer
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner (System.in);
        System.out.println ("Enter 1 word here - ");
        String word1 = scan.next();

    System.out.println ("Enter another word here - ");
    String word2 = scan.next();

    if (word1.equals(word2))
    {
        System.out.println("They are the same");
    }

}
}
sunleo
  • 10,589
  • 35
  • 116
  • 196
0

Use

if (word1.equals(word2))
{
 System.out.println("They are the same");   
}

See why here

Community
  • 1
  • 1
Suresh Kumar
  • 11,241
  • 9
  • 44
  • 54