exception - Why does Java throw NullPointerException here? -


public class test {      public int [] x;      public test(int n)     {        int[] x = new int [n];        (int i=0;i<x.length;i++)        {            x[i]=i;            stdout.println(x[i]);        }     }       public static void main(string[] args) {           string path = "/users/alekscooper/desktop/test.txt";         in reader = new in(path);         int size=reader.readint();         stdout.println("size = "+size);          test n = new test(size);         stdout.println(n.x[3]);      }      /* add code here */  } 

hello guys. i'm learning java through reading robert sedgwick's book on algorithms , i'm using libraries such stdout, example. question java in general. don't understand why java here throws nullpointerexception. know means in general, don't know why here because here's think i'm doing:

  1. read integer number file - size of array in class test. in test example size=10, no out-of-bound type of thing happens.

  2. print it.

  3. create object n of type test. in object think create array of size have read file. fun initialize 0 size-1 , print it. far good.

  4. and here begins. since class public , i've run constructor think have object n attribute has array x size elements. however, when i'm trying address x, example,

    stdout.println(n.x[3]);

    java throws nullpointerexception.

why so? please , thank time.

what did called shadowing shadowed field x local variable x. need avoiding this:

int[] x = new int [n]; wrong, if want field initialize instead of local variable : x = new int [n]; more information read this


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -