java - Null pointer exception in array initialized to null -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
this following code. have make array null purpose, when initialize array components 1, shows null pointer exception. how handle this?
public static void main(string[] args) { double[] a; a=null; if(a==null) for(int i=0;i<12;i++) a[i]=1; }
you need create array object , assign array variable before trying use variable. otherwise creating definition of nullpointerexception/npe: trying use (dereference) reference variable refers null.
// constant avoid "magic" numbers private static final int max_a = 12; // elsewhere in code if (a == null) { = new double[max_a]; // need this! (int = 0; < a.length; i++) { a[i] = 1.0; } }
Comments
Post a Comment