I am having a
Exception in thread "main" java.lang.NullPointerException
whenever I ran my small program. Below is three of the files from my simple code:
The exception happens on pizzaType_.add(type); from Pizza.java. Can anyone tell me what is wrong with the code and why I am getting an exception.
Here is where I made a mistake on. On Pizza.java, I had declared two class attribute called toppings_ and pizzatype_ of type ArrayList. When I created the constructor, I allocated/created memory (new) for those two attributes however, I made a mistake where I did declare toppings_ and pizzatype_ again inside the constructor. What happen next is when I used those two inside the class i.e. pizza:: order(), it ran out of scope thats why the compiler was telling me that the pointer where null.
The compiler was not able to recognize the declaration twice(Always blame someone else for my mistake lmao).
Hmmm. I wonder what would have happen if I move the class attribute below the contructor?
Please correct me if I am wrong, I do not know much.
Joined: Oct 13, 2005
Correct. If you declare the identifiers again inside the constructor (or a method) you end up with a local variable. Most programming languages permit local variables with the same name as "non-local" variables. Whether that is a good thing, I am never quite sure.
By moving the class attribute, do you mean what difference would it make if you declared the fields last in the class? Or something similar? Try it. I think you will find it makes no difference at all.
A similar problem people sometimes get is with set methods like thisTry it. See what happens. See how you can correct the error.
You need to pick up the knowledge of local variable, instance variable (non-static) , class variable (static).
Also, clarify the concept on when does this three different variable initialize and destroyed (out of scope),
so it will help you understand and build the strong foundation.
SCJP 6, SCWCD 5, SCBCD 5
Joined: Oct 13, 2005
One of the things about field declarations is that their location is of no grammatical significance. If you got an exception when the declaration preceded the constructor, you will suffer the same exception if the declaration follows the constructor.
I didn't see anything about local variables in the Java Tutorials, but you can try the Java Language Specification (JLS) (here is the index: would you believe try under "L"). Warning: the JLS is by no means easy reading.