简体   繁体   中英

if (str1 == null) when throws a NullPointerException

In java, Does the following line have a possibility (even 0.01%) to throw a NullPointerException??

public static void handleRequest(String str1){
   if (str1 == null){  // this line throws NPE, how come !! is it a JDK1.5 bug!!
        return null;
   }
   // other staff
}

Actually I am falling some bug in the code and It says that the exact above line in the method throws a java.lang.NullPointerException ?!

No, that line won't throw a NullPointerException under any circumstances.

But it depends what you mean by "similar". For example, if your actual line of code is

if (foo.str1 == null)

then you'll get a NullPointerException if foo is null.

if (str1 == null)  

will not throw a NullPointerException.

if(str1.equals(null)) 

does have that possibility.

EDIT:

If the line above is referenced by your stack trace, there is a very real chance that the code you are running does not match the code that you are looking at. This could happen if you made modifications to the class after you compiled and deployed it, resulting in mis-matched line numbers.

No,

if (str1 == null)

cannot throw a null pointer exception as no pointer is dereferenced.

The similar

if (obj1.getStr1() == null)

can throw a NPE in the case that obj1 == null, or,

if (str1 == null && str1.length() == 0)

will throw a NPE on str1.length() when str1 == null. (In this case the || operator should have been used.)

Can you show the exact line on which it breaks and include the stacktrace?

If you have byte code manipulation, eg in OSGi components the field access can be replaced with proxied getter methods. If you access a field after the underlying component has been discarded, the fields access throws an NPE because it has been replaced with the following and the thisObject is set to null.

if (thisObject.getStr1() == null)

BTW: I had a bug relating to this very problem today. :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM