Java NullPointerException 2D array initialized in constructor, but method refuses to acknowledge
<p>I've run into a strange instance of NullPointerExceptionwhere I run the following code,</p>

<pre><code>Graph_img g = new Graph_img(3,4);
g.randomGraph();
</code></pre>

<p>where the constructor and method are the following,</p>

<pre><code>public Graph_img(int width, int height){
    super();
    w = width;
    h = height;
    Node[][] Img = new Node[w][h];
}

//generate new MRF graph ~75% 0 bilevel
public void randomGraph(){
    V = new ArrayList&lt;Node&gt;(0);
    E = new ArrayList&lt;Edge&gt;(0);
    for(int x=0; x&lt;w; x++)
        for(int y=0; y&lt;h; y++){
            if(Math.random()&gt;0.75)
                Img[x][y] = new Node(x*h+y,1,2); //&lt;--- NullPointerException
            else
                Img[x][y] = new Node(x*h+y,0,2); //&lt;--- NullPointerException
            V.add(Img[x][y]);
        }
}
</code></pre>

<p>But if I run with the initialization moved to the method instead of the constructor,</p>

<pre><code>public Graph_img(int width, int height){
    super();
    w = width;
    h = height;
    //Node[][] Img = new Node[w][h]; &lt;-- MOVING THIS
}

//generate new MRF graph ~75% 0 bilevel
public void randomGraph(){
    V = new ArrayList&lt;Node&gt;(0);
    E = new ArrayList&lt;Edge&gt;(0);
    Node[][] Img = new Node[w][h]; //&lt;-- MOVED HERE
    for(int x=0; x&lt;w; x++)
        for(int y=0; y&lt;h; y++){
            if(Math.random()&gt;0.75)
                Img[x][y] = new Node(x*h+y,1,2);
            else
                Img[x][y] = new Node(x*h+y,0,2);
            V.add(Img[x][y]);
        }
}
</code></pre>

<p>Then everything works.  I am perplexed - why?  Thanks - Steve</p>
