Thursday, July 25, 2013

Equality in programming languages

Something as simple as comparing two values in a programming language can get you in trouble.

For example, in Perl:

my $name1 = "dennis";
my $name2 = "fred";

print "The names are the same" if ($name1 == $name2);  ## danger Will Robinson!!

Guess what prints out? The == is numeric comparison in Perl. If you want to compare strings you need to use the eq operator.

This is why you should always put:

use strict;
use warnings;

In the beginning of your Perl program. These will warn you about such problems.

In Java, you have to be careful when you check string equality:

if (string1 == string2) {
   // do something
}

The == operator may not work as expected depending on the source of the strings, as == does not compare the values of the two strings. You really want to use the .equals method:

if (string1.equals(string2)) {
   // do something
}

The .equals method will actually compare the values of the two strings.



No comments:

Post a Comment