05 July 2011

Java String comparison

A common mistake you might make when doing Java string comparison is like this:

String s = "abs";
String t = "cde";

// test for pointer equality, in other words,
// test if s and t are the same object
if (s == t)

What you really want to do might be this:

if (s.equals(t)) // compare characters in two strings

However in python, s==t is actually what you want. When you know too many programming languages, you can easily mess up the syntax and semantics of them accidentally. Be careful.

No comments: