0

I'm getting the user input like so:

Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();

When I compare it like this

if(input == "abc"){
  System.out.println("Match!");
}else{
  System.out.println(input + "\nabc");
}

If I type "abc" I see

abc
abc

Instead of the expected match. What's going on?

Gary
  • 13,303
  • 18
  • 49
  • 71
  • I'd say that's a dupe. I'm learning Java; moving from JavaScript -- That's a new concept to me. – Gary Jan 20 '14 at 01:44
  • Sorry, we can add the `dumb-question` tag – Gary Jan 20 '14 at 01:47
  • 2
    This question is not dumb. Every rookie makes this mistake. No worries. – Pshemo Jan 20 '14 at 01:48
  • To add onto what @Pshemo said, most beginners make the mistake that Strings in Java are treated as primitives. This is due to the way they are initialized and how operators affect them. I know I was there at one point too. – Obicere Jan 20 '14 at 01:52

2 Answers2

3

You are comparing String references, not String values. Use the String.equals method instead.

Ned
  • 937
  • 6
  • 10
1

== is comparing memory locations. you need to use input.equals("abc") instead.

axiopisty
  • 4,972
  • 8
  • 44
  • 73