Posted: 26 Feb 2018 0:42 EST Last activity: 27 Feb 2018 17:57 EST
String comparisons in Pega
Within data transforms, is there any difference in using @equals and == between string properties and/or string literals?
I understand that in Java, using == will compare the object reference even if the contents are identical. But in Pega (and correct me if I'm wrong) it will always compare contents and never the object reference.
I've had LSA/SSA's strongly believe that I should never use == to compare strings in data transforms, and others who believe it is perfectly fine.
Any thoughts on why I would use one over another? On looking at the Java code of @equals I can use it to avoid having to check whether the property has been set (null). It always returns false when one is null. Other than that, am I missing anything else when using == ?
To my knowledge, it is always advisable to use @equals (if you are motive is to compare the value of theStrings).
Using == might still work for few strings because when we give a String a "value", it is not exactly creating an object, it is actually placing it in the String pool, and another same string (say String2) will find the same reference in the pool (Please mind that the String2 is not a new object.)
But in case when you try to use 2 different String instances, then you logic will fail.
Because String instances get evaluated character by character (value evaluation) when @equals is used for comparison.
So, String a = new String("Test1");
String b = new String("Test1");
Would evaluate to true if equals is used (This is the expected behavior).
Would evaluate to false if == is used.
Please note that, if == evaluates to true then .equals evaluates to true for sure.
But, if .equals evaluates to true, there is no guarantee that == evaluates to true.
Hence, as per my understanding,
Use equals when you want to compare values of the String and
== when you want to evaluate the equality on the instance and memory address.