Re: Catching invalid string comparisons
Ulrich Eckhardt wrote:
Greetings!
I guess many of you have already seen code (especially from C++ programmers)
like the following:
String s = someFunction();
if(s == "0")
doThis();
else
doThat();
I wonder, is there a way to catch such comparisons where a non-fundamental
type is compared to a constant? I'm actually looking for a way to avoid
errors that occur due to this, maybe a warning when a comparison is done
for identity where one of the two sides required boxing (Is that the term?)
first.
There is no boxing with Strings, and String is a pretty fundamental type, so
I'm not quite sure I get these comments. Anyhow, it's usually a mistake to
compare String values with ==, except when comparing against null. It's such
a common mistake that IDEs include an option to warn you of it.
Further, I wonder about this case:
Integer n = otherFunction();
if(n == 42)
dontPanic();
Other than the above, I haven't actually tried it, but I would expect this
code to also not do what a naive programmer would expect.
What would a naive programmer expect? What do you expect this snippet to do?
I got absolutely no information from the cited sentence, lacking those details.
Just for the record, in case you didn't spot the problem in above code, this
is how the above should be written:
if(s.equals("0")) ...
if(n.equals(42)) ...
The 's' case is correct, but the 'n' case is just silly.
// Note: I'm not sure about the latter.
The reason is that '==' determines identity for objects while it determines
equality for builtin types like 'int' (please correct me if I'm wrong or if
this explanation is misleading in any way).
String is a built-in type also.
<sscce name="testit/Boxer.java" >
package testit;
public class Boxer
{ private Boxer(){}
public static Integer makeInteger( int value )
{
return new Integer( value );
}
public static void main(String[] args)
{
System.out.println();
Integer n = makeInteger( 17 );
System.out.println( n.toString() + " == 17? "+ (n == 17) );
n = makeInteger( 16385 );
System.out.println( n.toString() + " == 16385? "+ (n == 16385) );
n = makeInteger( 123456789 );
System.out.println( n.toString() + " == 123456789? "+ (n == 123456789) );
}
}
</sscce>
Output:
17 == 17? true
16385 == 16385? true
123456789 == 123456789? true
--
Lew