Jump to content

Difference bewtween exists() and !null?


Recommended Posts

Posted (edited)

I'm using this npc.exists(). I don't know to use exists() or != null. Or maybe even both if they are different?

They are indeed different.

npc != null is referred to as a "null check". npc.exists() is a call from an object through a variable.

 

npc is a "reference variable" - a variable used to "point" to an object. When a reference variable does not point to an object, it points to "null".

 

The object contains the actual exists() method, not the variable. If npc is not pointing to an object, it cannot properly call the method, resulting in a NullPointerException.

 

Unless you are 100% sure npc will not contain null, you do not need the null check. Although, if there's a possibility it will be null, you need the null check before you attempt to call npc.exists().

 

This is basic Object Orientation. If you'd like to know more, feel free to message me :) (don't be shy)

Edited by fixthissite
  • Like 2
Posted

They are indeed different.

npc != null is referred to as a "null check". npc.exists() is a call from an object through a variable.

 

npc is a "reference variable" - a variable used to "point" to an object. When a reference variable does not point to an object, it points to "null".

 

The object contains the actual exists() method, not the variable. If npc is not pointing to an object, it cannot properly call the method, resulting in a NullPointerException.

 

Unless you are 100% sure npc will not contain null, you do not need the null check. Although, if there's a possibility it will be null, you need the null check before you attempt to call npc.exists().

 

This is basic Object Orientation. If you'd like to know more, feel free to message me smile.png (don't be shy)

Thank you I appreciate the help :)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...