2

When I try to compare strings in Apex, for example '1a' < '-a', this statement returns true while in other languages, like Javascript, '1a' < '-a' is returning false.

However, '2a' is bigger than '-a'.

Is lexographic sorting implemented in apex in a different way than in other languages?

Why?

1 Answer 1

5

In Apex, == is a case-insensitive, locale-aware comparison of strings. That means that 'Hello' == 'hello' returns true. If something is equal to something else, neither are greater than or less than the other. In order to be internally consistent (because a == b and a < b and a > b cannot all be true at once), all comparison operators that work on strings are case-insensitive, locale-aware comparisons. This guarantees that only one of ==, <, and > will ever be true for two given input strings.

In many other languages, 'Hello' == 'hello' returns false. This is because they use a code-point comparison algorithm. Every character you can possibly see (and some you can't) have a numeric value called its "code point." For example, H is 72, while h is 104. That means that 'Hello' < 'hello' is true, because 72 is less than 104, and 'Hello' > 'hello' is false, because 72 is not greater than 104. As a logical conclusion from this, you should be able to see why Apex and other languages work differently, because their definition of == is different.

Consult the following truth table to see how Apex differs from JavaScript.

Condition JavaScript Apex
'Hello' == 'hello' false true
'Hello' != 'hello' true false
'Hello' < 'hello' true false
'Hello' > 'hello' false false
'Hello' <= 'hello' true true
'Hello' >= 'hello' false true

In addition, sorting is done in a sort of "dictionary" order in Apex. That means that letters and numbers come before punctuation, where numbers come before letters. I don't know of a specific document that calls out the specific order of punctuation, but just be aware that sorting in Apex is different than most other languages on purpose. It's meant to be meaningful in the context of a case-insensitive, locale-aware comparison way.

2
  • well, in my case this statement that letters and numbers come before punctuation, where numbers come before letters. doesn't hold true, since punctuation '-' is coming between 1 and 2. Is this another internal salesforce bug?
    – Patlatus
    Jan 20, 2023 at 11:12
  • @Patlatus That's not what I'm observing. both '1a' and '2a' are less than -a when I write some code. Maybe there's something you're missing? Can you post a concrete example that we can use to replicate in another org?
    – sfdcfox
    Jan 20, 2023 at 14:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .