function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
philbophilbo 

Apex and Case Insensitivity = 99 44/100% Pure

Hey,

An interesting little quirk related to case insensitivity in Apex.  If you go

String s1 = 'a';
String s2 = 'A';
system.debug ( s1 == s2 );


...it'll say 'true' as you'd expect.

But now do this:

Set<String> s = new Set<String> { 'a' , 'b' };
System.debug ( s.contains ( 'a' ) );
System.debug ( s.contains ( 'B' ) )
;

...the second debug statement says 'False'; in other words, you cannot find that second set element by 'B'.

Thus - this little corner of Apex is case-sensitive.   The same thing applies to Map keys, which makes sense, as they're probably implemented similarly under the sheets.

This can be used to your advantage if you need to do a case-sensitive compare between strings:

static boolean streq ( String a , String b ) {
    Set<String> s = new Set<String> { a };
    return ( s.contains ( b ) );
}


-philbo

EJWEJW
Almost all, if not all, method calls on built-in objects are case sensitive. The only default case insensitive behavior appears to be the == and != operators. Even 18 character IDs are not case insensitive when doing SOQL queries unfortunately.
philbophilbo
A case in point, and this one is somewhat more perverse. 

From my original example,

String s1 = 'a';
String s2 = 'A';
system.debug ( s1 == s2 );

spits out 'True'.  The '==' operator is case insensitive.

But now go:

system.assertEquals ( s1 , s2 );

and lo and behold - it throws an error.  Clearly the assertEquals method is case sensitive.

Derek Wiers (W)Derek Wiers (W)
I know this is a SUPER old post and all, but just wanted to chime in for posterity and for other users:
String s1 = 'a';
String s2 = 'A';
String s3 = 'a';
System.debug(s1.equals(s2));
System.debug(s1 == s2);
System.debug(s1.equals(s3));

This will print false, true, and true, denoting that '==' is case insensitive, but .equals() is case sensitive.  Given this behavior, it would seem that internally the set.contains() method is using .equals() for comparison.  In any case - don't bother trying to implement your own case-sensitive string equals function - just use .equals().