0

I am attempting to read from a file in Java, and use the string I get as a condition in an if statement. I know the reader is correct (it works in other programs), but when I try to do something like

if(reader.getVariable() == "A") {
    do x
}
else {
    do y
}

It will always do y, even though printing out the getVariable() method returns "A". Why is this?

Michael Liu
  • 52,147
  • 13
  • 117
  • 150

2 Answers2

1

In Java, always use the equals method to check whether two strings have the same value:

if(reader.getVariable().equals("A")) {

The == operator doesn't work because it checks whether two strings are the exact same instance, which they aren't in this case.

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
1

To compare strings in java, you should use the equals() method.

Rndm
  • 6,710
  • 7
  • 39
  • 58