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

Q

qazmlp1209

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 ) )
 
T

Timbo

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 ) )
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.
 
T

Thomas Schodt

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 ) )

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...
 
R

Roedy Green

But, what exactly is recommended for 'null' check?
if( stringObj == null )
or
if( stringObj.equals( null ) )

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.
 
M

Mike Schilling

Roedy Green 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.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top