

So you have a reference to something that does not actually exist. The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException. You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null). Reference variables can be set to null which means " I am referencing nothing". Now here is where things get interesting. All primitives have to be initialized to a usable value before they are manipulated. These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y.
JAVA STACK OVERFLOW ERROR EXAMPLE CODE
For example variables of type Object are references.Ĭonsider the following code where you declare a variable of primitive type int and don't initialize it: int x By convention reference types are usually denoted with a type that starts in uppercase. to access a method or field, or using [ to index an array. If you want to manipulate the Object that a reference variable refers to you must dereference it. References: variables that contain the memory address of an Object i.e. For example variables of type int or char are primitives. By convention primitive types start with a lowercase letter.


If you want to manipulate the data in a primitive variable you can manipulate that variable directly. There are two overarching types of variables in Java:
