0

I was working on a POC and as a process of which I ran into a weird issue of comparing two strings differently gives different results. I might be missing something simple but wanted to see if there is really a difference. Following is the piece of code I'm executing anonymously.

string a = 'Cancel';
string b = 'Cancel';

system.debug(' sample test:'+ a == b);
system.debug(a == b);

I expected to get the same results since the comparison I'm doing is the same. The only difference is I'm using a debug identifier and not an identifier in the second log.

Results:
system.debug(' sample test:'+ a == b); -- false
system.debug(a == b); -- true

Am I missing anything here?

1
  • 4
    concatenation + has a higher priority than comparing ==, First in concatenates sample test: + Cancel. Second, it checks it this concatenation equals b – Oleksandr Berehovskyi Nov 14 '19 at 21:20
2

I think because it is concatenating ' sample test:'+ a as a part of the left side evaluation of the == sign. If you do this:

string a = 'Cancel';
string b = 'Cancel';

system.debug(' sample test:'+ (a == b)); //notice parens to encapsulate evalutions of '=='
system.debug(a == b);

you will get this:

16:18:04.16 (16575910)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
16:18:04.16 (16921691)|USER_DEBUG|[4]|DEBUG| sample test:true
16:18:04.16 (16944462)|USER_DEBUG|[5]|DEBUG|true
16:18:04.16 (16998145)|CODE_UNIT_FINISHED|execute_anonymous_apex
16:18:04.16 (19048919)|EXECUTION_FINISHED
2
  • 2
    Another way to get around the concatenation would be to store the boolean in a separate variable, and pass the variable into the debug statements. – Nicholas Savini Nov 14 '19 at 21:21
  • gotcha, thank you – Anurag Nov 15 '19 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.