If (str1 == null) when throwing a NullPointerException

In java, does the following line (even 0.01%) have the ability 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 for an error in the code and says that the line exact

above in the method is throwing java.lang.NullPointerException ?!

+2


a source to share


4 answers


No, this line will not be thrown NullPointerException

under any circumstances.

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



if (foo.str1 == null)

      

then you will get a NullPointerException if foo

null.

+19


a source


if (str1 == null)  

      

will not throw a NullPointerException.

if(str1.equals(null)) 

      



has such an opportunity.

EDIT:

If the above line refers to your stack trace, there is a very real chance that the code you are using does not match the code you are looking at. This can happen if you made changes to the class after compilation and deployment, resulting in incorrect line numbers.

+10


a source


No,

if (str1 == null)

      

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

Similar

if (obj1.getStr1() == null)

      

can call NPE if obj1 == null, or,

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

      

will call NPE on str1.length () when str1 == null. (In this case, the operator must be used ||

.)

Can you show the exact line it breaks on and enable the stack?

+4


a source


If you have a byte code manipulation for example. in OSGi components, access to fields can be replaced with proxy methods. If you access a field after the underlying component has been discarded, accessing the fields calls NPE because it has been replaced with the following and this object is set to null.

if (thisObject.getStr1() == null)

      

BTW: I had an error related to this problem today.: P

+3


a source







All Articles