0
**public void testCompareTo() {
    System.out.println("compareTo");
    Patient p = null;
    Patient instance = null;
    int expResult = 0;
    int result = instance.compareTo(p);
    assertEquals(expResult, result);
}**

Is there a way to call a method in a null object or do I have to do an Exception here?

0

3 Answers 3

3

No, you can't call a non-static method on a null object, since that would cause a NullPointerException.

You must verify that instance is not null before calling instance.compareTo(p).

Sign up to request clarification or add additional context in comments.

4 Comments

Actually, semantically this is not true. What you mean is that calling any method on a null object will ALWAYS throw a NullPointerException
Is there a way to set a value for the variable "result"?.If I can't call compareTo and without changing the values of and 'p' and 'instance'
@T.J.Crowder That's interesting to know. I never tried to call a static method through a null object reference. Then again, I try not to call static methods though an object reference, so it's not a surprise I never tried it.
@user3133474 You can initialize it to a default value and then assign to it the result of compareTo if instance != null. Or you can use the new Optional class introduced in Java 8.
0

NullPointerException is inevitable in this case as java can not get any reference from a null object, which makes it obvious to throw a NullPointerException

Comments

0

null objects by definition are... nothing. You can't invoke an instance level method on a null object without causing a NullPointerException.

7 Comments

"You can't invoke anything on a null object without causing a NullPointerException" You can, you know: A static method. (Bizarre but true.)
You're technically invoking the method on the Class, not the object.
Yes, quite true. You're using the variable/data member (e.g., that's how the compiler figures out what class is relevant), but not an object.
Having just tested it, I didn't realize that at run time, a null instance.someStaticMethod() won't cause a NPE. Learned something today.... something... pretty useless :).
It is indeed (useless, I mean). :-) The bytecode even goes to the trouble of reading the value from the variable first, before...not using it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.