"stringObj == null" vs "stringObj.equals(null)", for null check??

"stringObj == null" vs "stringObj.equals(null)", for null check??

Post by qazmlp120 » Thu, 30 Mar 2006 18:08:56


As I am aware, it is required to use equals() method(and not '==') for
equality comparision of two String objects.
But, what exactly is recommended for 'null' check?
if( stringObj == null )
or
if( stringObj.equals( null ) )
 
 
 

"stringObj == null" vs "stringObj.equals(null)", for null check??

Post by Timb » Thu, 30 Mar 2006 18:18:21


If stringObj is null, then the second one (using .equals) will
throw a NullPointerException, because you are attempting to
dereference a null pointer. So, the first one should be used.

 
 
 

"stringObj == null" vs "stringObj.equals(null)", for null check??

Post by Thomas Sch » Thu, 30 Mar 2006 18:40:47


A String object cannot be null, only a String reference can be null.
You are testing if the String reference is null, so ...
Anyway, if stringObj was null the equals() version would throw a NPE...
 
 
 

"stringObj == null" vs "stringObj.equals(null)", for null check??

Post by weirongha » Thu, 30 Mar 2006 19:51:49

stringObj == null
 
 
 

"stringObj == null" vs "stringObj.equals(null)", for null check??

Post by Roedy Gree » Fri, 31 Mar 2006 04:46:27

On 29 Mar 2006 01:08:56 -0800, XXXX@XXXXX.COM wrote, quoted
or indirectly quoted someone who said :


the first is preferred. The second would likely like blow up with a
null pointer exception since people don't always defend against sort
of thing.
--
Canadian Mind Products, Roedy Green.
http://www.yqcomputer.com/ Java custom programming, consulting and coaching.
 
 
 

"stringObj == null" vs "stringObj.equals(null)", for null check??

Post by Mike Schil » Fri, 31 Mar 2006 07:37:57


"Roedy Green" < XXXX@XXXXX.COM > wrote in


That is, the second one will always NPE is stringObj is null, and possibly
even if it isn't.