0

I am trying the following code in Android Studio. When Debugging, I find out that even when Value of variable B is "(" my if statement does not execute and hovering over it, it shows it is false (please refer to image). The value of ScreenText in this case is "6(".

Any help is appreciated.

.enter image description here

alex jones
  • 37
  • 4

4 Answers4

2

You should compare strings with the .equals() method. In this case, and to prevent a null pointer exception in case that your B variable is null, you should do so like this:

if("(".equals(B)) {
...
}
Luis Miguel Serrano
  • 5,029
  • 2
  • 41
  • 41
1

The == operator is used for reference comparison, to check whether two object have the same reference.

You want to compare two Strings, use the boolean equals(String) method.

if( "(".equals(B)) {
// your logic
}

Here comparing B with "(" constant does not require you to make null checks.

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
0

I think a more generic way to compare strings in Android is:

TextUtils.equals(B, "(");

And by the way, in your code

String.valueOf(c).toString();

toString() is redundant.

Xiaoyu Yu
  • 725
  • 3
  • 12
0

If you want to compare the value or contents of two strings then use .equals().

if(string.equals("(")){
    //Enter your code
}

But if you want to check that two object points to same reference then use ==

BeingMIAkashs
  • 1,375
  • 11
  • 18