devxlogo

Code Generates Null Pointer Exception

Code Generates Null Pointer Exception

Question:
If I have:

class point { double x,y; }  &  import point;  class test {        public static void main(String args[])        {         point[] P = new point[10];        P[0].x = 5;        P[0].y = 34874;        } } 
it generates a null pointer exception. Why?

Answer:
Try:

P[0] = new Point();   P[0].x = 5;   etc. 
Your array declaration allocates an array large enough to holdonly 10 pointers to points. Space to hold each point must be allocatedseparately.

devx-admin

Share the Post: