简体   繁体   中英

Why is this throwing a null pointer exception?

I have the following piece of code inside a for loop

MyClass myobj= new MyClass(customers, price);
System.out.println(myobj);
if (!myobj.equals(null)) { //same happesn with myobj != null
    System.out.println("not null");
}
myMethod(myobj);

myMethod body is:

private void myMethod(MyClass myobj) {
   if (myobj.totalDemand()) {
      //bla bla
   }

After running the code in Junit the line "if (myobj.totalDemand())" throws a NullPointerException, however the console prints "not null"

If you call myobj.equals(null) , there's no guarantee that the implementation of equals() for the class will not throw a NullPointerException , and if myobj is null , you'll get a NullPointerException trying to invoke .equals() on a null object.


To test for null , use this code:

if (myobj == null)

and to test for not null, use this:

if (myobj != null)

If myobj is null you will get NullPointerException, and if it's not console will print out "not null". So, is there anything in variables customers and price in EVERY invoke cycle ?

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