Re: when using equals method with a null string...



On Fri, 10 Mar 2006 07:22:03 -0800, minjie wrote:

If I have declared 2 strings as follows:
private String myStr1 = "";
private String myStr2 = "";
and somewhere in the application they may or may not get assigned
values. When I do
if (myStr1.equals(myStr2))
....
I will get an exception if myStr1 is null. How do I test it without
using
if (myStr1 != null)
if (myStr1.equals(myStr2))
....
?
I have a lot of string comparisons like the above, and if I have to
test one by one like that, it's a lot of code!
Thanks.
I've just tried this code in Java 1.4 and 1.5
public class testCode{
public static void main (String[] args){
String s = "";
String y = new String("");
System.out.println("Tony equals string y"+ y.equals("Tony"));
System.out.println("Tony equals string s"+ s.equals("Tony"));
}
}
and it compiles and runs with no problems. I don't get a null pointer at
all. I can't get one with an if statement either.

Tony


.



Relevant Pages