May 29, 201510 yr Author What situation are you referring to? Not all classes define an exists method I'm using this npc.exists(). I don't know to use exists() or != null. Or maybe even both if they are different?
May 29, 201510 yr 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 May 29, 201510 yr by fixthissite
May 29, 201510 yr Author 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) Thank you I appreciate the help .
Create an account or sign in to comment