Wednesday, January 2, 2008

comparing objects with nulls

When trying to test an object to see if it's null or not (for good error handling purposes), it's good to know: a null object's .equal method doesn't measure up to a null. ie, you can't do this:



String s = null;
String r = null;

possiblySetMyString(r);

if(s.equals(null)){
System.out.println("string not set");
throw new RuntimeException();
}else{
System.out.println(s);
}

public void possiblySetMyString(String t){
s = t;
}



Nope! That won't work. you can't check if a string 'equals' null with the object's .equals method , because it's going to try to compare various String parameters to a null. Instead, replace the s.equals(null) with s==null.
Note: use == to check for primatives (int, char, bool, null etc), and use .equals to compare two objects. If you're comparing two different types, better convert before comparing.

No comments: