2004-03-15-2011Z


One more thing: never use '==' or '!=' to test string equality in java. It tests if the java.lang.Object instances are the same object, not if the strings are lexically the same. What you probably want is:
if (s1.compareTo(s2) != 0) { System.err.println("different!"); }

(updated later)

Nope, maybe not. Similar code is failing in my app. But then, this works as expected:

jcomeau@notebook /tmp
$ cat teststrings.java
public class teststrings {
 public static void main(String[] argv) {
  System.err.println("comparing " + argv[0] + " to "
   + argv[1] + ": " + argv[0].compareTo(argv[1]));
  System.err.println("now with String.equals(): " + argv[0].equals(argv[1]));
 }
}

jcomeau@notebook /tmp
$ java teststrings this that
comparing this to that: 8
now with String.equals(): false

jcomeau@notebook /tmp
$ java teststrings this this
comparing this to this: 0
now with String.equals(): true

Back to blog or home page

last updated 2013-01-10 20:15:28. served from tektonic.jcomeau.com