-1

I have an if statement that takes a string, and if another string has the same value as that string do 1 thing, and if the variable doesnt equal that string do another thring

here is my code

if(Pos != "D"){
                System.out.println("doesnt = D");
            }

 if (Pos == "D" ){//WHY ISNT THIS WORKING
                System.out.println("it does = D");
                    }

It recognizes when the variable doesnt = D and prints "doesnt = d" but when the variable = D it does nothing. I dont know why.

thanks

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user222786
  • 547
  • 4
  • 7
  • 17

1 Answers1

3

Never compare Strings with == or != since these check to see if two String variables refer to the same object reference, and this is not what you're interested in. Instead use the equals(...) or equalsIgnoreCase(...) method to see if the two Strings have the same chars in the same order as that's what really matters here. i.e.,

Use equals to compare strings :

if ("D".equals(Pos))
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758