Hi everyone. Here’s a quick post that might save you a lot of time. With some programming languages like JavaScript, @Formula or LotusScript, to compare a String value is pretty simple
| @Formula: tmp1 := “Test”;
tmp2 := “Test”; (tmp1 = tmp2) = True
|
JavaScript:var tmp1 = “Test”;
var tmp2 = “Test”; (tmp1 == tmp2) = True
|
LotusScript:dim tmp1 as String
dim tmp2 as Stringtmp1 = “Test” tmp2 = “Test” if(tmp1 = tmp2) = True |
But when it comes to Java, the rules are slightly different:
String tmp1 = “Test”;
String tmp2 = “Other Test”;
(tmp1 == tmp2) = True
In Java, the == operator compares Objects and not the physical values contained within. The line above this is checking if the object tmp1 is the same object as tmp2.
So, in Java, the proper way to compare values is by using the equals() method:
String tmp1 = “Test”;
String tmp2 = “Test”;
(tmp1.equals(tmp2) = True
If it’s anything that I can teach you today, it’s that with Java almost everything is an Object and not just a data type. If it’s an Object, it has Properties and Methods that should be considered at all times, especially when parsing or comparing values.
Cheers for now
John
I am sorry, but you are not right. If you compare two string literals the “==” operator will return true. If you do not believe try your own code. The reason for this is that equal String literals share the same Object. So the reference tmp1 points to the same object in the heap then tmp2.
But you are right that it is much saver to use the .equals() method to compare Strings, because if you do not use String literals in your comparison the “==” operator will not work reliable.
But you should not do
(tmp1.equals(tmp2.toString())
The correct way is
tmp1.equals(tmp2)
Because if you use tmp2.toString() there will be difficult to find bugs in your program if tmp2 is not a String. If you remove .toString() the compiler will throw an error if tmp2 is not a String.
Hi Ralf. Thanks for your feedback, and thank you for correcting me on that point.
My Java skills are not yet what I want them to be, but it’s getting close. Your feedback is much appreciated. I’ll amend my Blog post to reflect accordingly
If it’s anything that I can teach you today, it’s that with Java almost everything is an Object and not just a data type. What an excellent blog!