Jump to content

Difference bewtween exists() and !null?


Snowydell

Recommended Posts

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
Link to comment
Share on other sites

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 :)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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