Comparing Strings: For java programmers PDF Print E-mail
User Rating: / 0
PoorBest 
Sunday, 08 March 2009
HTML clipboard

The Java Days

Consider the following code:

String s1 = "hello";
String s2 = "hello";
if (s1 == s2) System.out.println("equal");

As you might expect, the Java program prints out "equal". Now consider this:

String s1 = "hello";
String
s2 = "he"; s2
+= "llo"; // s2
is now "hello" if (s1 == s2) { System.out.println("equal"); } else { System.out.println("not equal"); System.out.println(s1); System.out.println(s2); }

Strange as it might seem, this snippet prints out "not equal" followed by "hello" and "hello". Even though the two strings have the same value, their references are different. To get around this, Java programmers would have to use the equals methods: s1.equals(s2). Of course, you can't expect the newbies to know this...

Enter C#

The C# designers realized that String == String usually meant comparison of values rather than of references. Hence, this is now the default behavior in C#. The Java program above that printed "not equal" will print "equal" in C#. This makes quite a lot of sense, since its quite rare to compare String references. Of course, if you would like to do that in C#, it's still an option by casting the strings to objects:

if ((object) s1 == (object) s2)
{
// compares references of s1 and s2
}

Conclusion

C# makes comparing strings easy even for a novice programmer and without sacrificing flexibility. The compiler is smart enough to realize that the == operator, when used with Strings, compares values rather than references. The option to compare references, of course, is still open to the programmer.

 
< Prev   Next >
School Joomla Templates and Joomla Tutorials